code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
'use strict';
var clear = require('es5-ext/array/#/clear')
, eIndexOf = require('es5-ext/array/#/e-index-of')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, ee = require('event-emitter')
, Symbol = require('es6-symbol')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, Iterator = require('./lib/iterator')
, isNative = require('./is-native-implemented')
, call = Function.prototype.call, defineProperty = Object.defineProperty
, SetPoly, getValues;
module.exports = SetPoly = function (/*iterable*/) {
var iterable = arguments[0];
if (!(this instanceof SetPoly)) return new SetPoly(iterable);
if (this.__setData__ !== undefined) {
throw new TypeError(this + " cannot be reinitialized");
}
if (iterable != null) iterator(iterable);
defineProperty(this, '__setData__', d('c', []));
if (!iterable) return;
forOf(iterable, function (value) {
if (eIndexOf.call(this, value) !== -1) return;
this.push(value);
}, this.__setData__);
};
if (isNative) {
if (setPrototypeOf) setPrototypeOf(SetPoly, Set);
SetPoly.prototype = Object.create(Set.prototype, {
constructor: d(SetPoly)
});
}
ee(Object.defineProperties(SetPoly.prototype, {
add: d(function (value) {
if (this.has(value)) return this;
this.emit('_add', this.__setData__.push(value) - 1, value);
return this;
}),
clear: d(function () {
if (!this.__setData__.length) return;
clear.call(this.__setData__);
this.emit('_clear');
}),
delete: d(function (value) {
var index = eIndexOf.call(this.__setData__, value);
if (index === -1) return false;
this.__setData__.splice(index, 1);
this.emit('_delete', index, value);
return true;
}),
entries: d(function () { return new Iterator(this, 'key+value'); }),
forEach: d(function (cb/*, thisArg*/) {
var thisArg = arguments[1], iterator, result, value;
callable(cb);
iterator = this.values();
result = iterator._next();
while (result !== undefined) {
value = iterator._resolve(result);
call.call(cb, thisArg, value, value, this);
result = iterator._next();
}
}),
has: d(function (value) {
return (eIndexOf.call(this.__setData__, value) !== -1);
}),
keys: d(getValues = function () { return this.values(); }),
size: d.gs(function () { return this.__setData__.length; }),
values: d(function () { return new Iterator(this); }),
toString: d(function () { return '[object Set]'; })
}));
defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues));
defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set'));
| Socratacom/socrata-europe | wp-content/themes/sage/node_modules/asset-builder/node_modules/main-bower-files/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/es6-set/polyfill.js | JavaScript | gpl-2.0 | 2,730 |
'use strict';
const TYPE = Symbol.for('type');
class Data {
constructor(options) {
// File details
this.filepath = options.filepath;
// Type
this[TYPE] = 'data';
// Data
Object.assign(this, options.data);
}
}
module.exports = Data;
| mshick/velvet | core/classes/data.js | JavaScript | isc | 266 |
package sodium
// #cgo pkg-config: libsodium
// #include <stdlib.h>
// #include <sodium.h>
import "C"
func RuntimeHasNeon() bool {
return C.sodium_runtime_has_neon() != 0
}
func RuntimeHasSse2() bool {
return C.sodium_runtime_has_sse2() != 0
}
func RuntimeHasSse3() bool {
return C.sodium_runtime_has_sse3() != 0
}
| GoKillers/libsodium-go | sodium/runtime.go | GO | isc | 322 |
<?php
interface Container {
/**
* Checks if a $x exists.
*
* @param unknown $x
*
* @return boolean
*/
function contains($x);
} | guide42/php-immutable | src/base.php | PHP | isc | 165 |
angular.module('appTesting').service("LoginLocalStorage", function () {
"use strict";
var STORE_NAME = "login";
var setUser = function setUser(user) {
localStorage.setItem(STORE_NAME, JSON.stringify(user));
}
var getUser = function getUser() {
var storedTasks = localStorage.getItem(STORE_NAME);
if (storedTasks) {
return JSON.parse(storedTasks);
}
return {};
}
return {
setUser: setUser,
getUser: getUser
}
}); | pikachumetal/cursoangular05 | app/loginModule/services/localstorage.js | JavaScript | isc | 515 |
/* eslint-disable no-console */
const buildData = require('./build_data');
const buildSrc = require('./build_src');
const buildCSS = require('./build_css');
let _currBuild = null;
// if called directly, do the thing.
buildAll();
function buildAll() {
if (_currBuild) return _currBuild;
return _currBuild =
Promise.resolve()
.then(() => buildCSS())
.then(() => buildData())
.then(() => buildSrc())
.then(() => _currBuild = null)
.catch((err) => {
console.error(err);
_currBuild = null;
process.exit(1);
});
}
module.exports = buildAll;
| kartta-labs/iD | build.js | JavaScript | isc | 591 |
function LetterProps(o, sw, sc, fc, m, p) {
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true,
};
}
LetterProps.prototype.update = function (o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if (this.o !== o) {
this.o = o;
this._mdf.o = true;
updated = true;
}
if (this.sw !== sw) {
this.sw = sw;
this._mdf.sw = true;
updated = true;
}
if (this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if (this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if (this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
this.p = p;
this._mdf.p = true;
updated = true;
}
return updated;
};
| damienmortini/dlib | node_modules/lottie-web/player/js/utils/text/LetterProps.js | JavaScript | isc | 1,212 |
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoPluginInternal.hpp"
#include "lv2/atom.h"
#include "lv2/buf-size.h"
#include "lv2/data-access.h"
#include "lv2/instance-access.h"
#include "lv2/midi.h"
#include "lv2/options.h"
#include "lv2/port-props.h"
#include "lv2/resize-port.h"
#include "lv2/state.h"
#include "lv2/time.h"
#include "lv2/ui.h"
#include "lv2/units.h"
#include "lv2/urid.h"
#include "lv2/worker.h"
#include "lv2/lv2_kxstudio_properties.h"
#include "lv2/lv2_programs.h"
#include <fstream>
#include <iostream>
#ifndef DISTRHO_PLUGIN_URI
# error DISTRHO_PLUGIN_URI undefined!
#endif
#ifndef DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE
# define DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE 2048
#endif
#define DISTRHO_LV2_USE_EVENTS_IN (DISTRHO_PLUGIN_HAS_MIDI_INPUT || DISTRHO_PLUGIN_WANT_TIMEPOS || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI))
#define DISTRHO_LV2_USE_EVENTS_OUT (DISTRHO_PLUGIN_HAS_MIDI_OUTPUT || (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI))
// -----------------------------------------------------------------------
DISTRHO_PLUGIN_EXPORT
void lv2_generate_ttl(const char* const basename)
{
USE_NAMESPACE_DISTRHO
// Dummy plugin to get data from
d_lastBufferSize = 512;
d_lastSampleRate = 44100.0;
PluginExporter plugin;
d_lastBufferSize = 0;
d_lastSampleRate = 0.0;
d_string pluginDLL(basename);
d_string pluginTTL(pluginDLL + ".ttl");
// ---------------------------------------------
{
std::cout << "Writing manifest.ttl..."; std::cout.flush();
std::fstream manifestFile("manifest.ttl", std::ios::out);
d_string manifestString;
manifestString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n";
manifestString += "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";
#if DISTRHO_PLUGIN_HAS_UI
manifestString += "@prefix ui: <" LV2_UI_PREFIX "> .\n";
#endif
manifestString += "\n";
manifestString += "<" DISTRHO_PLUGIN_URI ">\n";
manifestString += " a lv2:Plugin ;\n";
manifestString += " lv2:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n";
manifestString += " rdfs:seeAlso <" + pluginTTL + "> .\n";
manifestString += "\n";
#if DISTRHO_PLUGIN_HAS_UI
manifestString += "<" DISTRHO_UI_URI ">\n";
# if DISTRHO_OS_HAIKU
manifestString += " a ui:BeUI ;\n";
# elif DISTRHO_OS_MAC
manifestString += " a ui:CocoaUI ;\n";
# elif DISTRHO_OS_WINDOWS
manifestString += " a ui:WindowsUI ;\n";
# else
manifestString += " a ui:X11UI ;\n";
# endif
# if ! DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
d_string pluginUI(pluginDLL);
pluginUI.truncate(pluginDLL.rfind("_dsp"));
pluginUI += "_ui";
manifestString += " ui:binary <" + pluginUI + "." DISTRHO_DLL_EXTENSION "> ;\n";
# else
manifestString += " ui:binary <" + pluginDLL + "." DISTRHO_DLL_EXTENSION "> ;\n";
#endif
manifestString += " lv2:extensionData ui:idleInterface ,\n";
# if DISTRHO_PLUGIN_WANT_PROGRAMS
manifestString += " ui:showInterface ,\n";
manifestString += " <" LV2_PROGRAMS__Interface "> ;\n";
# else
manifestString += " ui:showInterface ;\n";
# endif
manifestString += " lv2:optionalFeature ui:noUserResize ,\n";
manifestString += " ui:resize ,\n";
manifestString += " ui:touch ;\n";
# if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
manifestString += " lv2:requiredFeature <" LV2_DATA_ACCESS_URI "> ,\n";
manifestString += " <" LV2_INSTANCE_ACCESS_URI "> ,\n";
manifestString += " <" LV2_OPTIONS__options "> ,\n";
# else
manifestString += " lv2:requiredFeature <" LV2_OPTIONS__options "> ,\n";
# endif
manifestString += " <" LV2_URID__map "> .\n";
#endif
manifestFile << manifestString << std::endl;
manifestFile.close();
std::cout << " done!" << std::endl;
}
// ---------------------------------------------
{
std::cout << "Writing " << pluginTTL << "..."; std::cout.flush();
std::fstream pluginFile(pluginTTL, std::ios::out);
d_string pluginString;
// header
#if DISTRHO_LV2_USE_EVENTS_IN
pluginString += "@prefix atom: <" LV2_ATOM_PREFIX "> .\n";
#endif
pluginString += "@prefix doap: <http://usefulinc.com/ns/doap#> .\n";
pluginString += "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n";
pluginString += "@prefix lv2: <" LV2_CORE_PREFIX "> .\n";
pluginString += "@prefix rsz: <" LV2_RESIZE_PORT_PREFIX "> .\n";
#if DISTRHO_PLUGIN_HAS_UI
pluginString += "@prefix ui: <" LV2_UI_PREFIX "> .\n";
#endif
pluginString += "@prefix unit: <" LV2_UNITS_PREFIX "> .\n";
pluginString += "\n";
// plugin
pluginString += "<" DISTRHO_PLUGIN_URI ">\n";
#if DISTRHO_PLUGIN_IS_SYNTH
pluginString += " a lv2:InstrumentPlugin, lv2:Plugin ;\n";
#else
pluginString += " a lv2:Plugin ;\n";
#endif
pluginString += "\n";
// extensionData
pluginString += " lv2:extensionData <" LV2_STATE__interface "> ";
#if DISTRHO_PLUGIN_WANT_STATE
pluginString += ",\n <" LV2_OPTIONS__interface "> ";
pluginString += ",\n <" LV2_WORKER__interface "> ";
#endif
#if DISTRHO_PLUGIN_WANT_PROGRAMS
pluginString += ",\n <" LV2_PROGRAMS__Interface "> ";
#endif
pluginString += ";\n\n";
// optionalFeatures
#if DISTRHO_PLUGIN_IS_RT_SAFE
pluginString += " lv2:optionalFeature <" LV2_CORE__hardRTCapable "> ,\n";
pluginString += " <" LV2_BUF_SIZE__boundedBlockLength "> ;\n";
#else
pluginString += " lv2:optionalFeature <" LV2_BUF_SIZE__boundedBlockLength "> ;\n";
#endif
pluginString += "\n";
// requiredFeatures
pluginString += " lv2:requiredFeature <" LV2_OPTIONS__options "> ";
pluginString += ",\n <" LV2_URID__map "> ";
#if DISTRHO_PLUGIN_WANT_STATE
pluginString += ",\n <" LV2_WORKER__schedule "> ";
#endif
pluginString += ";\n\n";
// UI
#if DISTRHO_PLUGIN_HAS_UI
pluginString += " ui:ui <" DISTRHO_UI_URI "> ;\n";
pluginString += "\n";
#endif
{
uint32_t portIndex = 0;
#if DISTRHO_PLUGIN_NUM_INPUTS > 0
for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_INPUTS; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
pluginString += " a lv2:InputPort, lv2:AudioPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:symbol \"lv2_audio_in_" + d_string(i+1) + "\" ;\n";
pluginString += " lv2:name \"Audio Input " + d_string(i+1) + "\" ;\n";
if (i+1 == DISTRHO_PLUGIN_NUM_INPUTS)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
pluginString += "\n";
#endif
#if DISTRHO_PLUGIN_NUM_OUTPUTS > 0
for (uint32_t i=0; i < DISTRHO_PLUGIN_NUM_OUTPUTS; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
pluginString += " a lv2:OutputPort, lv2:AudioPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:symbol \"lv2_audio_out_" + d_string(i+1) + "\" ;\n";
pluginString += " lv2:name \"Audio Output " + d_string(i+1) + "\" ;\n";
if (i+1 == DISTRHO_PLUGIN_NUM_OUTPUTS)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
pluginString += "\n";
#endif
#if DISTRHO_LV2_USE_EVENTS_IN
pluginString += " lv2:port [\n";
pluginString += " a lv2:InputPort, atom:AtomPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Events Input\" ;\n";
pluginString += " lv2:symbol \"lv2_events_in\" ;\n";
pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n";
pluginString += " atom:bufferType atom:Sequence ;\n";
# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)
pluginString += " atom:supports <" LV2_ATOM__String "> ;\n";
# endif
# if DISTRHO_PLUGIN_HAS_MIDI_INPUT
pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n";
# endif
# if DISTRHO_PLUGIN_WANT_TIMEPOS
pluginString += " atom:supports <" LV2_TIME__Position "> ;\n";
# endif
pluginString += " ] ;\n\n";
++portIndex;
#endif
#if DISTRHO_LV2_USE_EVENTS_OUT
pluginString += " lv2:port [\n";
pluginString += " a lv2:OutputPort, atom:AtomPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Events Output\" ;\n";
pluginString += " lv2:symbol \"lv2_events_out\" ;\n";
pluginString += " rsz:minimumSize " + d_string(DISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE) + " ;\n";
pluginString += " atom:bufferType atom:Sequence ;\n";
# if (DISTRHO_PLUGIN_WANT_STATE && DISTRHO_PLUGIN_HAS_UI)
pluginString += " atom:supports <" LV2_ATOM__String "> ;\n";
# endif
# if DISTRHO_PLUGIN_HAS_MIDI_OUTPUT
pluginString += " atom:supports <" LV2_MIDI__MidiEvent "> ;\n";
# endif
pluginString += " ] ;\n\n";
++portIndex;
#endif
#if DISTRHO_PLUGIN_WANT_LATENCY
pluginString += " lv2:port [\n";
pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"Latency\" ;\n";
pluginString += " lv2:symbol \"lv2_latency\" ;\n";
pluginString += " lv2:designation lv2:latency ;\n";
pluginString += " lv2:portProperty lv2:reportsLatency, lv2:integer ;\n";
pluginString += " ] ;\n\n";
++portIndex;
#endif
for (uint32_t i=0, count=plugin.getParameterCount(); i < count; ++i, ++portIndex)
{
if (i == 0)
pluginString += " lv2:port [\n";
else
pluginString += " [\n";
if (plugin.isParameterOutput(i))
pluginString += " a lv2:OutputPort, lv2:ControlPort ;\n";
else
pluginString += " a lv2:InputPort, lv2:ControlPort ;\n";
pluginString += " lv2:index " + d_string(portIndex) + " ;\n";
pluginString += " lv2:name \"" + plugin.getParameterName(i) + "\" ;\n";
// symbol
{
d_string symbol(plugin.getParameterSymbol(i));
if (symbol.isEmpty())
symbol = "lv2_port_" + d_string(portIndex-1);
pluginString += " lv2:symbol \"" + symbol + "\" ;\n";
}
// ranges
{
const ParameterRanges& ranges(plugin.getParameterRanges(i));
if (plugin.getParameterHints(i) & kParameterIsInteger)
{
pluginString += " lv2:default " + d_string(int(plugin.getParameterValue(i))) + " ;\n";
pluginString += " lv2:minimum " + d_string(int(ranges.min)) + " ;\n";
pluginString += " lv2:maximum " + d_string(int(ranges.max)) + " ;\n";
}
else
{
pluginString += " lv2:default " + d_string(plugin.getParameterValue(i)) + " ;\n";
pluginString += " lv2:minimum " + d_string(ranges.min) + " ;\n";
pluginString += " lv2:maximum " + d_string(ranges.max) + " ;\n";
}
}
// unit
{
const d_string& unit(plugin.getParameterUnit(i));
if (! unit.isEmpty())
{
if (unit == "db" || unit == "dB")
{
pluginString += " unit:unit unit:db ;\n";
}
else if (unit == "hz" || unit == "Hz")
{
pluginString += " unit:unit unit:hz ;\n";
}
else if (unit == "khz" || unit == "kHz")
{
pluginString += " unit:unit unit:khz ;\n";
}
else if (unit == "mhz" || unit == "mHz")
{
pluginString += " unit:unit unit:mhz ;\n";
}
else if (unit == "%")
{
pluginString += " unit:unit unit:pc ;\n";
}
else
{
pluginString += " unit:unit [\n";
pluginString += " a unit:Unit ;\n";
pluginString += " unit:name \"" + unit + "\" ;\n";
pluginString += " unit:symbol \"" + unit + "\" ;\n";
pluginString += " unit:render \"%f " + unit + "\" ;\n";
pluginString += " ] ;\n";
}
}
}
// hints
{
const uint32_t hints(plugin.getParameterHints(i));
if (hints & kParameterIsBoolean)
pluginString += " lv2:portProperty lv2:toggled ;\n";
if (hints & kParameterIsInteger)
pluginString += " lv2:portProperty lv2:integer ;\n";
if (hints & kParameterIsLogarithmic)
pluginString += " lv2:portProperty <" LV2_PORT_PROPS__logarithmic "> ;\n";
if ((hints & kParameterIsAutomable) == 0 && ! plugin.isParameterOutput(i))
{
pluginString += " lv2:portProperty <" LV2_PORT_PROPS__expensive "> ,\n";
pluginString += " <" LV2_KXSTUDIO_PROPERTIES__NonAutomable "> ;\n";
}
}
if (i+1 == count)
pluginString += " ] ;\n\n";
else
pluginString += " ] ,\n";
}
}
pluginString += " doap:name \"" + d_string(plugin.getName()) + "\" ;\n";
pluginString += " doap:maintainer [ foaf:name \"" + d_string(plugin.getMaker()) + "\" ] .\n";
pluginFile << pluginString << std::endl;
pluginFile.close();
std::cout << " done!" << std::endl;
}
}
| DanielAeolusLaude/DPF-NTK | distrho/src/DistrhoPluginLV2export.cpp | C++ | isc | 16,790 |
// The following are instance methods and variables
var Note = Class.create({
initialize: function(id, is_new, raw_body) {
if (Note.debug) {
console.debug("Note#initialize (id=%d)", id)
}
this.id = id
this.is_new = is_new
this.document_observers = [];
// Cache the elements
this.elements = {
box: $('note-box-' + this.id),
corner: $('note-corner-' + this.id),
body: $('note-body-' + this.id),
image: $('image')
}
// Cache the dimensions
this.fullsize = {
left: this.elements.box.offsetLeft,
top: this.elements.box.offsetTop,
width: this.elements.box.clientWidth,
height: this.elements.box.clientHeight
}
// Store the original values (in case the user clicks Cancel)
this.old = {
raw_body: raw_body,
formatted_body: this.elements.body.innerHTML
}
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
// Make the note translucent
if (is_new) {
this.elements.box.setOpacity(0.2)
} else {
this.elements.box.setOpacity(0.5)
}
if (is_new && raw_body == '') {
this.bodyfit = true
this.elements.body.style.height = "100px"
}
// Attach the event listeners
this.elements.box.observe("mousedown", this.dragStart.bindAsEventListener(this))
this.elements.box.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.box.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.corner.observe("mousedown", this.resizeStart.bindAsEventListener(this))
this.elements.body.observe("mouseover", this.bodyShow.bindAsEventListener(this))
this.elements.body.observe("mouseout", this.bodyHideTimer.bindAsEventListener(this))
this.elements.body.observe("click", this.showEditBox.bindAsEventListener(this))
this.adjustScale()
},
// Returns the raw text value of this note
textValue: function() {
if (Note.debug) {
console.debug("Note#textValue (id=%d)", this.id)
}
return this.old.raw_body.strip()
},
// Removes the edit box
hideEditBox: function(e) {
if (Note.debug) {
console.debug("Note#hideEditBox (id=%d)", this.id)
}
var editBox = $('edit-box')
if (editBox != null) {
var boxid = editBox.noteid
$("edit-box").stopObserving()
$("note-save-" + boxid).stopObserving()
$("note-cancel-" + boxid).stopObserving()
$("note-remove-" + boxid).stopObserving()
$("note-history-" + boxid).stopObserving()
$("edit-box").remove()
}
},
// Shows the edit box
showEditBox: function(e) {
if (Note.debug) {
console.debug("Note#showEditBox (id=%d)", this.id)
}
this.hideEditBox(e)
var insertionPosition = Note.getInsertionPosition()
var top = insertionPosition[0]
var left = insertionPosition[1]
var html = ""
html += '<div id="edit-box" style="top: '+top+'px; left: '+left+'px; position: absolute; visibility: visible; z-index: 100; background: white; border: 1px solid black; padding: 12px;">'
html += '<form onsubmit="return false;" style="padding: 0; margin: 0;">'
html += '<textarea rows="7" id="edit-box-text" style="width: 350px; margin: 2px 2px 12px 2px;">' + this.textValue() + '</textarea>'
html += '<input type="submit" value="Save" name="save" id="note-save-' + this.id + '">'
html += '<input type="submit" value="Cancel" name="cancel" id="note-cancel-' + this.id + '">'
html += '<input type="submit" value="Remove" name="remove" id="note-remove-' + this.id + '">'
html += '<input type="submit" value="History" name="history" id="note-history-' + this.id + '">'
html += '</form>'
html += '</div>'
$("note-container").insert({bottom: html})
$('edit-box').noteid = this.id
$("edit-box").observe("mousedown", this.editDragStart.bindAsEventListener(this))
$("note-save-" + this.id).observe("click", this.save.bindAsEventListener(this))
$("note-cancel-" + this.id).observe("click", this.cancel.bindAsEventListener(this))
$("note-remove-" + this.id).observe("click", this.remove.bindAsEventListener(this))
$("note-history-" + this.id).observe("click", this.history.bindAsEventListener(this))
$("edit-box-text").focus()
},
// Shows the body text for the note
bodyShow: function(e) {
if (Note.debug) {
console.debug("Note#bodyShow (id=%d)", this.id)
}
if (this.dragging) {
return
}
if (this.hideTimer) {
clearTimeout(this.hideTimer)
this.hideTimer = null
}
if (Note.noteShowingBody == this) {
return
}
if (Note.noteShowingBody) {
Note.noteShowingBody.bodyHide()
}
Note.noteShowingBody = this
if (Note.zindex >= 9) {
/* don't use more than 10 layers (+1 for the body, which will always be above all notes) */
Note.zindex = 0
for (var i=0; i< Note.all.length; ++i) {
Note.all[i].elements.box.style.zIndex = 0
}
}
this.elements.box.style.zIndex = ++Note.zindex
this.elements.body.style.zIndex = 10
this.elements.body.style.top = 0 + "px"
this.elements.body.style.left = 0 + "px"
var dw = document.documentElement.scrollWidth
this.elements.body.style.visibility = "hidden"
this.elements.body.style.display = "block"
if (!this.bodyfit) {
this.elements.body.style.height = "auto"
this.elements.body.style.minWidth = "140px"
var w = null, h = null, lo = null, hi = null, x = null, last = null
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) {
/* for tall notes (lots of text), find more pleasant proportions */
lo = 140, hi = 400
do {
last = w
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
w = this.elements.body.offsetWidth
h = this.elements.body.offsetHeight
if (w/h < 1.6180339887) lo = x
else hi = x
} while ((lo < hi) && (w > last))
} else if (this.elements.body.scrollWidth <= this.elements.body.clientWidth) {
/* for short notes (often a single line), make the box no wider than necessary */
// scroll test necessary for Firefox
lo = 20, hi = w
do {
x = (lo+hi)/2
this.elements.body.style.minWidth = x + "px"
if (this.elements.body.offsetHeight > h) lo = x
else hi = x
} while ((hi - lo) > 4)
if (this.elements.body.offsetHeight > h)
this.elements.body.style.minWidth = hi + "px"
}
if (Prototype.Browser.IE) {
// IE7 adds scrollbars if the box is too small, obscuring the text
if (this.elements.body.offsetHeight < 35) {
this.elements.body.style.minHeight = "35px"
}
if (this.elements.body.offsetWidth < 47) {
this.elements.body.style.minWidth = "47px"
}
}
this.bodyfit = true
}
this.elements.body.style.top = (this.elements.box.offsetTop + this.elements.box.clientHeight + 5) + "px"
// keep the box within the document's width
var l = 0, e = this.elements.box
do { l += e.offsetLeft } while (e = e.offsetParent)
l += this.elements.body.offsetWidth + 10 - dw
if (l > 0)
this.elements.body.style.left = this.elements.box.offsetLeft - l + "px"
else
this.elements.body.style.left = this.elements.box.offsetLeft + "px"
this.elements.body.style.visibility = "visible"
},
// Creates a timer that will hide the body text for the note
bodyHideTimer: function(e) {
if (Note.debug) {
console.debug("Note#bodyHideTimer (id=%d)", this.id)
}
this.hideTimer = setTimeout(this.bodyHide.bindAsEventListener(this), 250)
},
// Hides the body text for the note
bodyHide: function(e) {
if (Note.debug) {
console.debug("Note#bodyHide (id=%d)", this.id)
}
this.elements.body.hide()
if (Note.noteShowingBody == this) {
Note.noteShowingBody = null
}
},
addDocumentObserver: function(name, func)
{
document.observe(name, func);
this.document_observers.push([name, func]);
},
clearDocumentObservers: function(name, handler)
{
for(var i = 0; i < this.document_observers.length; ++i)
{
var observer = this.document_observers[i];
document.stopObserving(observer[0], observer[1]);
}
this.document_observers = [];
},
// Start dragging the note
dragStart: function(e) {
if (Note.debug) {
console.debug("Note#dragStart (id=%d)", this.id)
}
this.addDocumentObserver("mousemove", this.drag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.dragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(5, this.elements.image.clientWidth - this.elements.box.clientWidth - 5)
this.boundsY = new ClipRange(5, this.elements.image.clientHeight - this.elements.box.clientHeight - 5)
this.dragging = true
this.bodyHide()
},
// Stop dragging the note
dragStop: function(e) {
if (Note.debug) {
console.debug("Note#dragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
this.bodyShow()
},
ratio: function() {
return this.elements.image.width / this.elements.image.getAttribute("large_width")
// var ratio = this.elements.image.width / this.elements.image.getAttribute("large_width")
// if (this.elements.image.scale_factor != null)
// ratio *= this.elements.image.scale_factor;
// return ratio
},
// Scale the notes for when the image gets resized
adjustScale: function() {
if (Note.debug) {
console.debug("Note#adjustScale (id=%d)", this.id)
}
var ratio = this.ratio()
for (p in this.fullsize) {
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
},
// Update the note's position as it gets dragged
drag: function(e) {
var left = this.boxStartX + e.pointerX() - this.cursorStartX
var top = this.boxStartY + e.pointerY() - this.cursorStartY
left = this.boundsX.clip(left)
top = this.boundsY.clip(top)
this.elements.box.style.left = left + 'px'
this.elements.box.style.top = top + 'px'
var ratio = this.ratio()
this.fullsize.left = left / ratio
this.fullsize.top = top / ratio
e.stop()
},
// Start dragging the edit box
editDragStart: function(e) {
if (Note.debug) {
console.debug("Note#editDragStart (id=%d)", this.id)
}
var node = e.element().nodeName
if (node != 'FORM' && node != 'DIV') {
return
}
this.addDocumentObserver("mousemove", this.editDrag.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.editDragStop.bindAsEventListener(this))
this.addDocumentObserver("selectstart", function() {return false})
this.elements.editBox = $('edit-box');
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.editStartX = this.elements.editBox.offsetLeft
this.editStartY = this.elements.editBox.offsetTop
this.dragging = true
},
// Stop dragging the edit box
editDragStop: function(e) {
if (Note.debug) {
console.debug("Note#editDragStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.cursorStartX = null
this.cursorStartY = null
this.editStartX = null
this.editStartY = null
this.dragging = false
},
// Update the edit box's position as it gets dragged
editDrag: function(e) {
var left = this.editStartX + e.pointerX() - this.cursorStartX
var top = this.editStartY + e.pointerY() - this.cursorStartY
this.elements.editBox.style.left = left + 'px'
this.elements.editBox.style.top = top + 'px'
e.stop()
},
// Start resizing the note
resizeStart: function(e) {
if (Note.debug) {
console.debug("Note#resizeStart (id=%d)", this.id)
}
this.cursorStartX = e.pointerX()
this.cursorStartY = e.pointerY()
this.boxStartWidth = this.elements.box.clientWidth
this.boxStartHeight = this.elements.box.clientHeight
this.boxStartX = this.elements.box.offsetLeft
this.boxStartY = this.elements.box.offsetTop
this.boundsX = new ClipRange(10, this.elements.image.clientWidth - this.boxStartX - 5)
this.boundsY = new ClipRange(10, this.elements.image.clientHeight - this.boxStartY - 5)
this.dragging = true
this.clearDocumentObservers()
this.addDocumentObserver("mousemove", this.resize.bindAsEventListener(this))
this.addDocumentObserver("mouseup", this.resizeStop.bindAsEventListener(this))
e.stop()
this.bodyHide()
},
// Stop resizing teh note
resizeStop: function(e) {
if (Note.debug) {
console.debug("Note#resizeStop (id=%d)", this.id)
}
this.clearDocumentObservers()
this.boxCursorStartX = null
this.boxCursorStartY = null
this.boxStartWidth = null
this.boxStartHeight = null
this.boxStartX = null
this.boxStartY = null
this.boundsX = null
this.boundsY = null
this.dragging = false
e.stop()
},
// Update the note's dimensions as it gets resized
resize: function(e) {
var width = this.boxStartWidth + e.pointerX() - this.cursorStartX
var height = this.boxStartHeight + e.pointerY() - this.cursorStartY
width = this.boundsX.clip(width)
height = this.boundsY.clip(height)
this.elements.box.style.width = width + "px"
this.elements.box.style.height = height + "px"
var ratio = this.ratio()
this.fullsize.width = width / ratio
this.fullsize.height = height / ratio
e.stop()
},
// Save the note to the database
save: function(e) {
if (Note.debug) {
console.debug("Note#save (id=%d)", this.id)
}
var note = this
for (p in this.fullsize) {
this.old[p] = this.fullsize[p]
}
this.old.raw_body = $('edit-box-text').value
this.old.formatted_body = this.textValue()
// FIXME: this is not quite how the note will look (filtered elems, <tn>...). the user won't input a <script> that only damages him, but it might be nice to "preview" the <tn> here
this.elements.body.update(this.textValue())
this.hideEditBox(e)
this.bodyHide()
this.bodyfit = false
var params = {
"id": this.id,
"note[x]": this.old.left,
"note[y]": this.old.top,
"note[width]": this.old.width,
"note[height]": this.old.height,
"note[body]": this.old.raw_body
}
if (this.is_new) {
params["note[post_id]"] = Note.post_id
}
notice("Saving note...")
new Ajax.Request('/note/update.json', {
parameters: params,
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note saved")
var note = Note.find(resp.old_id)
if (resp.old_id < 0) {
note.is_new = false
note.id = resp.new_id
note.elements.box.id = 'note-box-' + note.id
note.elements.body.id = 'note-body-' + note.id
note.elements.corner.id = 'note-corner-' + note.id
}
note.elements.body.innerHTML = resp.formatted_body
note.elements.box.setOpacity(0.5)
note.elements.box.removeClassName('unsaved')
} else {
notice("Error: " + resp.reason)
note.elements.box.addClassName('unsaved')
}
}
})
e.stop()
},
// Revert the note to the last saved state
cancel: function(e) {
if (Note.debug) {
console.debug("Note#cancel (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
var ratio = this.ratio()
for (p in this.fullsize) {
this.fullsize[p] = this.old[p]
this.elements.box.style[p] = this.fullsize[p] * ratio + 'px'
}
this.elements.body.innerHTML = this.old.formatted_body
e.stop()
},
// Remove all references to the note from the page
removeCleanup: function() {
if (Note.debug) {
console.debug("Note#removeCleanup (id=%d)", this.id)
}
this.elements.box.remove()
this.elements.body.remove()
var allTemp = []
for (i=0; i<Note.all.length; ++i) {
if (Note.all[i].id != this.id) {
allTemp.push(Note.all[i])
}
}
Note.all = allTemp
Note.updateNoteCount()
},
// Removes a note from the database
remove: function(e) {
if (Note.debug) {
console.debug("Note#remove (id=%d)", this.id)
}
this.hideEditBox(e)
this.bodyHide()
this_note = this
if (this.is_new) {
this.removeCleanup()
notice("Note removed")
} else {
notice("Removing note...")
new Ajax.Request('/note/update.json', {
parameters: {
"id": this.id,
"note[is_active]": "0"
},
onComplete: function(resp) {
var resp = resp.responseJSON
if (resp.success) {
notice("Note removed")
this_note.removeCleanup()
} else {
notice("Error: " + resp.reason)
}
}
})
}
e.stop()
},
// Redirect to the note's history
history: function(e) {
if (Note.debug) {
console.debug("Note#history (id=%d)", this.id)
}
this.hideEditBox(e)
if (this.is_new) {
notice("This note has no history")
} else {
location.href = '/history?search=notes:' + this.id
}
e.stop()
}
})
// The following are class methods and variables
Object.extend(Note, {
zindex: 0,
counter: -1,
all: [],
display: true,
debug: false,
// Show all notes
show: function() {
if (Note.debug) {
console.debug("Note.show")
}
$("note-container").show()
},
// Hide all notes
hide: function() {
if (Note.debug) {
console.debug("Note.hide")
}
$("note-container").hide()
},
// Find a note instance based on the id number
find: function(id) {
if (Note.debug) {
console.debug("Note.find")
}
for (var i=0; i<Note.all.size(); ++i) {
if (Note.all[i].id == id) {
return Note.all[i]
}
}
return null
},
// Toggle the display of all notes
toggle: function() {
if (Note.debug) {
console.debug("Note.toggle")
}
if (Note.display) {
Note.hide()
Note.display = false
} else {
Note.show()
Note.display = true
}
},
// Update the text displaying the number of notes a post has
updateNoteCount: function() {
if (Note.debug) {
console.debug("Note.updateNoteCount")
}
if (Note.all.length > 0) {
var label = ""
if (Note.all.length == 1)
label = "note"
else
label = "notes"
$('note-count').innerHTML = "This post has <a href=\"/note/history?post_id=" + Note.post_id + "\">" + Note.all.length + " " + label + "</a>"
} else {
$('note-count').innerHTML = ""
}
},
// Create a new note
create: function() {
if (Note.debug) {
console.debug("Note.create")
}
Note.show()
var insertion_position = Note.getInsertionPosition()
var top = insertion_position[0]
var left = insertion_position[1]
var html = ''
html += '<div class="note-box unsaved" style="width: 150px; height: 150px; '
html += 'top: ' + top + 'px; '
html += 'left: ' + left + 'px;" '
html += 'id="note-box-' + Note.counter + '">'
html += '<div class="note-corner" id="note-corner-' + Note.counter + '"></div>'
html += '</div>'
html += '<div class="note-body" title="Click to edit" id="note-body-' + Note.counter + '"></div>'
$("note-container").insert({bottom: html})
var note = new Note(Note.counter, true, "")
Note.all.push(note)
Note.counter -= 1
},
// Find a suitable position to insert new notes
getInsertionPosition: function() {
if (Note.debug) {
console.debug("Note.getInsertionPosition")
}
// We want to show the edit box somewhere on the screen, but not outside the image.
var scroll_x = $("image").cumulativeScrollOffset()[0]
var scroll_y = $("image").cumulativeScrollOffset()[1]
var image_left = $("image").positionedOffset()[0]
var image_top = $("image").positionedOffset()[1]
var image_right = image_left + $("image").width
var image_bottom = image_top + $("image").height
var left = 0
var top = 0
if (scroll_x > image_left) {
left = scroll_x
} else {
left = image_left
}
if (scroll_y > image_top) {
top = scroll_y
} else {
top = image_top + 20
}
if (top > image_bottom) {
top = image_top + 20
}
return [top, left]
}
})
| rhaphazard/moebooru | lib/assets/javascripts/moe-legacy/notes.js | JavaScript | isc | 21,067 |
// Copyright (c) 2021 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package indexers
import (
"context"
"fmt"
"sync"
"sync/atomic"
"github.com/decred/dcrd/blockchain/v4/internal/progresslog"
"github.com/decred/dcrd/database/v3"
"github.com/decred/dcrd/dcrutil/v4"
)
// IndexNtfnType represents an index notification type.
type IndexNtfnType int
const (
// ConnectNtfn indicates the index notification signals a block
// connected to the main chain.
ConnectNtfn IndexNtfnType = iota
// DisconnectNtfn indicates the index notification signals a block
// disconnected from the main chain.
DisconnectNtfn
)
var (
// bufferSize represents the index notification buffer size.
bufferSize = 128
// noPrereqs indicates no index prerequisites.
noPrereqs = "none"
)
// IndexNtfn represents an index notification detailing a block connection
// or disconnection.
type IndexNtfn struct {
NtfnType IndexNtfnType
Block *dcrutil.Block
Parent *dcrutil.Block
PrevScripts PrevScripter
IsTreasuryEnabled bool
Done chan bool
}
// IndexSubscription represents a subscription for index updates.
type IndexSubscription struct {
id string
idx Indexer
subscriber *IndexSubscriber
mtx sync.Mutex
// prerequisite defines the notification processing hierarchy for this
// subscription. It is expected that the subscriber associated with the
// prerequisite provided processes notifications before they are
// delivered by this subscription to its subscriber. An empty string
// indicates the subscription has no prerequisite.
prerequisite string
// dependent defines the index subscription that requires the subscriber
// associated with this subscription to have processed incoming
// notifications before it does. A nil dependency indicates the subscription
// has no dependencies.
dependent *IndexSubscription
}
// newIndexSubscription initializes a new index subscription.
func newIndexSubscription(subber *IndexSubscriber, indexer Indexer, prereq string) *IndexSubscription {
return &IndexSubscription{
id: indexer.Name(),
idx: indexer,
prerequisite: prereq,
subscriber: subber,
}
}
// stop prevents any future index updates from being delivered and
// unsubscribes the associated subscription.
func (s *IndexSubscription) stop() error {
// If the subscription has a prerequisite, find it and remove the
// subscription as a dependency.
if s.prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriber.subscriptions[s.prerequisite]
s.mtx.Unlock()
if !ok {
return fmt.Errorf("no subscription found with id %s", s.prerequisite)
}
prereq.mtx.Lock()
prereq.dependent = nil
prereq.mtx.Unlock()
return nil
}
// If the subscription has a dependent, stop it as well.
if s.dependent != nil {
err := s.dependent.stop()
if err != nil {
return err
}
}
// If the subscription is independent, remove it from the
// index subscriber's subscriptions.
s.mtx.Lock()
delete(s.subscriber.subscriptions, s.id)
s.mtx.Unlock()
return nil
}
// IndexSubscriber subscribes clients for index updates.
type IndexSubscriber struct {
subscribers uint32 // update atomically.
c chan IndexNtfn
subscriptions map[string]*IndexSubscription
mtx sync.Mutex
ctx context.Context
cancel context.CancelFunc
quit chan struct{}
}
// NewIndexSubscriber creates a new index subscriber. It also starts the
// handler for incoming index update subscriptions.
func NewIndexSubscriber(sCtx context.Context) *IndexSubscriber {
ctx, cancel := context.WithCancel(sCtx)
s := &IndexSubscriber{
c: make(chan IndexNtfn, bufferSize),
subscriptions: make(map[string]*IndexSubscription),
ctx: ctx,
cancel: cancel,
quit: make(chan struct{}),
}
return s
}
// Subscribe subscribes an index for updates. The returned index subscription
// has functions to retrieve a channel that produces a stream of index updates
// and to stop the stream when the caller no longer wishes to receive updates.
func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexSubscription, error) {
sub := newIndexSubscription(s, index, prerequisite)
// If the subscription has a prequisite, find it and set the subscription
// as a dependency.
if prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriptions[prerequisite]
s.mtx.Unlock()
if !ok {
return nil, fmt.Errorf("no subscription found with id %s", prerequisite)
}
prereq.mtx.Lock()
defer prereq.mtx.Unlock()
if prereq.dependent != nil {
return nil, fmt.Errorf("%s already has a dependent set: %s",
prereq.id, prereq.dependent.id)
}
prereq.dependent = sub
atomic.AddUint32(&s.subscribers, 1)
return sub, nil
}
// If the subscription does not have a prerequisite, add it to the index
// subscriber's subscriptions.
s.mtx.Lock()
s.subscriptions[sub.id] = sub
s.mtx.Unlock()
atomic.AddUint32(&s.subscribers, 1)
return sub, nil
}
// Notify relays an index notification to subscribed indexes for processing.
func (s *IndexSubscriber) Notify(ntfn *IndexNtfn) {
subscribers := atomic.LoadUint32(&s.subscribers)
// Only relay notifications when there are subscribed indexes
// to be notified.
if subscribers > 0 {
select {
case <-s.quit:
case s.c <- *ntfn:
}
}
}
// findLowestIndexTipHeight determines the lowest index tip height among
// subscribed indexes and their dependencies.
func (s *IndexSubscriber) findLowestIndexTipHeight(queryer ChainQueryer) (int64, int64, error) {
// Find the lowest tip height to catch up among subscribed indexes.
bestHeight, _ := queryer.Best()
lowestHeight := bestHeight
for _, sub := range s.subscriptions {
tipHeight, tipHash, err := sub.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
// Ensure the index tip is on the main chain.
if !queryer.MainChainHasBlock(tipHash) {
return 0, bestHeight, fmt.Errorf("%s: index tip (%s) is not on the "+
"main chain", sub.idx.Name(), tipHash)
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
// Update the lowest tip height if a dependent has a lower tip height.
dependent := sub.dependent
for dependent != nil {
tipHeight, _, err := sub.dependent.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
dependent = dependent.dependent
}
}
return lowestHeight, bestHeight, nil
}
// CatchUp syncs all subscribed indexes to the the main chain by connecting
// blocks from after the lowest index tip to the current main chain tip.
//
// This should be called after all indexes have subscribed for updates.
func (s *IndexSubscriber) CatchUp(ctx context.Context, db database.DB, queryer ChainQueryer) error {
lowestHeight, bestHeight, err := s.findLowestIndexTipHeight(queryer)
if err != nil {
return err
}
// Nothing to do if all indexes are synced.
if bestHeight == lowestHeight {
return nil
}
// Create a progress logger for the indexing process below.
progressLogger := progresslog.NewBlockProgressLogger("Indexed", log)
// tip and need to be caught up, so log the details and loop through
// each block that needs to be indexed.
log.Infof("Catching up from height %d to %d", lowestHeight,
bestHeight)
var cachedParent *dcrutil.Block
for height := lowestHeight + 1; height <= bestHeight; height++ {
if interruptRequested(ctx) {
return indexerError(ErrInterruptRequested, interruptMsg)
}
hash, err := queryer.BlockHashByHeight(height)
if err != nil {
return err
}
// Ensure the next tip hash is on the main chain.
if !queryer.MainChainHasBlock(hash) {
msg := fmt.Sprintf("the next block being synced to (%s) "+
"at height %d is not on the main chain", hash, height)
return indexerError(ErrBlockNotOnMainChain, msg)
}
var parent *dcrutil.Block
if cachedParent == nil && height > 0 {
parentHash, err := queryer.BlockHashByHeight(height - 1)
if err != nil {
return err
}
parent, err = queryer.BlockByHash(parentHash)
if err != nil {
return err
}
} else {
parent = cachedParent
}
child, err := queryer.BlockByHash(hash)
if err != nil {
return err
}
// Construct and send the index notification.
var prevScripts PrevScripter
err = db.View(func(dbTx database.Tx) error {
if interruptRequested(ctx) {
return indexerError(ErrInterruptRequested, interruptMsg)
}
prevScripts, err = queryer.PrevScripts(dbTx, child)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
isTreasuryEnabled, err := queryer.IsTreasuryAgendaActive(parent.Hash())
if err != nil {
return err
}
ntfn := &IndexNtfn{
NtfnType: ConnectNtfn,
Block: child,
Parent: parent,
PrevScripts: prevScripts,
IsTreasuryEnabled: isTreasuryEnabled,
}
// Relay the index update to subscribed indexes.
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, ntfn)
if err != nil {
s.cancel()
return err
}
}
cachedParent = child
progressLogger.LogBlockHeight(child.MsgBlock(), parent.MsgBlock())
}
log.Infof("Caught up to height %d", bestHeight)
return nil
}
// Run relays index notifications to subscribed indexes.
//
// This should be run as a goroutine.
func (s *IndexSubscriber) Run(ctx context.Context) {
for {
select {
case ntfn := <-s.c:
// Relay the index update to subscribed indexes.
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, &ntfn)
if err != nil {
log.Error(err)
s.cancel()
break
}
}
if ntfn.Done != nil {
close(ntfn.Done)
}
case <-ctx.Done():
log.Infof("Index subscriber shutting down")
close(s.quit)
// Stop all updates to subscribed indexes and terminate their
// processes.
for _, sub := range s.subscriptions {
err := sub.stop()
if err != nil {
log.Error("unable to stop index subscription: %v", err)
}
}
s.cancel()
return
}
}
}
| decred/dcrd | blockchain/indexers/indexsubscriber.go | GO | isc | 10,267 |
describe('dJSON', function () {
'use strict';
var chai = require('chai');
var expect = chai.expect;
var dJSON = require('../lib/dJSON');
var path = 'x.y["q.{r}"].z';
var obj;
beforeEach(function () {
obj = {
x: {
y: {
'q.{r}': {
z: 635
},
q: {
r: {
z: 1
}
}
}
},
'x-y': 5,
falsy: false
};
});
it('gets a value from an object with a path containing properties which contain a period', function () {
expect(dJSON.get(obj, path)).to.equal(635);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('sets a value from an object with a path containing properties which contain a period', function () {
dJSON.set(obj, path, 17771);
expect(dJSON.get(obj, path)).to.equal(17771);
expect(dJSON.get(obj, 'x.y.q.r.z')).to.equal(1);
});
it('will return undefined when requesting a property with a dash directly', function () {
expect(dJSON.get(obj, 'x-y')).to.be.undefined;
});
it('will return the proper value when requesting a property with a dash by square bracket notation', function () {
expect(dJSON.get(obj, '["x-y"]')).to.equal(5);
});
it('returns a value that is falsy', function () {
expect(dJSON.get(obj, 'falsy')).to.equal(false);
});
it('sets a value that is falsy', function () {
dJSON.set(obj, 'new', false);
expect(dJSON.get(obj, 'new')).to.equal(false);
});
it('uses an empty object as default for the value in the set method', function () {
var newObj = {};
dJSON.set(newObj, 'foo.bar.lorem');
expect(newObj).to.deep.equal({
foo: {
bar: {
lorem: {}
}
}
});
});
it('does not create an object when a path exists as empty string', function () {
var newObj = {
nestedObject: {
anArray: [
'i have a value',
''
]
}
};
var newPath = 'nestedObject.anArray[1]';
dJSON.set(newObj, newPath, 17771);
expect(newObj).to.deep.equal({
nestedObject: {
anArray: [
'i have a value',
17771
]
}
});
});
it('creates an object from a path with a left curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with a right curly brace', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path with curly braces', function () {
var newObj = {};
dJSON.set(newObj, path, 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.{r}': {
z: 'foo'
}
}
}
});
});
it('creates an object from a path without curly braces', function () {
var newObj = {};
dJSON.set(newObj, path.replace('{', '').replace('}', ''), 'foo');
expect(newObj).to.be.deep.equal({
x: {
y: {
'q.r': {
z: 'foo'
}
}
}
});
});
});
| bsander/dJSON | test/dJSON.spec.js | JavaScript | isc | 3,391 |
/**
* The MIT License Copyright (c) 2015 Teal Cube Games
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package land.face.strife.managers;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import land.face.strife.StrifePlugin;
import land.face.strife.data.champion.Champion;
import land.face.strife.data.champion.LifeSkillType;
import org.bukkit.entity.Player;
public class CombatStatusManager {
private final StrifePlugin plugin;
private final Map<Player, Integer> tickMap = new ConcurrentHashMap<>();
private static final int SECONDS_TILL_EXPIRY = 8;
public CombatStatusManager(StrifePlugin plugin) {
this.plugin = plugin;
}
public boolean isInCombat(Player player) {
return tickMap.containsKey(player);
}
public void addPlayer(Player player) {
tickMap.put(player, SECONDS_TILL_EXPIRY);
}
public void tickCombat() {
for (Player player : tickMap.keySet()) {
if (!player.isOnline() || !player.isValid()) {
tickMap.remove(player);
continue;
}
int ticksLeft = tickMap.get(player);
if (ticksLeft < 1) {
doExitCombat(player);
tickMap.remove(player);
continue;
}
tickMap.put(player, ticksLeft - 1);
}
}
public void doExitCombat(Player player) {
if (!tickMap.containsKey(player)) {
return;
}
Champion champion = plugin.getChampionManager().getChampion(player);
if (champion.getDetailsContainer().getExpValues() == null) {
return;
}
for (LifeSkillType type : champion.getDetailsContainer().getExpValues().keySet()) {
plugin.getSkillExperienceManager().addExperience(player, type,
champion.getDetailsContainer().getExpValues().get(type), false, false);
}
champion.getDetailsContainer().clearAll();
}
}
| TealCube/strife | src/main/java/land/face/strife/managers/CombatStatusManager.java | Java | isc | 2,828 |
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db import models
from django.utils import simplejson as json
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from philo.forms.fields import JSONFormField
from philo.utils.registry import RegistryIterator
from philo.validators import TemplateValidator, json_validator
#from philo.models.fields.entities import *
class TemplateField(models.TextField):
"""A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction."""
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs):
super(TemplateField, self).__init__(*args, **kwargs)
self.validators.append(TemplateValidator(allow, disallow, secure))
class JSONDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, instance, owner):
if instance is None:
raise AttributeError # ?
if self.field.name not in instance.__dict__:
json_string = getattr(instance, self.field.attname)
instance.__dict__[self.field.name] = json.loads(json_string)
return instance.__dict__[self.field.name]
def __set__(self, instance, value):
instance.__dict__[self.field.name] = value
setattr(instance, self.field.attname, json.dumps(value))
def __delete__(self, instance):
del(instance.__dict__[self.field.name])
setattr(instance, self.field.attname, json.dumps(None))
class JSONField(models.TextField):
"""A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`."""
default_validators = [json_validator]
def get_attname(self):
return "%s_json" % self.name
def contribute_to_class(self, cls, name):
super(JSONField, self).contribute_to_class(cls, name)
setattr(cls, name, JSONDescriptor(self))
models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
# Anything passed in as self.name is assumed to come from a serializer and
# will be treated as a json string.
if self.name in kwargs:
value = kwargs.pop(self.name)
# Hack to handle the xml serializer's handling of "null"
if value is None:
value = 'null'
kwargs[self.attname] = value
def formfield(self, *args, **kwargs):
kwargs["form_class"] = JSONFormField
return super(JSONField, self).formfield(*args, **kwargs)
class SlugMultipleChoiceField(models.Field):
"""Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices."""
__metaclass__ = models.SubfieldBase
description = _("Comma-separated slug field")
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if not value:
return []
if isinstance(value, list):
return value
return value.split(',')
def get_prep_value(self, value):
return ','.join(value)
def formfield(self, **kwargs):
# This is necessary because django hard-codes TypedChoiceField for things with choices.
defaults = {
'widget': forms.CheckboxSelectMultiple,
'choices': self.get_choices(include_blank=False),
'label': capfirst(self.verbose_name),
'required': not self.blank,
'help_text': self.help_text
}
if self.has_default():
if callable(self.default):
defaults['initial'] = self.default
defaults['show_hidden_initial'] = True
else:
defaults['initial'] = self.get_default()
for k in kwargs.keys():
if k not in ('coerce', 'empty_value', 'choices', 'required',
'widget', 'label', 'initial', 'help_text',
'error_messages', 'show_hidden_initial'):
del kwargs[k]
defaults.update(kwargs)
form_class = forms.TypedMultipleChoiceField
return form_class(**defaults)
def validate(self, value, model_instance):
invalid_values = []
for val in value:
try:
validate_slug(val)
except ValidationError:
invalid_values.append(val)
if invalid_values:
# should really make a custom message.
raise ValidationError(self.error_messages['invalid_choice'] % invalid_values)
def _get_choices(self):
if isinstance(self._choices, RegistryIterator):
return self._choices.copy()
elif hasattr(self._choices, 'next'):
choices, self._choices = itertools.tee(self._choices)
return choices
else:
return self._choices
choices = property(_get_choices)
try:
from south.modelsinspector import add_introspection_rules
except ImportError:
pass
else:
add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"])
add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"])
add_introspection_rules([], ["^philo\.models\.fields\.JSONField"]) | ithinksw/philo | philo/models/fields/__init__.py | Python | isc | 4,971 |
<?php
/**
* Time Controller
*
* @package Argentum
* @author Argentum Team
* @copyright (c) 2008 Argentum Team
* @license http://www.argentuminvoice.com/license.txt
*/
class Time_Controller extends Website_Controller {
/**
* Creates a new time block on a ticket
*/
public function add($ticket_id)
{
$time = new Time_Model();
$time->ticket_id = $ticket_id;
if ( ! $_POST) // Display the form
{
$this->template->body = new View('admin/time/add');
$this->template->body->errors = '';
$this->template->body->time = $time;
}
else
{
$time->set_fields($this->input->post());
$time->user_id = $_SESSION['auth_user']->id;
try
{
$time->save();
if ($this->input->post('ticket_complete'))
{
$ticket = new Ticket_Model($time->ticket_id);
$ticket->complete= TRUE;
$ticket->close_date = time();
$ticket->save();
Event::run('argentum.ticket_close', $ticket);
}
Event::run('argentum.ticket_time', $time);
url::redirect('ticket/'.($time->ticket->complete ? 'closed' : 'active').'/'.$time->ticket->project->id);
}
catch (Kohana_User_Exception $e)
{
$this->template->body = new View('admin/time/add');
$this->template->body->time = $time;
$this->template->body->errors = $e;
$this->template->body->set($this->input->post());
}
}
}
/**
* Deletes a time item for a ticket
*/
public function delete()
{
$time = new Time_Model($this->input->post('id'));
$time->delete();
url::redirect('ticket/view/'.$time->ticket->id);
}
} | la5942/argentum-invoice | application/controllers/admin/time.php | PHP | isc | 1,554 |
var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!obj.Includes[i].match(re)) {
inc.push('./' + obj.Includes[i]);
}
else {
inc.push(obj.Includes[i]);
}
}
}
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
} | bolav/fusepm | lib/fixunoproj.js | JavaScript | isc | 752 |
import mod437 from './mod437';
var value=mod437+1;
export default value;
| MirekSz/webpack-es6-ts | app/mods/mod438.js | JavaScript | isc | 73 |
const defaults = {
base_css: true, // the base dark theme css
inline_youtube: true, // makes youtube videos play inline the chat
collapse_onebox: true, // can collapse
collapse_onebox_default: false, // default option for collapse
pause_youtube_on_collapse: true, // default option for pausing youtube on collapse
user_color_bars: true, // show colored bars above users message blocks
fish_spinner: true, // fish spinner is best spinner
inline_imgur: true, // inlines webm,gifv,mp4 content from imgur
visualize_hex: true, // underlines hex codes with their colour values
syntax_highlight_code: true, // guess at language and highlight the code blocks
emoji_translator: true, // emoji translator for INPUT area
code_mode_editor: true, // uses CodeMirror for your code inputs
better_image_uploads: true // use the drag & drop and paste api for image uploads
};
const fileLocations = {
inline_youtube: ['js/inline_youtube.js'],
collapse_onebox: ['js/collapse_onebox.js'],
user_color_bars: ['js/user_color_bars.js'],
fish_spinner: ['js/fish_spinner.js'],
inline_imgur: ['js/inline_imgur.js'],
visualize_hex: ['js/visualize_hex.js'],
better_image_uploads: ['js/better_image_uploads.js'],
syntax_highlight_code: ['js/highlight.js', 'js/syntax_highlight_code.js'],
emoji_translator: ['js/emojidata.js', 'js/emoji_translator.js'],
code_mode_editor: ['CodeMirror/js/codemirror.js',
'CodeMirror/mode/cmake/cmake.js',
'CodeMirror/mode/cobol/cobol.js',
'CodeMirror/mode/coffeescript/coffeescript.js',
'CodeMirror/mode/commonlisp/commonlisp.js',
'CodeMirror/mode/css/css.js',
'CodeMirror/mode/dart/dart.js',
'CodeMirror/mode/go/go.js',
'CodeMirror/mode/groovy/groovy.js',
'CodeMirror/mode/haml/haml.js',
'CodeMirror/mode/haskell/haskell.js',
'CodeMirror/mode/htmlembedded/htmlembedded.js',
'CodeMirror/mode/htmlmixed/htmlmixed.js',
'CodeMirror/mode/jade/jade.js',
'CodeMirror/mode/javascript/javascript.js',
'CodeMirror/mode/lua/lua.js',
'CodeMirror/mode/markdown/markdown.js',
'CodeMirror/mode/mathematica/mathematica.js',
'CodeMirror/mode/nginx/nginx.js',
'CodeMirror/mode/pascal/pascal.js',
'CodeMirror/mode/perl/perl.js',
'CodeMirror/mode/php/php.js',
'CodeMirror/mode/puppet/puppet.js',
'CodeMirror/mode/python/python.js',
'CodeMirror/mode/ruby/ruby.js',
'CodeMirror/mode/sass/sass.js',
'CodeMirror/mode/scheme/scheme.js',
'CodeMirror/mode/shell/shell.js' ,
'CodeMirror/mode/sql/sql.js',
'CodeMirror/mode/swift/swift.js',
'CodeMirror/mode/twig/twig.js',
'CodeMirror/mode/vb/vb.js',
'CodeMirror/mode/vbscript/vbscript.js',
'CodeMirror/mode/vhdl/vhdl.js',
'CodeMirror/mode/vue/vue.js',
'CodeMirror/mode/xml/xml.js',
'CodeMirror/mode/xquery/xquery.js',
'CodeMirror/mode/yaml/yaml.js',
'js/code_mode_editor.js']
};
// right now I assume order is correct because I'm a terrible person. make an order array or base it on File Locations and make that an array
// inject the observer and the utils always. then initialize the options.
injector([{type: 'js', location: 'js/observer.js'},{type: 'js', location: 'js/utils.js'}], _ => chrome.storage.sync.get(defaults, init));
function init(options) {
// inject the options for the plugins themselves.
const opts = document.createElement('script');
opts.textContent = `
const options = ${JSON.stringify(options)};
`;
document.body.appendChild(opts);
// now load the plugins.
const loading = [];
if( !options.base_css ) {
document.documentElement.classList.add('nocss');
}
delete options.base_css;
for( const key of Object.keys(options) ) {
if( !options[key] || !( key in fileLocations)) continue;
for( const location of fileLocations[key] ) {
const [,type] = location.split('.');
loading.push({location, type});
}
}
injector(loading, _ => {
const drai = document.createElement('script');
drai.textContent = `
if( document.readyState === 'complete' ) {
DOMObserver.drain();
} else {
window.onload = _ => DOMObserver.drain();
}
`;
document.body.appendChild(drai);
});
}
function injector([first, ...rest], cb) {
if( !first ) return cb();
if( first.type === 'js' ) {
injectJS(first.location, _ => injector(rest, cb));
} else {
injectCSS(first.location, _ => injector(rest, cb));
}
}
function injectCSS(file, cb) {
const elm = document.createElement('link');
elm.rel = 'stylesheet';
elm.type = 'text/css';
elm.href = chrome.extension.getURL(file);
elm.onload = cb;
document.head.appendChild(elm);
}
function injectJS(file, cb) {
const elm = document.createElement('script');
elm.type = 'text/javascript';
elm.src = chrome.extension.getURL(file);
elm.onload = cb;
document.body.appendChild(elm);
} | rlemon/se-chat-dark-theme-plus | script.js | JavaScript | isc | 4,901 |
'use strict';
const expect = require('expect.js');
const http = require('http');
const express = require('express');
const linkCheck = require('../');
describe('link-check', function () {
this.timeout(2500);//increase timeout to enable 429 retry tests
let baseUrl;
let laterCustomRetryCounter;
before(function (done) {
const app = express();
app.head('/nohead', function (req, res) {
res.sendStatus(405); // method not allowed
});
app.get('/nohead', function (req, res) {
res.sendStatus(200);
});
app.get('/foo/redirect', function (req, res) {
res.redirect('/foo/bar');
});
app.get('/foo/bar', function (req, res) {
res.json({foo:'bar'});
});
app.get('/loop', function (req, res) {
res.redirect('/loop');
});
app.get('/hang', function (req, res) {
// no reply
});
app.get('/notfound', function (req, res) {
res.sendStatus(404);
});
app.get('/basic-auth', function (req, res) {
if (req.headers["authorization"] === "Basic Zm9vOmJhcg==") {
return res.sendStatus(200);
}
res.sendStatus(401);
});
// prevent first header try to be a hit
app.head('/later-custom-retry-count', function (req, res) {
res.sendStatus(405); // method not allowed
});
app.get('/later-custom-retry-count', function (req, res) {
laterCustomRetryCounter++;
if(laterCustomRetryCounter === parseInt(req.query.successNumber)) {
res.sendStatus(200);
}else{
res.setHeader('retry-after', 1);
res.sendStatus(429);
}
});
// prevent first header try to be a hit
app.head('/later-standard-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var stdRetried = false;
var stdFirstTry = 0;
app.get('/later', function (req, res) {
var isRetryDelayExpired = stdFirstTry + 1000 < Date.now();
if(!stdRetried || !isRetryDelayExpired){
stdFirstTry = Date.now();
stdRetried = true;
res.setHeader('retry-after', 1);
res.sendStatus(429);
}else{
res.sendStatus(200);
}
});
// prevent first header try to be a hit
app.head('/later-no-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var stdNoHeadRetried = false;
var stdNoHeadFirstTry = 0;
app.get('/later-no-header', function (req, res) {
var minTime = stdNoHeadFirstTry + 1000;
var maxTime = minTime + 100;
var now = Date.now();
var isRetryDelayExpired = minTime < now && now < maxTime;
if(!stdNoHeadRetried || !isRetryDelayExpired){
stdNoHeadFirstTry = Date.now();
stdNoHeadRetried = true;
res.sendStatus(429);
}else{
res.sendStatus(200);
}
});
// prevent first header try to be a hit
app.head('/later-non-standard-header', function (req, res) {
res.sendStatus(405); // method not allowed
});
var nonStdRetried = false;
var nonStdFirstTry = 0;
app.get('/later-non-standard-header', function (req, res) {
var isRetryDelayExpired = nonStdFirstTry + 1000 < Date.now();
if(!nonStdRetried || !isRetryDelayExpired){
nonStdFirstTry = Date.now();
nonStdRetried = true;
res.setHeader('retry-after', '1s');
res.sendStatus(429);
}else {
res.sendStatus(200);
}
});
app.get(encodeURI('/url_with_unicode–'), function (req, res) {
res.sendStatus(200);
});
app.get('/url_with_special_chars\\(\\)\\+', function (req, res) {
res.sendStatus(200);
});
const server = http.createServer(app);
server.listen(0 /* random open port */, 'localhost', function serverListen(err) {
if (err) {
done(err);
return;
}
baseUrl = 'http://' + server.address().address + ':' + server.address().port;
done();
});
});
it('should find that a valid link is alive', function (done) {
linkCheck(baseUrl + '/foo/bar', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that a valid external link with basic authentication is alive', function (done) {
linkCheck(baseUrl + '/basic-auth', {
headers: {
'Authorization': 'Basic Zm9vOmJhcg=='
},
}, function (err, result) {
expect(err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that a valid relative link is alive', function (done) {
linkCheck('/foo/bar', { baseUrl: baseUrl }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should find that an invalid link is dead', function (done) {
linkCheck(baseUrl + '/foo/dead', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/dead');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
expect(result.err).to.be(null);
done();
});
});
it('should find that an invalid relative link is dead', function (done) {
linkCheck('/foo/dead', { baseUrl: baseUrl }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('/foo/dead');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
expect(result.err).to.be(null);
done();
});
});
it('should report no DNS entry as a dead link (http)', function (done) {
linkCheck('http://example.example.example.com/', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('http://example.example.example.com/');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.be('ENOTFOUND');
done();
});
});
it('should report no DNS entry as a dead link (https)', function (done) {
const badLink = 'https://githuuuub.com/tcort/link-check';
linkCheck(badLink, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(badLink);
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.contain('ENOTFOUND');
done();
});
});
it('should timeout if there is no response', function (done) {
linkCheck(baseUrl + '/hang', { timeout: '100ms' }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/hang');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.code).to.be('ECONNRESET');
done();
});
});
it('should try GET if HEAD fails', function (done) {
linkCheck(baseUrl + '/nohead', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/nohead');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should handle redirects', function (done) {
linkCheck(baseUrl + '/foo/redirect', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/redirect');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done();
});
});
it('should handle valid mailto', function (done) {
linkCheck('mailto:linuxgeek@gmail.com', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:linuxgeek@gmail.com');
expect(result.status).to.be('alive');
done();
});
});
it('should handle valid mailto with encoded characters in address', function (done) {
linkCheck('mailto:foo%20bar@example.org', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:foo%20bar@example.org');
expect(result.status).to.be('alive');
done();
});
});
it('should handle valid mailto containing hfields', function (done) {
linkCheck('mailto:linuxgeek@gmail.com?subject=caf%C3%A9', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:linuxgeek@gmail.com?subject=caf%C3%A9');
expect(result.status).to.be('alive');
done();
});
});
it('should handle invalid mailto', function (done) {
linkCheck('mailto:foo@@bar@@baz', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be('mailto:foo@@bar@@baz');
expect(result.status).to.be('dead');
done();
});
});
it('should handle file protocol', function(done) {
linkCheck('fixtures/file.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol with fragment', function(done) {
linkCheck('fixtures/file.md#section-1', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol with query', function(done) {
linkCheck('fixtures/file.md?foo=bar', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file path containing spaces', function(done) {
linkCheck('fixtures/s p a c e/A.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle baseUrl containing spaces', function(done) {
linkCheck('A.md', { baseUrl: 'file://' + __dirname + '/fixtures/s p a c e'}, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
done()
});
});
it('should handle file protocol and invalid files', function(done) {
linkCheck('fixtures/missing.md', { baseUrl: 'file://' + __dirname }, function(err, result) {
expect(err).to.be(null);
expect(result.err.code).to.be('ENOENT');
expect(result.status).to.be('dead');
done()
});
});
it('should ignore file protocol on absolute links', function(done) {
linkCheck(baseUrl + '/foo/bar', { baseUrl: 'file://' }, function(err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/foo/bar');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
expect(result.err).to.be(null);
done()
});
});
it('should ignore file protocol on fragment links', function(done) {
linkCheck('#foobar', { baseUrl: 'file://' }, function(err, result) {
expect(err).to.be(null);
expect(result.link).to.be('#foobar');
done()
});
});
it('should callback with an error on unsupported protocol', function (done) {
linkCheck('gopher://gopher/0/v2/vstat', function (err, result) {
expect(result).to.be(null);
expect(err).to.be.an(Error);
done();
});
});
it('should handle redirect loops', function (done) {
linkCheck(baseUrl + '/loop', function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/loop');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(0);
expect(result.err.message).to.contain('Max redirects reached');
done();
});
});
it('should honour response codes in opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 404, 200 ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(404);
done();
});
});
it('should honour regexps in opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 200, /^[45][0-9]{2}$/ ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(404);
done();
});
});
it('should honour opts.aliveStatusCodes[]', function (done) {
linkCheck(baseUrl + '/notfound', { aliveStatusCodes: [ 200 ] }, function (err, result) {
expect(err).to.be(null);
expect(result.link).to.be(baseUrl + '/notfound');
expect(result.status).to.be('dead');
expect(result.statusCode).to.be(404);
done();
});
});
it('should retry after the provided delay on HTTP 429 with standard header', function (done) {
linkCheck(baseUrl + '/later', { retryOn429: true }, function (err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.link).to.be(baseUrl + '/later');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
it('should retry after the provided delay on HTTP 429 with non standard header, and return a warning', function (done) {
linkCheck(baseUrl + '/later-non-standard-header', { retryOn429: true }, function (err, result) {
expect(err).to.be(null);
expect(result.err).not.to.be(null)
expect(result.err).to.contain("Server returned a non standard \'retry-after\' header.");
expect(result.link).to.be(baseUrl + '/later-non-standard-header');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
it('should retry after 1s delay on HTTP 429 without header', function (done) {
linkCheck(baseUrl + '/later-no-header', { retryOn429: true, fallbackRetryDelay: '1s' }, function (err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.link).to.be(baseUrl + '/later-no-header');
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// 2 is default retry so test with custom 3
it('should retry 3 times for 429 status codes', function(done) {
laterCustomRetryCounter = 0;
linkCheck(baseUrl + '/later-custom-retry-count?successNumber=3', { retryOn429: true, retryCount: 3 }, function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// See issue #23
it('should handle non URL encoded unicode chars in URLs', function(done) {
//last char is EN DASH
linkCheck(baseUrl + '/url_with_unicode–', function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
// See issues #34 and #40
it('should not URL encode already encoded characters', function(done) {
linkCheck(baseUrl + '/url_with_special_chars%28%29%2B', function(err, result) {
expect(err).to.be(null);
expect(result.err).to.be(null);
expect(result.status).to.be('alive');
expect(result.statusCode).to.be(200);
done();
});
});
});
| tcort/link-check | test/link-check.test.js | JavaScript | isc | 18,014 |
function daysLeftThisWeek (date) {
return 6 - date.getDay()
}
module.exports = daysLeftThisWeek
| akileez/toolz | src/date/daysLeftThisWeek.js | JavaScript | isc | 99 |
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
from collections import defaultdict
from shutil import copy
from shutil import copyfile
from shutil import copystat
from shutil import copytree
from tempfile import mkdtemp
import boto3
import botocore
import yaml
import sys
from .helpers import archive
from .helpers import get_environment_variable_value
from .helpers import LambdaContext
from .helpers import mkdir
from .helpers import read
from .helpers import timestamp
ARN_PREFIXES = {
"cn-north-1": "aws-cn",
"cn-northwest-1": "aws-cn",
"us-gov-west-1": "aws-us-gov",
}
log = logging.getLogger(__name__)
def load_source(module_name, module_path):
"""Loads a python module from the path of the corresponding file."""
if sys.version_info[0] == 3 and sys.version_info[1] >= 5:
import importlib.util
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
elif sys.version_info[0] == 3 and sys.version_info[1] < 5:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader(module_name, module_path)
module = loader.load_module()
return module
def cleanup_old_versions(
src, keep_last_versions, config_file="config.yaml", profile_name=None,
):
"""Deletes old deployed versions of the function in AWS Lambda.
Won't delete $Latest and any aliased version
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param int keep_last_versions:
The number of recent versions to keep and not delete
"""
if keep_last_versions <= 0:
print("Won't delete all versions. Please do this manually")
else:
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
profile_name = cfg.get("profile")
aws_access_key_id = cfg.get("aws_access_key_id")
aws_secret_access_key = cfg.get("aws_secret_access_key")
client = get_client(
"lambda",
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region"),
)
response = client.list_versions_by_function(
FunctionName=cfg.get("function_name"),
)
versions = response.get("Versions")
if len(response.get("Versions")) < keep_last_versions:
print("Nothing to delete. (Too few versions published)")
else:
version_numbers = [
elem.get("Version") for elem in versions[1:-keep_last_versions]
]
for version_number in version_numbers:
try:
client.delete_function(
FunctionName=cfg.get("function_name"),
Qualifier=version_number,
)
except botocore.exceptions.ClientError as e:
print(f"Skipping Version {version_number}: {e}")
def deploy(
src,
requirements=None,
local_package=None,
config_file="config.yaml",
profile_name=None,
preserve_vpc=False,
):
"""Deploys a new function to AWS Lambda.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder then add the handler file in the root of this directory.
# Zip the contents of this folder into a single file and output to the dist
# directory.
path_to_zip_file = build(
src,
config_file=config_file,
requirements=requirements,
local_package=local_package,
)
existing_config = get_function_config(cfg)
if existing_config:
update_function(
cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc
)
else:
create_function(cfg, path_to_zip_file)
def deploy_s3(
src,
requirements=None,
local_package=None,
config_file="config.yaml",
profile_name=None,
preserve_vpc=False,
):
"""Deploys a new function via AWS S3.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder then add the handler file in the root of this directory.
# Zip the contents of this folder into a single file and output to the dist
# directory.
path_to_zip_file = build(
src,
config_file=config_file,
requirements=requirements,
local_package=local_package,
)
use_s3 = True
s3_file = upload_s3(cfg, path_to_zip_file, use_s3)
existing_config = get_function_config(cfg)
if existing_config:
update_function(
cfg,
path_to_zip_file,
existing_config,
use_s3=use_s3,
s3_file=s3_file,
preserve_vpc=preserve_vpc,
)
else:
create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def upload(
src,
requirements=None,
local_package=None,
config_file="config.yaml",
profile_name=None,
):
"""Uploads a new function to AWS S3.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Copy all the pip dependencies required to run your code into a temporary
# folder then add the handler file in the root of this directory.
# Zip the contents of this folder into a single file and output to the dist
# directory.
path_to_zip_file = build(
src,
config_file=config_file,
requirements=requirements,
local_package=local_package,
)
upload_s3(cfg, path_to_zip_file)
def invoke(
src,
event_file="event.json",
config_file="config.yaml",
profile_name=None,
verbose=False,
):
"""Simulates a call to your function.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str alt_event:
An optional argument to override which event file to use.
:param bool verbose:
Whether to print out verbose details.
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Set AWS_PROFILE environment variable based on `--profile` option.
if profile_name:
os.environ["AWS_PROFILE"] = profile_name
# Load environment variables from the config file into the actual
# environment.
env_vars = cfg.get("environment_variables")
if env_vars:
for key, value in env_vars.items():
os.environ[key] = get_environment_variable_value(value)
# Load and parse event file.
path_to_event_file = os.path.join(src, event_file)
event = read(path_to_event_file, loader=json.loads)
# Tweak to allow module to import local modules
try:
sys.path.index(src)
except ValueError:
sys.path.append(src)
handler = cfg.get("handler")
# Inspect the handler string (<module>.<function name>) and translate it
# into a function we can execute.
fn = get_callable_handler_function(src, handler)
timeout = cfg.get("timeout")
if timeout:
context = LambdaContext(cfg.get("function_name"), timeout)
else:
context = LambdaContext(cfg.get("function_name"))
start = time.time()
results = fn(event, context)
end = time.time()
print("{0}".format(results))
if verbose:
print(
"\nexecution time: {:.8f}s\nfunction execution "
"timeout: {:2}s".format(end - start, cfg.get("timeout", 15))
)
def init(src, minimal=False):
"""Copies template files to a given directory.
:param str src:
The path to output the template lambda project files.
:param bool minimal:
Minimal possible template files (excludes event.json).
"""
templates_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "project_templates",
)
for filename in os.listdir(templates_path):
if (minimal and filename == "event.json") or filename.endswith(".pyc"):
continue
dest_path = os.path.join(templates_path, filename)
if not os.path.isdir(dest_path):
copy(dest_path, src)
def build(
src,
requirements=None,
local_package=None,
config_file="config.yaml",
profile_name=None,
):
"""Builds the file bundle.
:param str src:
The path to your Lambda ready project (folder must contain a valid
config.yaml and handler module (e.g.: service.py).
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
# Load and parse the config file.
path_to_config_file = os.path.join(src, config_file)
cfg = read_cfg(path_to_config_file, profile_name)
# Get the absolute path to the output directory and create it if it doesn't
# already exist.
dist_directory = cfg.get("dist_directory", "dist")
path_to_dist = os.path.join(src, dist_directory)
mkdir(path_to_dist)
# Combine the name of the Lambda function with the current timestamp to use
# for the output filename.
function_name = cfg.get("function_name")
output_filename = "{0}-{1}.zip".format(timestamp(), function_name)
path_to_temp = mkdtemp(prefix="aws-lambda")
pip_install_to_target(
path_to_temp, requirements=requirements, local_package=local_package,
)
# Hack for Zope.
if "zope" in os.listdir(path_to_temp):
print(
"Zope packages detected; fixing Zope package paths to "
"make them importable.",
)
# Touch.
with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"):
pass
# Gracefully handle whether ".zip" was included in the filename or not.
output_filename = (
"{0}.zip".format(output_filename)
if not output_filename.endswith(".zip")
else output_filename
)
# Allow definition of source code directories we want to build into our
# zipped package.
build_config = defaultdict(**cfg.get("build", {}))
build_source_directories = build_config.get("source_directories", "")
build_source_directories = (
build_source_directories
if build_source_directories is not None
else ""
)
source_directories = [
d.strip() for d in build_source_directories.split(",")
]
files = []
for filename in os.listdir(src):
if os.path.isfile(filename):
if filename == ".DS_Store":
continue
if filename == config_file:
continue
print("Bundling: %r" % filename)
files.append(os.path.join(src, filename))
elif os.path.isdir(filename) and filename in source_directories:
print("Bundling directory: %r" % filename)
files.append(os.path.join(src, filename))
# "cd" into `temp_path` directory.
os.chdir(path_to_temp)
for f in files:
if os.path.isfile(f):
_, filename = os.path.split(f)
# Copy handler file into root of the packages folder.
copyfile(f, os.path.join(path_to_temp, filename))
copystat(f, os.path.join(path_to_temp, filename))
elif os.path.isdir(f):
src_path_length = len(src) + 1
destination_folder = os.path.join(
path_to_temp, f[src_path_length:]
)
copytree(f, destination_folder)
# Zip them together into a single file.
# TODO: Delete temp directory created once the archive has been compiled.
path_to_zip_file = archive("./", path_to_dist, output_filename)
return path_to_zip_file
def get_callable_handler_function(src, handler):
"""Translate a string of the form "module.function" into a callable
function.
:param str src:
The path to your Lambda project containing a valid handler file.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
# "cd" into `src` directory.
os.chdir(src)
module_name, function_name = handler.split(".")
filename = get_handler_filename(handler)
path_to_module_file = os.path.join(src, filename)
module = load_source(module_name, path_to_module_file)
return getattr(module, function_name)
def get_handler_filename(handler):
"""Shortcut to get the filename from the handler string.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
module_name, _ = handler.split(".")
return "{0}.py".format(module_name)
def _install_packages(path, packages):
"""Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:param list packages:
A list of packages to be installed via pip.
"""
def _filter_blacklist(package):
blacklist = ["-i", "#", "Python==", "python-lambda=="]
return all(package.startswith(entry) is False for entry in blacklist)
filtered_packages = filter(_filter_blacklist, packages)
for package in filtered_packages:
if package.startswith("-e "):
package = package.replace("-e ", "")
print("Installing {package}".format(package=package))
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
package,
"-t",
path,
"--ignore-installed",
]
)
print(
"Install directory contents are now: {directory}".format(
directory=os.listdir(path)
)
)
def pip_install_to_target(path, requirements=None, local_package=None):
"""For a given active virtualenv, gather all installed pip packages then
copy (re-install) them to the path provided.
:param str path:
Path to copy installed pip packages to.
:param str requirements:
If set, only the packages in the supplied requirements file are
installed.
If not set then installs all packages found via pip freeze.
:param str local_package:
The path to a local package with should be included in the deploy as
well (and/or is not available on PyPi)
"""
packages = []
if not requirements:
print("Gathering pip packages")
pkgStr = subprocess.check_output(
[sys.executable, "-m", "pip", "freeze"]
)
packages.extend(pkgStr.decode("utf-8").splitlines())
else:
if os.path.exists(requirements):
print("Gathering requirement packages")
data = read(requirements)
packages.extend(data.splitlines())
if not packages:
print("No dependency packages installed!")
if local_package is not None:
if not isinstance(local_package, (list, tuple)):
local_package = [local_package]
for l_package in local_package:
packages.append(l_package)
_install_packages(path, packages)
def get_role_name(region, account_id, role):
"""Shortcut to insert the `account_id` and `role` into the iam string."""
prefix = ARN_PREFIXES.get(region, "aws")
return "arn:{0}:iam::{1}:role/{2}".format(prefix, account_id, role)
def get_account_id(
profile_name, aws_access_key_id, aws_secret_access_key, region=None,
):
"""Query STS for a users' account_id"""
client = get_client(
"sts", profile_name, aws_access_key_id, aws_secret_access_key, region,
)
return client.get_caller_identity().get("Account")
def get_client(
client,
profile_name,
aws_access_key_id,
aws_secret_access_key,
region=None,
):
"""Shortcut for getting an initialized instance of the boto3 client."""
boto3.setup_default_session(
profile_name=profile_name,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=region,
)
return boto3.client(client)
def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None):
"""Register and upload a function to AWS Lambda."""
print("Creating your new Lambda function")
byte_stream = read(path_to_zip_file, binary_file=True)
profile_name = cfg.get("profile")
aws_access_key_id = cfg.get("aws_access_key_id")
aws_secret_access_key = cfg.get("aws_secret_access_key")
account_id = get_account_id(
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region",),
)
role = get_role_name(
cfg.get("region"),
account_id,
cfg.get("role", "lambda_basic_execution"),
)
client = get_client(
"lambda",
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region"),
)
# Do we prefer development variable over config?
buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name")
func_name = os.environ.get("LAMBDA_FUNCTION_NAME") or cfg.get(
"function_name"
)
print("Creating lambda function with name: {}".format(func_name))
if use_s3:
kwargs = {
"FunctionName": func_name,
"Runtime": cfg.get("runtime", "python2.7"),
"Role": role,
"Handler": cfg.get("handler"),
"Code": {
"S3Bucket": "{}".format(buck_name),
"S3Key": "{}".format(s3_file),
},
"Description": cfg.get("description", ""),
"Timeout": cfg.get("timeout", 15),
"MemorySize": cfg.get("memory_size", 512),
"VpcConfig": {
"SubnetIds": cfg.get("subnet_ids", []),
"SecurityGroupIds": cfg.get("security_group_ids", []),
},
"Publish": True,
}
else:
kwargs = {
"FunctionName": func_name,
"Runtime": cfg.get("runtime", "python2.7"),
"Role": role,
"Handler": cfg.get("handler"),
"Code": {"ZipFile": byte_stream},
"Description": cfg.get("description", ""),
"Timeout": cfg.get("timeout", 15),
"MemorySize": cfg.get("memory_size", 512),
"VpcConfig": {
"SubnetIds": cfg.get("subnet_ids", []),
"SecurityGroupIds": cfg.get("security_group_ids", []),
},
"Publish": True,
}
if "tags" in cfg:
kwargs.update(
Tags={key: str(value) for key, value in cfg.get("tags").items()}
)
if "environment_variables" in cfg:
kwargs.update(
Environment={
"Variables": {
key: get_environment_variable_value(value)
for key, value in cfg.get("environment_variables").items()
},
},
)
client.create_function(**kwargs)
concurrency = get_concurrency(cfg)
if concurrency > 0:
client.put_function_concurrency(
FunctionName=func_name, ReservedConcurrentExecutions=concurrency
)
def update_function(
cfg,
path_to_zip_file,
existing_cfg,
use_s3=False,
s3_file=None,
preserve_vpc=False,
):
"""Updates the code of an existing Lambda function"""
print("Updating your Lambda function")
byte_stream = read(path_to_zip_file, binary_file=True)
profile_name = cfg.get("profile")
aws_access_key_id = cfg.get("aws_access_key_id")
aws_secret_access_key = cfg.get("aws_secret_access_key")
account_id = get_account_id(
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region",),
)
role = get_role_name(
cfg.get("region"),
account_id,
cfg.get("role", "lambda_basic_execution"),
)
client = get_client(
"lambda",
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region"),
)
# Do we prefer development variable over config?
buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name")
if use_s3:
client.update_function_code(
FunctionName=cfg.get("function_name"),
S3Bucket="{}".format(buck_name),
S3Key="{}".format(s3_file),
Publish=True,
)
else:
client.update_function_code(
FunctionName=cfg.get("function_name"),
ZipFile=byte_stream,
Publish=True,
)
kwargs = {
"FunctionName": cfg.get("function_name"),
"Role": role,
"Runtime": cfg.get("runtime"),
"Handler": cfg.get("handler"),
"Description": cfg.get("description", ""),
"Timeout": cfg.get("timeout", 15),
"MemorySize": cfg.get("memory_size", 512),
}
if preserve_vpc:
kwargs["VpcConfig"] = existing_cfg.get("Configuration", {}).get(
"VpcConfig"
)
if kwargs["VpcConfig"] is None:
kwargs["VpcConfig"] = {
"SubnetIds": cfg.get("subnet_ids", []),
"SecurityGroupIds": cfg.get("security_group_ids", []),
}
else:
del kwargs["VpcConfig"]["VpcId"]
else:
kwargs["VpcConfig"] = {
"SubnetIds": cfg.get("subnet_ids", []),
"SecurityGroupIds": cfg.get("security_group_ids", []),
}
if "environment_variables" in cfg:
kwargs.update(
Environment={
"Variables": {
key: str(get_environment_variable_value(value))
for key, value in cfg.get("environment_variables").items()
},
},
)
ret = client.update_function_configuration(**kwargs)
concurrency = get_concurrency(cfg)
if concurrency > 0:
client.put_function_concurrency(
FunctionName=cfg.get("function_name"),
ReservedConcurrentExecutions=concurrency,
)
elif "Concurrency" in existing_cfg:
client.delete_function_concurrency(
FunctionName=cfg.get("function_name")
)
if "tags" in cfg:
tags = {key: str(value) for key, value in cfg.get("tags").items()}
if tags != existing_cfg.get("Tags"):
if existing_cfg.get("Tags"):
client.untag_resource(
Resource=ret["FunctionArn"],
TagKeys=list(existing_cfg["Tags"].keys()),
)
client.tag_resource(Resource=ret["FunctionArn"], Tags=tags)
def upload_s3(cfg, path_to_zip_file, *use_s3):
"""Upload a function to AWS S3."""
print("Uploading your new Lambda function")
profile_name = cfg.get("profile")
aws_access_key_id = cfg.get("aws_access_key_id")
aws_secret_access_key = cfg.get("aws_secret_access_key")
client = get_client(
"s3",
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region"),
)
byte_stream = b""
with open(path_to_zip_file, mode="rb") as fh:
byte_stream = fh.read()
s3_key_prefix = cfg.get("s3_key_prefix", "/dist")
checksum = hashlib.new("md5", byte_stream).hexdigest()
timestamp = str(time.time())
filename = "{prefix}{checksum}-{ts}.zip".format(
prefix=s3_key_prefix, checksum=checksum, ts=timestamp,
)
# Do we prefer development variable over config?
buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name")
func_name = os.environ.get("LAMBDA_FUNCTION_NAME") or cfg.get(
"function_name"
)
kwargs = {
"Bucket": "{}".format(buck_name),
"Key": "{}".format(filename),
"Body": byte_stream,
}
client.put_object(**kwargs)
print("Finished uploading {} to S3 bucket {}".format(func_name, buck_name))
if use_s3:
return filename
def get_function_config(cfg):
"""Check whether a function exists or not and return its config"""
function_name = cfg.get("function_name")
profile_name = cfg.get("profile")
aws_access_key_id = cfg.get("aws_access_key_id")
aws_secret_access_key = cfg.get("aws_secret_access_key")
client = get_client(
"lambda",
profile_name,
aws_access_key_id,
aws_secret_access_key,
cfg.get("region"),
)
try:
return client.get_function(FunctionName=function_name)
except client.exceptions.ResourceNotFoundException as e:
if "Function not found" in str(e):
return False
def get_concurrency(cfg):
"""Return the Reserved Concurrent Executions if present in the config"""
concurrency = int(cfg.get("concurrency", 0))
return max(0, concurrency)
def read_cfg(path_to_config_file, profile_name):
cfg = read(path_to_config_file, loader=yaml.full_load)
if profile_name is not None:
cfg["profile"] = profile_name
elif "AWS_PROFILE" in os.environ:
cfg["profile"] = os.environ["AWS_PROFILE"]
return cfg
| nficano/python-lambda | aws_lambda/aws_lambda.py | Python | isc | 26,779 |
# Copyright (c) 2015, Max Fillinger <max@max-fillinger.net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
# The epub format specification is available at http://idpf.org/epub/201
'''Contains the EpubBuilder class to build epub2.0.1 files with the getebook
module.'''
import html
import re
import datetime
import getebook
import os.path
import re
import zipfile
__all__ = ['EpubBuilder', 'EpubTOC', 'Author']
def _normalize(name):
'''Transform "Firstname [Middlenames] Lastname" into
"Lastname, Firstname [Middlenames]".'''
split = name.split()
if len(split) == 1:
return name
return split[-1] + ', ' + ' '.join(name[0:-1])
def _make_starttag(tag, attrs):
'Write a starttag.'
out = '<' + tag
for key in attrs:
out += ' {}="{}"'.format(key, html.escape(attrs[key]))
out += '>'
return out
def _make_xml_elem(tag, text, attr = []):
'Write a flat xml element.'
out = ' <' + tag
for (key, val) in attr:
out += ' {}="{}"'.format(key, val)
if text:
out += '>{}</{}>\n'.format(text, tag)
else:
out += ' />\n'
return out
class EpubTOC(getebook.TOC):
'Table of contents.'
_head = ((
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">\n'
' <head>\n'
' <meta name="dtb:uid" content="{}" />\n'
' <meta name="dtb:depth" content="{}" />\n'
' <meta name="dtb:totalPageCount" content="0" />\n'
' <meta name="dtb:maxPageNumber" content="0" />\n'
' </head>\n'
' <docTitle>\n'
' <text>{}</text>\n'
' </docTitle>\n'
))
_doc_author = ((
' <docAuthor>\n'
' <text>{}</text>\n'
' </docAuthor>\n'
))
_navp = ((
'{0}<navPoint id="nav{1}">\n'
'{0} <navLabel>\n'
'{0} <text>{2}</text>\n'
'{0} </navLabel>\n'
'{0} <content src="{3}" />\n'
))
def _navp_xml(self, entry, indent_lvl):
'Write xml for an entry and all its subentries.'
xml = self._navp.format(' '*indent_lvl, str(entry.no), entry.text,
entry.target)
for sub in entry.entries:
xml += self._navp_xml(sub, indent_lvl+1)
xml += ' '*indent_lvl + '</navPoint>\n'
return xml
def write_xml(self, uid, title, authors):
'Write the xml code for the table of contents.'
xml = self._head.format(uid, self.max_depth, title)
for aut in authors:
xml += self._doc_author.format(aut)
xml += ' <navMap>\n'
for entry in self.entries:
xml += self._navp_xml(entry, 2)
xml += ' </navMap>\n</ncx>'
return xml
class _Fileinfo:
'Information about a component file of an epub.'
def __init__(self, name, in_spine = True, guide_title = None,
guide_type = None):
'''Initialize the object. If the file does not belong in the
reading order, in_spine should be set to False. If it should
appear in the guide, set guide_title and guide_type.'''
self.name = name
(self.ident, ext) = os.path.splitext(name)
name_split = name.rsplit('.', 1)
self.ident = name_split[0]
self.in_spine = in_spine
self.guide_title = guide_title
self.guide_type = guide_type
# Infer media-type from file extension
ext = ext.lower()
if ext in ('.htm', '.html', '.xhtml'):
self.media_type = 'application/xhtml+xml'
elif ext in ('.png', '.gif', '.jpeg'):
self.media_type = 'image/' + ext
elif ext == '.jpg':
self.media_type = 'image/jpeg'
elif ext == '.css':
self.media_type = 'text/css'
elif ext == '.ncx':
self.media_type = 'application/x-dtbncx+xml'
else:
raise ValueError('Can\'t infer media-type from extension: %s' % ext)
def manifest_entry(self):
'Write the XML element for the manifest.'
return _make_xml_elem('item', '',
[
('href', self.name),
('id', self.ident),
('media-type', self.media_type)
])
def spine_entry(self):
'''Write the XML element for the spine.
(Empty string if in_spine is False.)'''
if self.in_spine:
return _make_xml_elem('itemref', '', [('idref', self.ident)])
else:
return ''
def guide_entry(self):
'''Write the XML element for the guide.
(Empty string if no guide title and type are given.)'''
if self.guide_title and self.guide_type:
return _make_xml_elem('reference', '',
[
('title', self.guide_title),
('type', self.guide_type),
('href', self.name)
])
else:
return ''
class _EpubMeta:
'Metadata entry for an epub file.'
def __init__(self, tag, text, *args):
'''The metadata entry is an XML element. *args is used for
supplying the XML element's attributes as (key, value) pairs.'''
self.tag = tag
self.text = text
self.attr = args
def write_xml(self):
'Write the XML element.'
return _make_xml_elem(self.tag, self.text, self.attr)
def __repr__(self):
'Returns the text.'
return self.text
def __str__(self):
'Returns the text.'
return self.text
class _EpubDate(_EpubMeta):
'Metadata element for the publication date.'
_date_re = re.compile('^([0-9]{4})(-[0-9]{2}(-[0-9]{2})?)?$')
def __init__(self, date):
'''date must be a string of the form "YYYY[-MM[-DD]]". If it is
not of this form, or if the date is invalid, ValueError is
raised.'''
m = self._date_re.match(date)
if not m:
raise ValueError('invalid date format')
year = int(m.group(1))
try:
mon = int(m.group(2)[1:])
if mon < 0 or mon > 12:
raise ValueError('month must be in 1..12')
except IndexError:
pass
try:
day = int(m.group(3)[1:])
datetime.date(year, mon, day) # raises ValueError if invalid
except IndexError:
pass
self.tag = 'dc:date'
self.text = date
self.attr = ()
class _EpubLang(_EpubMeta):
'Metadata element for the language of the book.'
_lang_re = re.compile('^[a-z]{2}(-[A-Z]{2})?$')
def __init__(self, lang):
'''lang must be a lower-case two-letter language code,
optionally followed by a "-" and a upper-case two-letter country
code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")'''
if self._lang_re.match(lang):
self.tag = 'dc:language'
self.text = lang
self.attr = ()
else:
raise ValueError('invalid language format')
class Author(_EpubMeta):
'''To control the file-as and role attribute for the authors, pass
an Author object to the EpubBuilder instead of a string. The file-as
attribute is a form of the name used for sorting. The role attribute
describes how the person was involved in the work.
You ONLY need this if an author's name is not of the form
"Given-name Family-name", or if you want to specify a role other
than author. Otherwise, you can just pass a string.
The value of role should be a MARC relator, e.g., "aut" for author
or "edt" for editor. See http://www.loc.gov/marc/relators/ for a
full list.'''
def __init__(self, name, fileas = None, role = 'aut'):
'''Initialize the object. If the argument "fileas" is not given,
"Last-name, First-name" is used for the file-as attribute. If
the argument "role" is not given, "aut" is used for the role
attribute.'''
if not fileas:
fileas = _normalize(name)
self.tag = 'dc:creator'
self.text = name
self.attr = (('opf:file-as', fileas), ('opf:role', role))
class _OPFfile:
'''Class for writing the OPF (Open Packaging Format) file for an
epub file. The OPF file contains the metadata, a manifest of all
component files in the epub, a "spine" which specifies the reading
order and a guide which points to important components of the book
such as the title page.'''
_opf = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<package version="2.0" xmlns="http://www.idpf.org/2007/opf" unique_identifier="uid_id">\n'
' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">\n'
'{}'
' </metadata>\n'
' <manifest>\n'
'{}'
' </manifest>\n'
' <spine toc="toc">\n'
'{}'
' </spine>\n'
' <guide>\n'
'{}'
' </guide>\n'
'</package>\n'
)
def __init__(self):
'Initialize.'
self.meta = []
self.filelist = []
def write_xml(self):
'Write the XML code for the OPF file.'
metadata = ''
for elem in self.meta:
metadata += elem.write_xml()
manif = ''
spine = ''
guide = ''
for finfo in self.filelist:
manif += finfo.manifest_entry()
spine += finfo.spine_entry()
guide += finfo.guide_entry()
return self._opf.format(metadata, manif, spine, guide)
class EpubBuilder:
'''Builds an epub2.0.1 file. Some of the attributes of this class
(title, uid, lang) are marked as "mandatory" because they represent
metadata that is required by the epub specification. If these
attributes are left unset, default values will be used.'''
_style_css = (
'h1, h2, h3, h4, h5, h6 {\n'
' text-align: center;\n'
'}\n'
'p {\n'
' text-align: justify;\n'
' margin-top: 0.125em;\n'
' margin-bottom: 0em;\n'
' text-indent: 1.0em;\n'
'}\n'
'.getebook-tp {\n'
' margin-top: 8em;\n'
'}\n'
'.getebook-tp-authors {\n'
' font-size: 2em;\n'
' text-align: center;\n'
' margin-bottom: 1em;\n'
'}\n'
'.getebook-tp-title {\n'
' font-weight: bold;\n'
' font-size: 3em;\n'
' text-align: center;\n'
'}\n'
'.getebook-tp-sub {\n'
' text-align: center;\n'
' font-weight: normal;\n'
' font-size: 0.8em;\n'
' margin-top: 1em;\n'
'}\n'
'.getebook-false-h {\n'
' font-weight: bold;\n'
' font-size: 1.5em;\n'
'}\n'
'.getebook-small-h {\n'
' font-style: normal;\n'
' font-weight: normal;\n'
' font-size: 0.8em;\n'
'}\n'
)
_container_xml = (
'<?xml version="1.0"?>\n'
'<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
' <rootfiles>\n'
' <rootfile full-path="package.opf" media-type="application/oebps-package+xml"/>\n'
' </rootfiles>\n'
'</container>\n'
)
_html = (
'<?xml version="1.0" encoding="utf-8"?>\n'
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n'
'<html xmlns="http://www.w3.org/1999/xhtml">\n'
' <head>\n'
' <title>{}</title>\n'
' <meta http-equiv="content-type" content="application/xtml+xml; charset=utf-8" />\n'
' <link href="style.css" rel="stylesheet" type="text/css" />\n'
' </head>\n'
' <body>\n{}'
' </body>\n'
'</html>\n'
)
_finalized = False
def __init__(self, epub_file):
'''Initialize the EpubBuilder instance. "epub_file" is the
filename of the epub to be created.'''
self.epub_f = zipfile.ZipFile(epub_file, 'w', zipfile.ZIP_DEFLATED)
self.epub_f.writestr('mimetype', 'application/epub+zip')
self.epub_f.writestr('META-INF/container.xml', self._container_xml)
self.toc = EpubTOC()
self.opf = _OPFfile()
self.opf.filelist.append(_Fileinfo('toc.ncx', False))
self.opf.filelist.append(_Fileinfo('style.css', False))
self._authors = []
self.opt_meta = {} # Optional metadata (other than authors)
self.content = ''
self.part_no = 0
self.cont_filename = 'part%03d.html' % self.part_no
def __enter__(self):
'Return self for use in with ... as ... statement.'
return self
def __exit__(self, except_type, except_val, traceback):
'Call finalize() and close the file.'
try:
self.finalize()
finally:
# Close again in case an exception happened in finalize()
self.epub_f.close()
return False
@property
def uid(self):
'''Unique identifier of the ebook. (mandatory)
If this property is left unset, a pseudo-random string will be
generated which is long enough for collisions with existing
ebooks to be extremely unlikely.'''
try:
return self._uid
except AttributeError:
import random
from string import (ascii_letters, digits)
alnum = ascii_letters + digits
self.uid = ''.join([random.choice(alnum) for i in range(15)])
return self._uid
@uid.setter
def uid(self, val):
self._uid = _EpubMeta('dc:identifier', str(val), ('id', 'uid_id'))
@property
def title(self):
'''Title of the ebook. (mandatory)
If this property is left unset, it defaults to "Untitled".'''
try:
return self._title
except AttributeError:
self.title = 'Untitled'
return self._title
@title.setter
def title(self, val):
# If val is not a string, raise TypeError now rather than later.
self._title = _EpubMeta('dc:title', '' + val)
@property
def lang(self):
'''Language of the ebook. (mandatory)
The language must be given as a lower-case two-letter code, optionally
followed by a "-" and an upper-case two-letter country code.
(e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")
If this property is left unset, it defaults to "en".'''
try:
return self._lang
except AttributeError:
self.lang = 'en'
return self._lang
@lang.setter
def lang(self, val):
self._lang = _EpubLang(val)
@property
def author(self):
'''Name of the author. (optional)
If there are multiple authors, pass a list of strings.
To control the file-as and role attribute, use author objects instead
of strings; file-as is an alternate form of the name used for sorting.
For a description of the role attribute, see the docstring of the
author class.'''
if len(self._authors) == 1:
return self._authors[0]
return tuple([aut for aut in self._authors])
@author.setter
def author(self, val):
if isinstance(val, Author) or isinstance(val, str):
authors = [val]
else:
authors = val
for aut in authors:
try:
self._authors.append(Author('' + aut))
except TypeError:
# aut is not a string, so it should be an Author object
self._authors.append(aut)
@author.deleter
def author(self):
self._authors = []
@property
def date(self):
'''Publication date. (optional)
Must be given in "YYYY[-MM[-DD]]" format.'''
try:
return self.opt_meta['date']
except KeyError:
return None
@date.setter
def date(self, val):
self.opt_meta['date'] = _EpubDate(val)
@date.deleter
def date(self):
del self._date
@property
def rights(self):
'Copyright/licensing information. (optional)'
try:
return self.opt_meta['rights']
except KeyError:
return None
@rights.setter
def rights(self, val):
self.opt_meta['rights'] = _EpubMeta('dc:rights', '' + val)
@rights.deleter
def rights(self):
del self._rights
@property
def publisher(self):
'Publisher name. (optional)'
try:
return self.opt_meta['publisher']
except KeyError:
return None
@publisher.setter
def publisher(self, val):
self.opt_meta['publisher'] = _EpubMeta('dc:publisher', '' + val)
@publisher.deleter
def publisher(self):
del self._publisher
@property
def style_css(self):
'''CSS stylesheet for the files that are generated by the EpubBuilder
instance. Can be overwritten or extended, but not deleted.'''
return self._style_css
@style_css.setter
def style_css(self, val):
self._style_css = '' + val
def titlepage(self, main_title = None, subtitle = None):
'''Create a title page for the ebook. If no main_title is given,
the title attribute of the EpubBuilder instance is used.'''
tp = '<div class="getebook-tp">\n'
if len(self._authors) >= 1:
if len(self._authors) == 1:
aut_str = str(self._authors[0])
else:
aut_str = ', '.join(str(self._authors[0:-1])) + ', and ' \
+ str(self._authors[-1])
tp += '<div class="getebook-tp-authors">%s</div>\n' % aut_str
if not main_title:
main_title = str(self.title)
tp += '<div class="getebook-tp-title">%s' % main_title
if subtitle:
tp += '<div class="getebook-tp-sub">%s</div>' % subtitle
tp += '</div>\n</div>\n'
self.opf.filelist.insert(0, _Fileinfo('title.html',
guide_title = 'Titlepage', guide_type = 'title-page'))
self.epub_f.writestr('title.html', self._html.format(self.title, tp))
def headingpage(self, heading, subtitle = None, toc_text = None):
'''Create a page containing only a (large) heading, optionally
with a smaller subtitle. If toc_text is not given, it defaults
to the heading.'''
self.new_part()
tag = 'h%d' % min(6, self.toc.depth)
self.content += '<div class="getebook-tp">'
self.content += '<{} class="getebook-tp-title">{}'.format(tag, heading)
if subtitle:
self.content += '<div class="getebook-tp-sub">%s</div>' % subtitle
self.content += '</%s>\n' % tag
if not toc_text:
toc_text = heading
self.toc.new_entry(toc_text, self.cont_filename)
self.new_part()
def insert_file(self, name, in_spine = False, guide_title = None,
guide_type = None, arcname = None):
'''Include an external file into the ebook. By default, it will
be added to the archive under its basename; the argument
"arcname" can be used to specify a different name.'''
if not arcname:
arcname = os.path.basename(name)
self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title,
guide_type))
self.epub_f.write(name, arcname)
def add_file(self, arcname, str_or_bytes, in_spine = False,
guide_title = None, guide_type = None):
'''Add the string or bytes instance str_or_bytes to the archive
under the name arcname.'''
self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title,
guide_type))
self.epub_f.writestr(arcname, str_or_bytes)
def false_heading(self, elem):
'''Handle a "false heading", i.e., text that appears in heading
tags in the source even though it is not a chapter heading.'''
elem.attrs['class'] = 'getebook-false-h'
elem.tag = 'p'
self.handle_elem(elem)
def _heading(self, elem):
'''Write a heading.'''
# Handle paragraph heading if we have one waiting (see the
# par_heading method). We don\'t use _handle_par_h here because
# we merge it with the subsequent proper heading.
try:
par_h = self.par_h
del self.par_h
except AttributeError:
toc_text = elem.text
else:
# There is a waiting paragraph heading, we merge it with the
# new heading.
toc_text = par_h.text + '. ' + elem.text
par_h.tag = 'div'
par_h.attrs['class'] = 'getebook-small-h'
elem.children.insert(0, par_h)
# Set the class attribute value.
elem.attrs['class'] = 'getebook-chapter-h'
self.toc.new_entry(toc_text, self.cont_filename)
# Add heading to the epub.
tag = 'h%d' % min(self.toc.depth, 6)
self.content += _make_starttag(tag, elem.attrs)
for elem in elem.children:
self.handle_elem(elem)
self.content += '</%s>\n' % tag
def par_heading(self, elem):
'''Handle a "paragraph heading", i.e., a chaper heading or part
of a chapter heading inside paragraph tags. If it is immediately
followed by a heading, they will be merged into one.'''
self.par_h = elem
def _handle_par_h(self):
'Check if there is a waiting paragraph heading and handle it.'
try:
self._heading(self.par_h)
except AttributeError:
pass
def handle_elem(self, elem):
'Handle html element as supplied by getebook.EbookParser.'
try:
tag = elem.tag
except AttributeError:
# elem should be a string
is_string = True
tag = None
else:
is_string = False
if tag in getebook._headings:
self._heading(elem)
else:
# Handle waiting par_h if necessary (see par_heading)
try:
self._heading(self.par_h)
except AttributeError:
pass
if is_string:
self.content += elem
elif tag == 'br':
self.content += '<br />\n'
elif tag == 'img':
self.content += self._handle_image(elem.attrs) + '\n'
elif tag == 'a' or tag == 'noscript':
# Ignore tag, just write child elements
for child in elem.children:
self.handle_elem(child)
else:
self.content += _make_starttag(tag, elem.attrs)
for child in elem.children:
self.handle_elem(child)
self.content += '</%s>' % tag
if tag == 'p':
self.content += '\n'
def _handle_image(self, attrs):
'Returns the alt text of an image tag.'
try:
return attrs['alt']
except KeyError:
return ''
def new_part(self):
'''Begin a new part of the epub. Write the current html document
to the archive and begin a new one.'''
# Handle waiting par_h (see par_heading)
try:
self._heading(self.par_h)
except AttributeError:
pass
if self.content:
html = self._html.format(self.title, self.content)
self.epub_f.writestr(self.cont_filename, html)
self.part_no += 1
self.content = ''
self.cont_filename = 'part%03d.html' % self.part_no
self.opf.filelist.append(_Fileinfo(self.cont_filename))
def finalize(self):
'Complete and close the epub file.'
# Handle waiting par_h (see par_heading)
if self._finalized:
# Avoid finalizing twice. Otherwise, calling finalize inside
# a with-block would lead to an exception when __exit__
# calls finalize again.
return
try:
self._heading(self.par_h)
except AttributeError:
pass
if self.content:
html = self._html.format(self.title, self.content)
self.epub_f.writestr(self.cont_filename, html)
self.opf.meta = [self.uid, self.lang, self.title] + self._authors
self.opf.meta += self.opt_meta.values()
self.epub_f.writestr('package.opf', self.opf.write_xml())
self.epub_f.writestr('toc.ncx',
self.toc.write_xml(self.uid, self.title, self._authors))
self.epub_f.writestr('style.css', self._style_css)
self.epub_f.close()
self._finalized = True
| mfil/getebook | getebook/epub.py | Python | isc | 25,314 |
package minecraft
import (
"testing"
"vimagination.zapto.org/minecraft/nbt"
)
func TestNew(t *testing.T) {
biomes := make(nbt.ByteArray, 256)
biome := int8(-1)
blocks := make(nbt.ByteArray, 4096)
add := make(nbt.ByteArray, 2048)
data := make(nbt.ByteArray, 2048)
for i := 0; i < 256; i++ {
biomes[i] = biome
//if biome++; biome >= 23 {
// biome = -1
//}
}
dataTag := nbt.NewTag("", nbt.Compound{
nbt.NewTag("Level", nbt.Compound{
nbt.NewTag("Biomes", biomes),
nbt.NewTag("HeightMap", make(nbt.IntArray, 256)),
nbt.NewTag("InhabitedTime", nbt.Long(0)),
nbt.NewTag("LastUpdate", nbt.Long(0)),
nbt.NewTag("Sections", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(0)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(1)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(3)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(10)),
},
}),
nbt.NewTag("TileEntities", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("id", nbt.String("test1")),
nbt.NewTag("x", nbt.Int(-191)),
nbt.NewTag("y", nbt.Int(13)),
nbt.NewTag("z", nbt.Int(379)),
nbt.NewTag("testTag", nbt.Byte(1)),
},
nbt.Compound{
nbt.NewTag("id", nbt.String("test2")),
nbt.NewTag("x", nbt.Int(-191)),
nbt.NewTag("y", nbt.Int(17)),
nbt.NewTag("z", nbt.Int(372)),
nbt.NewTag("testTag", nbt.Long(8)),
},
}),
nbt.NewTag("Entities", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("id", nbt.String("testEntity1")),
nbt.NewTag("Pos", &nbt.ListDouble{
nbt.Double(-190),
nbt.Double(13),
nbt.Double(375),
}),
nbt.NewTag("Motion", &nbt.ListDouble{
nbt.Double(1),
nbt.Double(13),
nbt.Double(11),
}),
nbt.NewTag("Rotation", &nbt.ListFloat{
nbt.Float(13),
nbt.Float(11),
}),
nbt.NewTag("FallDistance", nbt.Float(0)),
nbt.NewTag("Fire", nbt.Short(-1)),
nbt.NewTag("Air", nbt.Short(300)),
nbt.NewTag("OnGround", nbt.Byte(1)),
nbt.NewTag("Dimension", nbt.Int(0)),
nbt.NewTag("Invulnerable", nbt.Byte(0)),
nbt.NewTag("PortalCooldown", nbt.Int(0)),
nbt.NewTag("UUIDMost", nbt.Long(0)),
nbt.NewTag("UUIDLease", nbt.Long(0)),
nbt.NewTag("Riding", nbt.Compound{}),
},
nbt.Compound{
nbt.NewTag("id", nbt.String("testEntity2")),
nbt.NewTag("Pos", &nbt.ListDouble{
nbt.Double(-186),
nbt.Double(2),
nbt.Double(378),
}),
nbt.NewTag("Motion", &nbt.ListDouble{
nbt.Double(17.5),
nbt.Double(1000),
nbt.Double(54),
}),
nbt.NewTag("Rotation", &nbt.ListFloat{
nbt.Float(11),
nbt.Float(13),
}),
nbt.NewTag("FallDistance", nbt.Float(30)),
nbt.NewTag("Fire", nbt.Short(4)),
nbt.NewTag("Air", nbt.Short(30)),
nbt.NewTag("OnGround", nbt.Byte(0)),
nbt.NewTag("Dimension", nbt.Int(0)),
nbt.NewTag("Invulnerable", nbt.Byte(1)),
nbt.NewTag("PortalCooldown", nbt.Int(10)),
nbt.NewTag("UUIDMost", nbt.Long(1450)),
nbt.NewTag("UUIDLease", nbt.Long(6435)),
nbt.NewTag("Riding", nbt.Compound{}),
},
}),
nbt.NewTag("TileTicks", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("i", nbt.Int(0)),
nbt.NewTag("t", nbt.Int(0)),
nbt.NewTag("p", nbt.Int(0)),
nbt.NewTag("x", nbt.Int(-192)),
nbt.NewTag("y", nbt.Int(0)),
nbt.NewTag("z", nbt.Int(368)),
},
nbt.Compound{
nbt.NewTag("i", nbt.Int(1)),
nbt.NewTag("t", nbt.Int(34)),
nbt.NewTag("p", nbt.Int(12)),
nbt.NewTag("x", nbt.Int(-186)),
nbt.NewTag("y", nbt.Int(11)),
nbt.NewTag("z", nbt.Int(381)),
},
}),
nbt.NewTag("TerrainPopulated", nbt.Byte(1)),
nbt.NewTag("xPos", nbt.Int(-12)),
nbt.NewTag("zPos", nbt.Int(23)),
}),
})
if _, err := newChunk(-12, 23, dataTag); err != nil {
t.Fatalf("reveived unexpected error during testing, %q", err.Error())
}
}
func TestBiomes(t *testing.T) {
chunk, _ := newChunk(0, 0, nbt.Tag{})
for b := Biome(0); b < 23; b++ {
biome := b
for x := int32(0); x < 16; x++ {
for z := int32(0); z < 16; z++ {
chunk.SetBiome(x, z, biome)
if newB := chunk.GetBiome(x, z); newB != biome {
t.Errorf("error setting biome at co-ordinates, expecting %q, got %q", biome.String(), newB.String())
}
}
}
}
}
func TestBlock(t *testing.T) {
chunk, _ := newChunk(0, 0, nbt.Tag{})
testBlocks := []struct {
Block
x, y, z int32
recheck bool
}{
//Test simple set
{
Block{
ID: 12,
},
0, 0, 0,
true,
},
//Test higher ids
{
Block{
ID: 853,
},
1, 0, 0,
true,
},
{
Block{
ID: 463,
},
2, 0, 0,
true,
},
{
Block{
ID: 1001,
},
3, 0, 0,
true,
},
//Test data set
{
Block{
ID: 143,
Data: 12,
},
0, 1, 0,
true,
},
{
Block{
ID: 153,
Data: 4,
},
1, 1, 0,
true,
},
{
Block{
ID: 163,
Data: 5,
},
2, 1, 0,
true,
},
//Test metadata [un]set
{
Block{
metadata: nbt.Compound{
nbt.NewTag("testInt2", nbt.Int(1743)),
nbt.NewTag("testString2", nbt.String("world")),
},
},
0, 0, 1,
true,
},
{
Block{
metadata: nbt.Compound{
nbt.NewTag("testInt", nbt.Int(15)),
nbt.NewTag("testString", nbt.String("hello")),
},
},
1, 0, 1,
false,
},
{
Block{},
1, 0, 1,
true,
},
//Test tick [un]set
{
Block{
ticks: []Tick{{123, 1, 4}, {123, 7, -1}},
},
0, 1, 1,
true,
},
{
Block{
ticks: []Tick{{654, 4, 6}, {4, 63, 5}, {4, 5, 9}},
},
1, 1, 1,
false,
},
{
Block{},
1, 1, 1,
true,
},
}
for _, tB := range testBlocks {
chunk.SetBlock(tB.x, tB.y, tB.z, tB.Block)
if block := chunk.GetBlock(tB.x, tB.y, tB.z); !tB.Block.EqualBlock(block) {
t.Errorf("blocks do not match, expecting %s, got %s", tB.Block.String(), block.String())
}
}
for _, tB := range testBlocks {
if tB.recheck {
if block := chunk.GetBlock(tB.x, tB.y, tB.z); !tB.Block.EqualBlock(block) {
t.Errorf("blocks do not match, expecting:-\n%s\ngot:-\n%s", tB.Block.String(), block.String())
}
}
}
}
func TestHeightMap(t *testing.T) {
tests := []struct {
x, y, z int32
Block
height int32
}{
{0, 0, 0, Block{}, 0},
{1, 0, 0, Block{ID: 1}, 1},
{1, 1, 0, Block{ID: 1}, 2},
{1, 0, 0, Block{}, 2},
{1, 1, 0, Block{}, 0},
{2, 10, 0, Block{ID: 1}, 11},
{2, 12, 0, Block{ID: 1}, 13},
{2, 12, 0, Block{}, 11},
{2, 10, 0, Block{}, 0},
{3, 15, 0, Block{ID: 1}, 16},
{3, 16, 0, Block{ID: 1}, 17},
{3, 16, 0, Block{}, 16},
{3, 15, 0, Block{}, 0},
{4, 31, 0, Block{ID: 1}, 32},
{4, 32, 0, Block{ID: 1}, 33},
{4, 32, 0, Block{}, 32},
{4, 31, 0, Block{}, 0},
{5, 16, 0, Block{ID: 1}, 17},
{5, 32, 0, Block{ID: 1}, 33},
{5, 32, 0, Block{}, 17},
{5, 16, 0, Block{}, 0},
}
chunk, _ := newChunk(0, 0, nbt.Tag{})
for n, test := range tests {
chunk.SetBlock(test.x, test.y, test.z, test.Block)
if h := chunk.GetHeight(test.x, test.z); h != test.height {
t.Errorf("test %d: expecting height %d, got %d", n+1, test.height, h)
}
}
}
| MJKWoolnough/minecraft | chunk_test.go | GO | isc | 7,980 |
using System.Collections.Generic;
namespace ConsoleDemo.Visitor.v0
{
public class CommandsManager
{
readonly List<object> items = new List<object>();
// The client class has a structure (a list in this case) of items (commands).
// The client knows how to iterate through the structure
// The client would need to do different operations on the items from the structure when iterating it
}
} | iQuarc/Code-Design-Training | DesignPatterns/ConsoleDemo/Visitor/v0/CommandsManager.cs | C# | mit | 440 |
var contenedor = {};
var json = [];
var json_active = [];
var timeout;
var result = {};
$(document).ready(function() {
$('#buscador').keyup(function() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(function() {
search();
}, 100);
});
$("body").on('change', '#result', function() {
result = $("#result").val();
load_content(json);
});
$("body").on('click', '.asc', function() {
var name = $(this).parent().attr('rel');
console.log(name);
$(this).removeClass("asc").addClass("desc");
order(name, true);
});
$("body").on('click', '.desc', function() {
var name = $(this).parent().attr('rel');
$(this).removeClass("desc").addClass("asc");
order(name, false);
});
});
function update(id,parent,valor){
for (var i=0; i< json.length; i++) {
if (json[i].id === id){
json[i][parent] = valor;
return;
}
}
}
function load_content(json) {
max = result;
data = json.slice(0, max);
json_active = json;
$("#numRows").html(json.length);
contenedor.html('');
2
var list = table.find("th[rel]");
var html = '';
$.each(data, function(i, value) {
html += '<tr id="' + value.id + '">';
$.each(list, function(index) {
valor = $(this).attr('rel');
if (valor != 'acction') {
if ($(this).hasClass("editable")) {
html += '<td><span class="edition" rel="' + value.id + '">' + value[valor] .substring(0, 60) +'</span></td>';
} else if($(this).hasClass("view")){
if(value[valor].length > 1){
var class_1 = $(this).data('class');
html += '<td><a href="javascript:void(0)" class="'+class_1+'" rel="'+ value[valor] + '" data-id="' + value.id + '"></a></td>';
}else{
html += '<td></td>';
}
}else{
html += '<td>' + value[valor] + '</td>';
}
} else {
html += '<td>';
$.each(acction, function(k, data) {
html += '<a class="' + data.class + '" rel="' + value[data.rel] + '" href="' + data.link + value[data.parameter] + '" target="'+data.target+'" >' + data.button + '</a>';
});
html += "</td>";
}
if (index >= list.length - 1) {
html += '</tr>';
contenedor.append(html);
html = '';
}
});
});
}
function selectedRow(json) {
var num = result;
var rows = json.length;
var total = rows / num;
var cant = Math.floor(total);
$("#result").html('');
for (i = 0; i < cant; i++) {
$("#result").append("<option value=\"" + parseInt(num) + "\">" + num + "</option>");
num = num + result;
}
$("#result").append("<option value=\"" + parseInt(rows) + "\">" + rows + "</option>");
}
function order(prop, asc) {
json = json.sort(function(a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
contenedor.html('');
load_content(json);
}
function search() {
var list = table.find("th[rel]");
var data = [];
var serch = $("#buscador").val();
json.forEach(function(element, index, array) {
$.each(list, function(index) {
valor = $(this).attr('rel');
if (element[valor]) {
if (element[valor].like('%' + serch + '%')) {
data.push(element);
return false;
}
}
});
});
contenedor.html('');
load_content(data);
}
String.prototype.like = function(search) {
if (typeof search !== 'string' || this === null) {
return false;
}
search = search.replace(new RegExp("([\\.\\\\\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:\\-])", "g"), "\\$1");
search = search.replace(/%/g, '.*').replace(/_/g, '.');
return RegExp('^' + search + '$', 'gi').test(this);
}
function export_csv(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
// CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ';';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '";';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
// var fileName = "Report_";
//fileName += ReportTitle.replace(/ /g,"_");
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = ReportTitle + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} | mpandolfelli/papelera | js/function.js | JavaScript | mit | 5,520 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Username.php 24594 2012-01-05 21:27:01Z matthew $
*/
/**
* @see Zend_Gdata_Extension
*/
// require_once 'Zend/Gdata/Extension.php';
/**
* Represents the yt:username element
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube_Extension_Username extends Zend_Gdata_Extension
{
protected $_rootElement = 'username';
protected $_rootNamespace = 'yt';
public function __construct($text = null)
{
$this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
parent::__construct();
$this->_text = $text;
}
}
| levfurtado/scoops | vendor/bombayworks/zendframework1/library/Zend/Gdata/YouTube/Extension/Username.php | PHP | mit | 1,488 |
module V1
class EventUserSchedulesController < ApplicationController
before_action :set_event_session, only: [:create]
# POST /event_user_schedules
def create
@event_user_schedule = current_user.add_session_to_my_schedule(@event_session)
if @event_user_schedule.save
render json: @event_user_schedule, serializer: EventUserScheduleShortSerializer, root: "event_user_schedule", status: :created
else
render json: @event_user_schedule.errors, status: :unprocessable_entity
end
end
# DELETE /event_user_schedules/:id
def destroy
@event_user_schedule = EventUserSchedule.find(params[:id])
if @event_user_schedule.event_user.user == current_user
@event_user_schedule.destroy
head :no_content
else
head :forbidden
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def event_user_schedule_params
params.require(:event_user_schedule).permit(:event_session_id)
end
def set_event_session
@event_session = EventSession.find(event_user_schedule_params[:event_session_id])
end
end
end | danjohnson3141/rest_api | app/controllers/v1/event_user_schedules_controller.rb | Ruby | mit | 1,200 |
package com.jeecg.qywx.core.service;
import com.jeecg.qywx.base.entity.QywxReceivetext;
/**
* 文本处理接口
* @author 付明星
*
*/
public interface TextDealInterfaceService {
/**
* 文本消息处理接口
* @param receiveText 文本消息实体类
*/
void dealTextMessage(QywxReceivetext receiveText);
}
| xiongmaoshouzha/test | jeecg-p3-biz-qywx/src/main/java/com/jeecg/qywx/core/service/TextDealInterfaceService.java | Java | mit | 326 |
<?php namespace EugeneTolok\Telegram\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class BuilderTableUpdateEugenetolokTelegramDialogsSteps2 extends Migration
{
public function up()
{
Schema::table('eugenetolok_telegram_dialogs_steps', function($table)
{
$table->increments('id');
});
}
public function down()
{
Schema::table('eugenetolok_telegram_dialogs_steps', function($table)
{
$table->dropColumn('id');
});
}
}
| eugenetolok/easy-telegram-bot | updates/builder_table_update_eugenetolok_telegram_dialogs_steps_2.php | PHP | mit | 553 |
import React from 'react';
import ons from 'onsenui';
import {
Page,
Toolbar,
BackButton,
LazyList,
ListItem
} from 'react-onsenui';
class InfiniteScroll extends React.Component {
renderRow(index) {
return (
<ListItem key={index}>
{'Item ' + (index + 1)}
</ListItem>
);
}
renderToolbar() {
return (
<Toolbar>
<div className='left'>
<BackButton>Back</BackButton>
</div>
<div className='center'>
Infinite scroll
</div>
</Toolbar>
);
}
render() {
return (
<Page renderToolbar={this.renderToolbar}>
<LazyList
length={10000}
renderRow={this.renderRow}
calculateItemHeight={() => ons.platform.isAndroid() ? 77 : 45}
/>
</Page>
);
}
}
module.exports = InfiniteScroll;
| gnetsys/OnsenUIv2-React-PhoneGap-Starter-Kit | www/components/InfiniteScroll.js | JavaScript | mit | 854 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datafactory.v2018_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* The location of Google Cloud Storage dataset.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class)
@JsonTypeName("GoogleCloudStorageLocation")
public class GoogleCloudStorageLocation extends DatasetLocation {
/**
* Specify the bucketName of Google Cloud Storage. Type: string (or
* Expression with resultType string).
*/
@JsonProperty(value = "bucketName")
private Object bucketName;
/**
* Specify the version of Google Cloud Storage. Type: string (or Expression
* with resultType string).
*/
@JsonProperty(value = "version")
private Object version;
/**
* Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @return the bucketName value
*/
public Object bucketName() {
return this.bucketName;
}
/**
* Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @param bucketName the bucketName value to set
* @return the GoogleCloudStorageLocation object itself.
*/
public GoogleCloudStorageLocation withBucketName(Object bucketName) {
this.bucketName = bucketName;
return this;
}
/**
* Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @return the version value
*/
public Object version() {
return this.version;
}
/**
* Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string).
*
* @param version the version value to set
* @return the GoogleCloudStorageLocation object itself.
*/
public GoogleCloudStorageLocation withVersion(Object version) {
this.version = version;
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/datafactory/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/datafactory/v2018_06_01/GoogleCloudStorageLocation.java | Java | mit | 2,402 |
$js.module({
prerequisite:[
'/{$jshome}/modules/splice.module.extensions.js'
],
imports:[
{ Inheritance : '/{$jshome}/modules/splice.inheritance.js' },
{'SpliceJS.UI':'../splice.ui.js'},
'splice.controls.pageloader.html'
],
definition:function(){
var scope = this;
var
imports = scope.imports
;
var
Class = imports.Inheritance.Class
, UIControl = imports.SpliceJS.UI.UIControl
;
var PageLoader = Class(function PageLoaderController(){
this.base();
}).extend(UIControl);
scope.exports(
PageLoader
);
}
})
| jonahgroup/SpliceJS.Modules | src/ui.controls/splice.controls.pageloader.js | JavaScript | mit | 545 |
RSpec.describe AuthorizeIf do
let(:controller) {
double(:dummy_controller, controller_name: "dummy", action_name: "index").
extend(AuthorizeIf)
}
describe "#authorize_if" do
context "when object is given" do
it "returns true if truthy object is given" do
expect(controller.authorize_if(true)).to eq true
expect(controller.authorize_if(Object.new)).to eq true
end
it "raises NotAuthorizedError if falsey object is given" do
expect {
controller.authorize_if(false)
}.to raise_error(AuthorizeIf::NotAuthorizedError)
expect {
controller.authorize_if(nil)
}.to raise_error(AuthorizeIf::NotAuthorizedError)
end
end
context "when object and block are given" do
it "allows exception customization through the block" do
expect {
controller.authorize_if(false) do |exception|
exception.message = "Custom Message"
exception.context[:request_ip] = "192.168.1.1"
end
}.to raise_error(AuthorizeIf::NotAuthorizedError, "Custom Message") do |exception|
expect(exception.message).to eq("Custom Message")
expect(exception.context[:request_ip]).to eq("192.168.1.1")
end
end
end
context "when no arguments are given" do
it "raises ArgumentError" do
expect {
controller.authorize_if
}.to raise_error(ArgumentError)
end
end
end
describe "#authorize" do
context "when corresponding authorization rule exists" do
context "when rule does not accept parameters" do
it "returns true if rule returns true" do
controller.define_singleton_method(:authorize_index?) { true }
expect(controller.authorize).to eq true
end
end
context "when rule accepts parameters" do
it "calls rule with given parameters" do
class << controller
def authorize_index?(param_1, param_2:)
param_1 || param_2
end
end
expect(controller.authorize(false, param_2: true)).to eq true
end
end
context "when block is given" do
it "passes block through to `authorize_if` method" do
controller.define_singleton_method(:authorize_index?) { false }
expect {
controller.authorize do |exception|
exception.message = "passed through"
end
}.to raise_error(AuthorizeIf::NotAuthorizedError, "passed through") do |exception|
expect(exception.message).to eq("passed through")
end
end
end
end
context "when corresponding authorization rule does not exist" do
it "raises MissingAuthorizationRuleError" do
expect {
controller.authorize
}.to raise_error(
AuthorizeIf::MissingAuthorizationRuleError,
"No authorization rule defined for action dummy#index. Please define method #authorize_index? for #{controller.class.name}"
)
end
end
end
end
| vrybas/authorize_if | spec/authorize_if_spec.rb | Ruby | mit | 3,092 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("34_FactorialSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("34_FactorialSum")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("880c59c2-814b-4c4c-91b0-a6f62aa7f1f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| steliyan/ProjectEuler | 34_FactorialSum/Properties/AssemblyInfo.cs | C# | mit | 1,406 |
namespace MyColors
{
partial class SimpleToolTip
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(305, 51);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// SimpleToolTip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(305, 51);
this.ControlBox = false;
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SimpleToolTip";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "SimpleToolTip";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label1;
}
} | cborrow/MyColors | SimpleToolTip.Designer.cs | C# | mit | 2,497 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Gama.Atenciones.Wpf.Views
{
/// <summary>
/// Interaction logic for SearchBoxView.xaml
/// </summary>
public partial class SearchBoxView : UserControl
{
public SearchBoxView()
{
InitializeComponent();
}
}
}
| PFC-acl-amg/GamaPFC | GamaPFC/Gama.Atenciones.Wpf/Views/SearchBoxView.xaml.cs | C# | mit | 663 |
<?php
namespace Terrific\Composition\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\SerializerBundle\Annotation\ReadOnly;
use JMS\SerializerBundle\Annotation\Type;
use JMS\SerializerBundle\Annotation\Exclude;
use JMS\SerializerBundle\Annotation\Groups;
use JMS\SerializerBundle\Annotation\Accessor;
/**
* Terrific\Composition\Entity\Module
*
* @ORM\Table(name="module")
* @ORM\Entity(repositoryClass="Terrific\Composition\Entity\ModuleRepository")
*/
class Module
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
* @ReadOnly
*/
private $id;
/**
* @ORM\Column(name="in_work", type="boolean")
* @Type("boolean")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $inWork = false;
/**
* @ORM\Column(name="shared", type="boolean")
* @Type("boolean")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $shared = false;
/**
* @ORM\Column(name="title", type="string", length=255)
* @Type("string")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $title;
/**
* @ORM\Column(name="description", type="text")
* @Type("string")
* @Groups({"project_list", "project_details", "module_list", "module_details"})
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity="Project")
* @Type("integer")
* @Groups({"module_details"})
*/
private $project;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $markup;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $style;
/**
* @ORM\OneToOne(targetEntity="Snippet")
* @Type("Terrific\Composition\Entity\Snippet")
* @Groups({"module_details"})
*/
private $script;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* @return text
*/
public function getDescription()
{
return $this->description;
}
/**
* Set markup
*
* @param Terrific\Composition\Entity\Snippet $markup
*/
public function setMarkup(\Terrific\Composition\Entity\Snippet $markup)
{
$this->markup = $markup;
}
/**
* Get markup
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getMarkup()
{
return $this->markup;
}
/**
* Set style
*
* @param Terrific\Composition\Entity\Snippet $style
*/
public function setStyle(\Terrific\Composition\Entity\Snippet $style)
{
$this->style = $style;
}
/**
* Get style
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getStyle()
{
return $this->style;
}
/**
* Set script
*
* @param Terrific\Composition\Entity\Snippet $script
*/
public function setScript(\Terrific\Composition\Entity\Snippet $script)
{
$this->script = $script;
}
/**
* Get script
*
* @return Terrific\Composition\Entity\Snippet
*/
public function getScript()
{
return $this->script;
}
/**
* Set project
*
* @param Terrific\Composition\Entity\Project $project
* @return Module
*/
public function setProject(\Terrific\Composition\Entity\Project $project = null)
{
$this->project = $project;
return $this;
}
/**
* Get project
*
* @return Terrific\Composition\Entity\Project
*/
public function getProject()
{
return $this->project;
}
/**
* Set inWork
*
* @param boolean $inWork
* @return Module
*/
public function setInWork($inWork)
{
$this->inWork = $inWork;
return $this;
}
/**
* Get inWork
*
* @return boolean
*/
public function getInWork()
{
return $this->inWork;
}
/**
* Set shared
*
* @param boolean $shared
* @return Module
*/
public function setShared($shared)
{
$this->shared = $shared;
return $this;
}
/**
* Get shared
*
* @return boolean
*/
public function getShared()
{
return $this->shared;
}
} | brunschgi/terrific-io-old | src/Terrific/Composition/Entity/Module.php | PHP | mit | 5,480 |
using System;
using System.Collections;
using System.Linq;
using Xunit;
namespace Popsql.Tests
{
public class SqlValuesTests
{
[Fact]
public void Add_WithNullValues_ThrowsArgumentNull()
{
var values = new SqlValues();
Assert.Throws<ArgumentNullException>(() => values.Add(null));
}
[Fact]
public void Count_ReturnsNumberOfItems()
{
var values = new SqlValues();
Assert.Equal(0, values.Count);
values.Add(Enumerable.Range(0, 5).Cast<SqlValue>());
Assert.Equal(1, values.Count);
values.Add(Enumerable.Range(5, 10).Cast<SqlValue>());
Assert.Equal(2, values.Count);
}
[Fact]
public void ExpressionType_ReturnsValues()
{
Assert.Equal(SqlExpressionType.Values, new SqlValues().ExpressionType);
}
[Fact]
public void GetEnumerator_ReturnsEnumerator()
{
var values = new SqlValues
{
Enumerable.Range(0, 5).Cast<SqlValue>(),
Enumerable.Range(5, 10).Cast<SqlValue>()
};
var enumerator = ((IEnumerable) values).GetEnumerator();
Assert.NotNull(enumerator);
int count = 0;
while (enumerator.MoveNext())
{
count++;
}
Assert.Equal(2, count);
}
}
} | WouterDemuynck/popsql | src/Popsql.Tests/SqlValuesTests.cs | C# | mit | 1,149 |
package se.dsv.waora.deviceinternetinformation;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* <code>ConnectionActivity</code> presents UI for showing if the device
* is connected to internet.
*
* @author Dushant Singh
*/
public class ConnectionActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiate view
TextView connectivityStatus = (TextView) findViewById(R.id.textViewDeviceConnectivity);
// Get connectivity service.
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Get active network information
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
// Check if active network is connected.
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
// Set status connected
connectivityStatus.setText(getString(R.string.online));
connectivityStatus.setTextColor(getResources().getColor(R.color.color_on));
// Check if connected with wifi
boolean isWifiOn = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if (isWifiOn) {
// Set wifi status on
TextView wifiTextView = (TextView) findViewById(R.id.textViewWifi);
wifiTextView.setText(getString(R.string.on));
wifiTextView.setTextColor(getResources().getColor(R.color.color_on));
} else {
// Set mobile data status on.
TextView mobileDataTextView = (TextView) findViewById(R.id.textViewMobileData);
mobileDataTextView.setText(getString(R.string.on));
mobileDataTextView.setTextColor(getResources().getColor(R.color.color_on));
}
}
}
}
| dushantSW/ip-mobile | 7.3.1/DeviceInternetInformation/app/src/main/java/se/dsv/waora/deviceinternetinformation/ConnectionActivity.java | Java | mit | 2,212 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 8