answer
stringlengths 15
1.25M
|
|---|
#include "QtAV/LibAVFilter.h"
#include <QtCore/QSharedPointer>
#include "QtAV/private/Filter_p.h"
#include "QtAV/Statistics.h"
#include "QtAV/AudioFrame.h"
#include "QtAV/VideoFrame.h"
#include "QtAV/private/AVCompat.h"
#include "utils/internal.h"
#include "utils/Logger.h"
/*
* libav10.x, ffmpeg2.x: av_buffersink_read deprecated
* libav9.x: only av_buffersink_read can be used
* ffmpeg<2.0: <API key> and av_buffersink_read
*/
// TODO: enabled = false if no libavfilter
// TODO: filter_complex
// NO COPY in push/pull
#define <API key> (LIBAV_MODULE_CHECK(LIBAVFILTER, 4, 2, 0) || FFMPEG_MODULE_CHECK(LIBAVFILTER, 3, 79, 100)) //3.79.101: ff2.0.4
namespace QtAV {
#if QTAV_HAVE(AVFILTER)
// local types can not be used as template parameters
class AVFrameHolder {
public:
AVFrameHolder() {
m_frame = av_frame_alloc();
#if !<API key>
picref = 0;
#endif
}
~AVFrameHolder() {
av_frame_free(&m_frame);
#if !<API key>
<API key>(&picref);
#endif
}
AVFrame* frame() { return m_frame;}
#if !<API key>
AVFilterBufferRef** bufferRef() { return &picref;}
// copy properties and data ptrs(no deep copy).
void copyBufferToFrame() { <API key>(m_frame, picref);}
#endif
private:
AVFrame *m_frame;
#if !<API key>
AVFilterBufferRef *picref;
#endif
};
typedef QSharedPointer<AVFrameHolder> AVFrameHolderRef;
#endif //QTAV_HAVE(AVFILTER)
class LibAVFilter::Private
{
public:
Private()
: avframe(0)
, status(LibAVFilter::NotConfigured)
{
#if QTAV_HAVE(AVFILTER)
filter_graph = 0;
in_filter_ctx = 0;
out_filter_ctx = 0;
<API key>();
#endif //QTAV_HAVE(AVFILTER)
}
~Private() {
#if QTAV_HAVE(AVFILTER)
avfilter_graph_free(&filter_graph);
#endif //QTAV_HAVE(AVFILTER)
if (avframe) {
av_frame_free(&avframe);
avframe = 0;
}
}
bool setOptions(const QString& opt) {
if (options == opt)
return false;
options = opt;
status = LibAVFilter::NotConfigured;
return true;
}
bool pushAudioFrame(Frame *frame, bool changed, const QString& args);
bool pushVideoFrame(Frame *frame, bool changed, const QString& args);
bool setup(const QString& args, bool video) {
if (avframe) {
av_frame_free(&avframe);
avframe = 0;
}
status = LibAVFilter::ConfigureFailed;
#if QTAV_HAVE(AVFILTER)
avfilter_graph_free(&filter_graph);
filter_graph = <API key>();
//QString sws_flags_str;
// pixel_aspect==sar, pixel_aspect is more compatible
QString buffersrc_args = args;
qDebug("buffersrc_args=%s", buffersrc_args.toUtf8().constData());
AVFilter *buffersrc = <API key>(video ? "buffer" : "abuffer");
Q_ASSERT(buffersrc);
AV_ENSURE_OK(<API key>(&in_filter_ctx,
buffersrc,
"in", buffersrc_args.toUtf8().constData(), NULL,
filter_graph)
, false);
/* buffer video sink: to terminate the filter chain. */
AVFilter *buffersink = <API key>(video ? "buffersink" : "abuffersink");
Q_ASSERT(buffersink);
AV_ENSURE_OK(<API key>(&out_filter_ctx, buffersink, "out",
NULL, NULL, filter_graph)
, false);
/* Endpoints for the filter graph. */
AVFilterInOut *outputs = <API key>();
AVFilterInOut *inputs = <API key>();
outputs->name = av_strdup("in");
outputs->filter_ctx = in_filter_ctx;
outputs->pad_idx = 0;
outputs->next = NULL;
inputs->name = av_strdup("out");
inputs->filter_ctx = out_filter_ctx;
inputs->pad_idx = 0;
inputs->next = NULL;
struct delete_helper {
AVFilterInOut **x;
delete_helper(AVFilterInOut **io) : x(io) {}
~delete_helper() {
// libav always free it in <API key>. so we does nothing
#if QTAV_USE_FFMPEG(LIBAVFILTER)
avfilter_inout_free(x);
#endif
}
} scoped_in(&inputs), scoped_out(&outputs);
//<API key>, <API key>?
AV_ENSURE_OK(<API key>(filter_graph, options.toUtf8().constData(), &inputs, &outputs, NULL), false);
AV_ENSURE_OK(<API key>(filter_graph, NULL), false);
avframe = av_frame_alloc();
status = LibAVFilter::ConfigureOk;
#if DBG_GRAPH
//not available in libav9
const char* g = avfilter_graph_dump(filter_graph, NULL);
if (g)
qDebug().nospace() << "filter graph:\n" << g; // use << to not print special chars in qt5.5
av_freep(&g);
#endif //DBG_GRAPH
return true;
#endif //QTAV_HAVE(AVFILTER)
return false;
}
#if QTAV_HAVE(AVFILTER)
AVFilterGraph *filter_graph;
AVFilterContext *in_filter_ctx;
AVFilterContext *out_filter_ctx;
#endif //QTAV_HAVE(AVFILTER)
AVFrame *avframe;
QString options;
LibAVFilter::Status status;
};
QStringList LibAVFilter::videoFilters()
{
static const QStringList list(LibAVFilter::registeredFilters(AVMEDIA_TYPE_VIDEO));
return list;
}
QStringList LibAVFilter::audioFilters()
{
static const QStringList list(LibAVFilter::registeredFilters(AVMEDIA_TYPE_AUDIO));
return list;
}
QString LibAVFilter::filterDescription(const QString &filterName)
{
QString s;
#if QTAV_HAVE(AVFILTER)
<API key>();
const AVFilter *f = <API key>(filterName.toUtf8().constData());
if (!f)
return s;
if (f->description)
s.append(QString::fromUtf8(f->description));
#if AV_MODULE_CHECK(LIBAVFILTER, 3, 7, 0, 8, 100)
return s.append(QLatin1String("\n")).append(QObject::tr("Options:"))
.append(Internal::optionsToString((void*)&f->priv_class));
#endif
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(filterName);
return s;
}
LibAVFilter::LibAVFilter()
: priv(new Private())
{
}
LibAVFilter::~LibAVFilter()
{
delete priv;
}
void LibAVFilter::setOptions(const QString &options)
{
if (!priv->setOptions(options))
return;
Q_EMIT optionsChanged();
}
QString LibAVFilter::options() const
{
return priv->options;
}
LibAVFilter::Status LibAVFilter::status() const
{
return priv->status;
}
bool LibAVFilter::pushVideoFrame(Frame *frame, bool changed)
{
return priv->pushVideoFrame(frame, changed, sourceArguments());
}
bool LibAVFilter::pushAudioFrame(Frame *frame, bool changed)
{
return priv->pushAudioFrame(frame, changed, sourceArguments());
}
void* LibAVFilter::pullFrameHolder()
{
#if QTAV_HAVE(AVFILTER)
AVFrameHolder *holder = NULL;
holder = new AVFrameHolder();
#if <API key>
int ret = <API key>(priv->out_filter_ctx, holder->frame());
#else
int ret = av_buffersink_read(priv->out_filter_ctx, holder->bufferRef());
#endif //<API key>
if (ret < 0) {
qWarning("<API key> error: %s", av_err2str(ret));
delete holder;
return 0;
}
#if !<API key>
holder->copyBufferToFrame();
#endif
return holder;
#endif //QTAV_HAVE(AVFILTER)
return 0;
}
QStringList LibAVFilter::registeredFilters(int type)
{
QStringList filters;
#if QTAV_HAVE(AVFILTER)
<API key>();
const AVFilter* f = NULL;
AVFilterPad* fp = NULL; // no const in <API key>() for ffmpeg<=1.2 libav<=9
#if AV_MODULE_CHECK(LIBAVFILTER, 3, 8, 0, 53, 100)
while ((f = avfilter_next(f))) {
#else
AVFilter** ff = NULL;
while ((ff = av_filter_next(ff)) && *ff) {
f = (*ff);
#endif
fp = (AVFilterPad*)f->inputs;
// only check the 1st pad
if (!fp || !<API key>(fp, 0) || <API key>(fp, 0) != (AVMediaType)type)
continue;
fp = (AVFilterPad*)f->outputs;
// only check the 1st pad
if (!fp || !<API key>(fp, 0) || <API key>(fp, 0) != (AVMediaType)type)
continue;
filters.append(QLatin1String(f->name));
}
#endif //QTAV_HAVE(AVFILTER)
return filters;
}
class <API key> : public VideoFilterPrivate
{
public:
<API key>()
: VideoFilterPrivate()
, pixfmt(QTAV_PIX_FMT_C(NONE))
, width(0)
, height(0)
{}
AVPixelFormat pixfmt;
int width, height;
};
LibAVFilterVideo::LibAVFilterVideo(QObject *parent)
: VideoFilter(*new <API key>(), parent)
, LibAVFilter()
{
}
QStringList LibAVFilterVideo::filters() const
{
return LibAVFilter::videoFilters();
}
void LibAVFilterVideo::process(Statistics *statistics, VideoFrame *frame)
{
Q_UNUSED(statistics);
#if QTAV_HAVE(AVFILTER)
if (status() == ConfigureFailed)
return;
DPTR_D(LibAVFilterVideo);
//Status old = status();
bool changed = false;
if (d.width != frame->width() || d.height != frame->height() || d.pixfmt != frame->pixelFormatFFmpeg()) {
changed = true;
d.width = frame->width();
d.height = frame->height();
d.pixfmt = (AVPixelFormat)frame->pixelFormatFFmpeg();
}
bool ok = pushVideoFrame(frame, changed);
//if (old != status())
// emit statusChanged();
if (!ok)
return;
AVFrameHolderRef ref((AVFrameHolder*)pullFrameHolder());
if (!ref)
return;
const AVFrame *f = ref->frame();
VideoFrame vf(f->width, f->height, VideoFormat(f->format));
vf.setBits((quint8**)f->data);
vf.setBytesPerLine((int*)f->linesize);
vf.setMetaData(QStringLiteral("avframe_hoder_ref"), QVariant::fromValue(ref));
vf.setTimestamp(ref->frame()->pts/1000000.0); //pkt_pts?
//vf.setMetaData(frame->availableMetaData());
*frame = vf;
#else
Q_UNUSED(frame);
#endif //QTAV_HAVE(AVFILTER)
}
QString LibAVFilterVideo::sourceArguments() const
{
DPTR_D(const LibAVFilterVideo);
#if QTAV_USE_LIBAV(LIBAVFILTER)
return QStringLiteral("%1:%2:%3:%4:%5:%6:%7")
#else
return QStringLiteral("video_size=%1x%2:pix_fmt=%3:time_base=%4/%5:pixel_aspect=%6/%7")
#endif
.arg(d.width).arg(d.height).arg(d.pixfmt)
.arg(1).arg(AV_TIME_BASE) //time base 1/1?
.arg(1).arg(1) //sar
;
}
class <API key> : public AudioFilterPrivate
{
public:
<API key>()
: AudioFilterPrivate()
, sample_rate(0)
, sample_fmt(AV_SAMPLE_FMT_NONE)
, channel_layout(0)
{}
int sample_rate;
AVSampleFormat sample_fmt;
qint64 channel_layout;
};
LibAVFilterAudio::LibAVFilterAudio(QObject *parent)
: AudioFilter(*new <API key>(), parent)
, LibAVFilter()
{}
QStringList LibAVFilterAudio::filters() const
{
return LibAVFilter::audioFilters();
}
QString LibAVFilterAudio::sourceArguments() const
{
DPTR_D(const LibAVFilterAudio);
return QStringLiteral("time_base=%1/%2:sample_rate=%3:sample_fmt=%4:channel_layout=0x%5")
.arg(1)
.arg(AV_TIME_BASE)
.arg(d.sample_rate)
//ffmpeg new: <API key>
//libav, ffmpeg old: AV_OPT_TYPE_STRING
.arg(QLatin1String(<API key>(d.sample_fmt)))
.arg(d.channel_layout, 0, 16) //AV_OPT_TYPE_STRING
;
}
void LibAVFilterAudio::process(Statistics *statistics, AudioFrame *frame)
{
Q_UNUSED(statistics);
#if QTAV_HAVE(AVFILTER)
if (status() == ConfigureFailed)
return;
DPTR_D(LibAVFilterAudio);
//Status old = status();
bool changed = false;
const AudioFormat afmt(frame->format());
if (d.sample_rate != afmt.sampleRate() || d.sample_fmt != afmt.sampleFormatFFmpeg() || d.channel_layout != afmt.channelLayoutFFmpeg()) {
changed = true;
d.sample_rate = afmt.sampleRate();
d.sample_fmt = (AVSampleFormat)afmt.sampleFormatFFmpeg();
d.channel_layout = afmt.channelLayoutFFmpeg();
}
bool ok = pushAudioFrame(frame, changed);
//if (old != status())
// emit statusChanged();
if (!ok)
return;
AVFrameHolderRef ref((AVFrameHolder*)pullFrameHolder());
if (!ref)
return;
const AVFrame *f = ref->frame();
AudioFormat fmt;
fmt.<API key>(f->format);
fmt.<API key>(f->channel_layout);
fmt.setSampleRate(f->sample_rate);
if (!fmt.isValid()) {// need more data to decode to get a frame
return;
}
AudioFrame af(fmt);
//af.setBits((quint8**)f->extended_data);
//af.setBytesPerLine((int*)f->linesize);
af.setBits(f->extended_data); // TODO: ref
af.setBytesPerLine(f->linesize[0], 0); // for correct alignment
af.<API key>(f->nb_samples);
af.setMetaData(QStringLiteral("avframe_hoder_ref"), QVariant::fromValue(ref));
af.setTimestamp(ref->frame()->pts/1000000.0); //pkt_pts?
//af.setMetaData(frame->availableMetaData());
*frame = af;
#else
Q_UNUSED(frame);
#endif //QTAV_HAVE(AVFILTER)
}
bool LibAVFilter::Private::pushVideoFrame(Frame *frame, bool changed, const QString &args)
{
#if QTAV_HAVE(AVFILTER)
VideoFrame *vf = static_cast<VideoFrame*>(frame);
if (status == LibAVFilter::NotConfigured || !avframe || changed) {
if (!setup(args, true)) {
qWarning("setup video filter graph error");
//enabled = false; // skip this filter and avoid crash
return false;
}
}
if (!vf->constBits(0)) {
*vf = vf->to(vf->format());
}
avframe->pts = frame->timestamp() * 1000000.0; // time_base is 1/1000000
avframe->width = vf->width();
avframe->height = vf->height();
avframe->format = (AVPixelFormat)vf->pixelFormatFFmpeg();
for (int i = 0; i < vf->planeCount(); ++i) {
avframe->data[i] = (uint8_t*)vf->constBits(i);
avframe->linesize[i] = vf->bytesPerLine(i);
}
//TODO: side data for vf_codecview etc
//int ret = <API key>(in_filter_ctx, avframe, <API key>);
/*
* <API key> equals to <API key> with <API key>.
* <API key> is more compatible, while <API key> only exists in ffmpeg >=2.0
* add a ref if frame is ref counted
* TODO: libav < 10.0 will copy the frame, prefer to use av_buffersrc_buffer
*/
AV_ENSURE_OK(<API key>(in_filter_ctx, avframe), false);
return true;
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(frame);
return false;
}
bool LibAVFilter::Private::pushAudioFrame(Frame *frame, bool changed, const QString &args)
{
#if QTAV_HAVE(AVFILTER)
if (status == LibAVFilter::NotConfigured || !avframe || changed) {
if (!setup(args, false)) {
qWarning("setup audio filter graph error");
//enabled = false; // skip this filter and avoid crash
return false;
}
}
AudioFrame *af = static_cast<AudioFrame*>(frame);
const AudioFormat afmt(af->format());
avframe->pts = frame->timestamp() * 1000000.0; // time_base is 1/1000000
avframe->sample_rate = afmt.sampleRate();
avframe->channel_layout = afmt.channelLayoutFFmpeg();
#if QTAV_USE_FFMPEG(LIBAVCODEC) || QTAV_USE_FFMPEG(LIBAVUTIL) //AVFrame was in avcodec
avframe->channels = afmt.channels(); //MUST set because <API key> will compare channels and layout
#endif
avframe->format = (AVSampleFormat)afmt.sampleFormatFFmpeg();
avframe->nb_samples = af->samplesPerChannel();
for (int i = 0; i < af->planeCount(); ++i) {
//avframe->data[i] = (uint8_t*)af->constBits(i);
avframe->extended_data[i] = (uint8_t*)af->constBits(i);
avframe->linesize[i] = af->bytesPerLine(i);
}
AV_ENSURE_OK(<API key>(in_filter_ctx, avframe), false);
return true;
#endif //QTAV_HAVE(AVFILTER)
Q_UNUSED(frame);
return false;
}
} //namespace QtAV
#if QTAV_HAVE(AVFILTER)
Q_DECLARE_METATYPE(QtAV::AVFrameHolderRef)
#endif
|
import os
import pydot
# import pprint
FONT = "Lucida Sans"
def graphviz_setup(gviz_path):
os.environ['PATH'] = gviz_path + ";" + os.environ['PATH']
def add_child(graph, child_id, child_label, parent_id, colour):
node = pydot.Node(child_id, style="filled", fillcolor=colour, label=child_label, shape="polygon", fontname=FONT)
graph.add_node(node)
graph.add_edge(pydot.Edge(parent_id, node))
def add_children(graph, parent_id, d, level=0):
blue = "#6b6bd1"
white = "#fdfefd"
green = "#33a333"
colours = [blue, white, green] * 3
for class_, children in d.items():
colour = colours[level]
child_label = class_
child_id = parent_id + "_" + class_
add_child(graph, child_id, child_label, parent_id, colour)
add_children(graph, child_id, children, level+1)
def save_file(graph, fn):
filename = "%s.png" % fn
graph.write_png(filename)
graph.write("%s.dot" % fn)
os.startfile(filename)
def main(gviz_path, layer_only=False):
graphviz_setup(gviz_path)
graph = pydot.Dot(graph_type='digraph', rankdir="TB")
layer_children = {
'CLASS': {
'LABEL': {'STYLE': {}},
'CONNECTIONOPTIONS': {},
'LEADER': {'STYLE': {}},
'STYLE': {},
'VALIDATION': {}
},
'CLUSTER': {},
'COMPOSITE': {},
'FEATURE': {'POINTS': {}},
'GRID': {},
'JOIN': {},
'METADATA': {},
'PROJECTION': {},
'SCALETOKEN': {'VALUES': {}},
'VALIDATION': {}
}
# pprint.pprint(layer_children)
classes = {
"MAP": {
"LAYER": layer_children,
'LEGEND': {'LABEL': {}},
'PROJECTION': {},
'QUERYMAP': {},
'REFERENCE': {},
'SCALEBAR': {'LABEL': {}},
'SYMBOL': {},
'WEB': {'METADATA': {}, 'VALIDATION': {}}
}
}
if layer_only:
root = "LAYER"
classes = classes["MAP"]
fn = "layer_classes"
else:
fn = "map_classes"
root, = classes.keys()
node = pydot.Node(root, style="filled", fillcolor="#33a333", label=root, fontname=FONT, shape="polygon")
graph.add_node(node)
add_children(graph, root, classes[root])
save_file(graph, fn)
if __name__ == "__main__":
gviz_path = r"C:\Program Files (x86)\Graphviz2.38\bin"
main(gviz_path, True)
main(gviz_path, False)
print("Done!")
|
import { get_definition } from './../base';
export const push_link = (
oid, linkurl, linkname, onmenu='true', instance_name,
when, additional_args, description
) => get_definition({
oid,
linkurl,
linkname,
onmenu,
instance_name
},
{
label: 'VersionOne - Push Link',
method: 'push_link',
module: 'main',
name: 'v1plugin'
},
when, additional_args, description
);
|
#endregion
namespace RedBadger.Xpf.Graphics
{
<summary>
Represents a Texture.
</summary>
public interface ITexture
{
<summary>
Gets the height of this texture in pixels.
</summary>
int Height { get; }
<summary>
Gets the width of this texture in pixels.
</summary>
int Width { get; }
}
}
|
<?php
namespace fufudao\base;
use yii\behaviors\TimestampBehavior;
//use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord as ar;
use yii\db\Expression;
class ActiveRecord extends ar
{
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created','modified'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['modified']
],
'value' => new Expression(date('\'Y-m-d H:i:s\'')),
],
];
}
public function newID(){
$schema = $this->getTableSchema();
$primaryKey = $schema->primaryKey[0];
$col = $schema->columns[$primaryKey];
$ret = $this->getAttribute($primaryKey);
if( empty($ret) ){
if( $col->phpType === \yii\db\Schema::TYPE_STRING ){
switch ($col->size){
case 13:
$ret = uniqid();
break;
case 32:
$ret = md5(uniqid(mt_rand(), true));
break;
}
}
}
return $ret;
}
}
|
# Cookbook Name:: dokku
# Spec:: plugins
require "spec_helper"
describe "dokku::plugins" do
context "when all attributes are default" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "does nothing" do
expect { chef_run }.to_not raise_error
end
end
context "when plugins exist in attributes and no actions are listed" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [{
name: "redis",
url: "https://github.com/dokku/dokku-redis.git"
}]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "installs plugins" do
expect(chef_run).to <API key>(
"redis").with(url: "https://github.com/dokku/dokku-redis.git")
end
end
context "when plugins exist in attributes" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [
{ name: "redis", url: "https://github.com/dokku/dokku-redis.git",
action: "install" },
{ name: "mongo", url: "https://github.com/dokku/dokku-mongo.git",
action: "uninstall" },
]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "manages plugins" do
expect(chef_run).to <API key>(
"redis").with(url: "https://github.com/dokku/dokku-redis.git")
expect(chef_run).to <API key>(
"mongo").with(url: "https://github.com/dokku/dokku-mongo.git")
end
end
context "when plugins to be installed provide a commit to fetch" do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new do |node|
node.override["dokku"]["plugins"] = [
{ name: "redis", url: "https://github.com/dokku/dokku-redis.git",
action: "install", committish: "0.4.4" },
]
end
runner.converge(described_recipe)
end
before do
stub_command("which nginx").and_return("/usr/bin/nginx")
end
it "installs the plugins specifying that committish" do
expect(chef_run).to <API key>("redis").with(
url: "https://github.com/dokku/dokku-redis.git", committish: "0.4.4",
)
end
end
end
|
'use strict';
// Load the application's configuration
const config = require('../server/config');
const url = config.express_host + '/api';
// Required modules
const async = require('async');
const colors = require('colors');
const request = require('request');
// Counter for the Measurements
let counter = 1;
// Read the arguments from the command line or set them to the default values
const interval = process.argv[2] || 2000;
const thingName = process.argv[3] || 'Demo';
const thingLocLat = process.argv[4] || 51.964113;
const thingLocLng = process.argv[5] || 7.624862;
// REST API authentication token
let token;
console.log('\n
console.log(' STARTING DEMONSTRATION...'.cyan);
console.log('\n
async.waterfall([
// Create a new User
function(callback) {
console.log(' Creating a new', 'User...\n'.cyan);
const userJson = {
email: 'demo#' + Math.random().toFixed() + '@example.com',
password: 'demoPass'
};
// Post the new User
request.post({
headers: {'content-type': 'application/json'},
url: url + '/users',
json: userJson
}, function(error, response, body) {
if (!error) {
console.log(' New User', 'created.'.green);
token = body.token;
} else {
console.log(' New User creation', 'failed'.red);
}
console.log('\n
callback(error, body._id);
});
},
// Create a new Thing
function(userId, callback) {
console.log(' Creating a new', 'Thing...\n'.cyan);
const thingJson = {
name: thingName,
loc: {
coordinates: [ thingLocLat, thingLocLng ]
},
userId: userId,
waterbodyId: '<API key>',
token: token
};
// Post the new Thing
request.post({
headers: {'content-type': 'application/json'},
url: url + '/things',
json: thingJson
}, function(error, response, body) {
if (!error) {
console.log(' New Thing', 'created.'.green);
} else {
console.log(' New Thing creation', 'failed'.red);
}
console.log('\n
callback(error, body._id);
});
},
// Create a new Feature
function(thingId, callback) {
console.log(' Creating a new', 'Feature...\n'.cyan);
const featureJson = {
name: 'demoFeature',
unit: 'foo',
token: token
};
// Post the new Feature
request.post({
headers: {'content-type': 'application/json'},
url: url + '/features',
json: featureJson
}, function(error, response, body) {
if (!error) {
console.log(' New Feature', 'created'.green);
} else {
console.log(' New Feature creation', 'failed'.red);
}
console.log('\n
callback(error, thingId, body._id);
});
},
// Create a new Sensor
function(thingId, featureId, callback) {
console.log(' Creating a new', 'Sensor...\n'.cyan);
const sensorJson = {
name: 'demoSensor',
interval: interval,
refLevel: 2,
warnLevel: 6,
riskLevel: 8,
thingId: thingId,
featureId: featureId,
token: token
};
// Post the new Sensor
request.post({
headers: {'content-type': 'application/json'},
url: url + '/sensors',
json: sensorJson
}, function(error, response, body) {
if (!error) {
console.log(' New Sensor', 'created.'.green);
} else {
console.log(' New Sensor creation', 'failed'.red);
}
console.log('\n
callback(error, body._id);
});
},
// Create new Measurements in an interval
function(sensorId, callback) {
console.log(' Finished demo setup. Measuring now...'.cyan);
console.log('\n
let value = 4;
setInterval(function() {
console.log(' Creating a new', 'Measurement...\n'.cyan);
// Calculate the Measurement's value as a random number with respect to its previous value
if (value < 1 || Math.random() > 0.5) {
value += Math.random();
} else {
value -= Math.random();
}
value = parseFloat(value.toFixed(2));
let measurementJson = {
date: Date.now(),
value: value,
sensorId: sensorId,
token: token
};
// Post the new Measurement
request.post({
headers: {'content-type': 'application/json'},
url: url + '/measurements',
json: measurementJson
}, function(error, response, body) {
if (!error) {
console.log(' New Measurement', ('#' + counter).cyan, 'created.'.green, '\nValue:', body.value.cyan);
counter++;
} else {
console.log(' New Measurement creation', 'failed'.red);
callback(error);
}
console.log('\n
});
}, interval);
}
], function(err, result) {
if (err) {
console.log(err);
}
});
|
import React from 'react'
import {HOC, Link} from 'cerebral-view-react'
import PageProgress from '../PageProgress'
// View
class AutoReload extends React.Component {
constructor (props) {
super(props)
this.state = {
secondsElapsed: 0
}
this.onInterval = this.onInterval.bind(this)
}
componentWillMount () {
this.intervals = []
}
<API key> () {
this.intervals.forEach(clearInterval)
}
componentDidMount () {
this.setInterval(this.onInterval, 1000)
}
setInterval () {
this.intervals.push(setInterval.apply(null, arguments))
}
onInterval () {
let secondsElapsed = 0
if (this.props.isEnabled) {
secondsElapsed = this.state.secondsElapsed + 1
if (secondsElapsed >= this.props.triggerAfterSeconds) {
this.trigger()
secondsElapsed = 0
}
}
if (secondsElapsed !== this.state.secondsElapsed) {
this.setState({
secondsElapsed: secondsElapsed
})
}
}
trigger () {
this.props.triggers.map((trigger) => trigger())
}
triggerNow (e) {
if (e) {
e.preventDefault()
}
if (this.props.isEnabled) {
if (this.state.secondsElapsed > 0) {
this.trigger()
this.setState({
secondsElapsed: 0
})
}
}
}
render () {
const signals = this.props.signals
const progress = {
isEnabled: this.props.isEnabled,
elapsed: this.state.secondsElapsed,
total: this.props.triggerAfterSeconds
}
return (
<div>
<PageProgress {...progress} />
<hr />
<pre>
<API key><br />
======================<br />
[{'='.repeat(this.state.secondsElapsed)}{'.'.repeat(this.props.triggerAfterSeconds - this.state.secondsElapsed - 1)}]<br />
isEnabled: {this.props.isEnabled ? 'yepp' : 'nope'}<br />
triggerAfterSeconds: {this.props.triggerAfterSeconds}<br />
numberOfTriggers: {this.props.triggers.length}<br />
secondsElapsed: {this.state.secondsElapsed}<br />
secondsBeforeReload: {this.props.triggerAfterSeconds - this.state.secondsElapsed}<br />
<Link signal={signals.app.reload.reloadingDisabled}>clickmeto_<b>disable</b>_reloading</Link><br />
<Link signal={signals.app.reload.reloadingEnabled}>clickmeto_<b>enable</b>_reloading</Link><br />
<Link signal={signals.app.reload.reloadingToggled}>clickmeto_<b>toggle</b>_reloading</Link><br />
<a onClick={(e) => this.triggerNow(e)}>clickmeto_<b>trigger_NOW</b></a><br />
<Link signal={signals.app.reload.<API key>} params={{interval: 10}}>clickmeto_reload_@<b>10_seconds</b></Link><br />
<Link signal={signals.app.reload.<API key>} params={{interval: 20}}>clickmeto_reload_@<b>20_seconds</b></Link><br />
<Link signal={signals.app.reload.<API key>} params={{interval: 30}}>clickmeto_reload_@<b>30_seconds</b></Link><br />
<Link signal={signals.app.reload.<API key>} params={{interval: 60}}>clickmeto_reload_@<b>60_seconds</b></Link><br />
=<br />
<i>designed by pbit</i>
</pre>
</div>
)
}
}
// Model
AutoReload.propTypes = {
isEnabled: React.PropTypes.bool,
triggerAfterSeconds: React.PropTypes.number,
signals: React.PropTypes.object,
triggers: React.PropTypes.array
}
AutoReload.defaultProps = {
triggers: []
}
// Binding
const StatefullAutoReload = HOC(AutoReload, {
isEnabled: ['app', 'reload', 'isEnabled'],
triggerAfterSeconds: ['app', 'reload', 'triggerAfterSeconds']
})
// API
export default StatefullAutoReload
|
#!/bin/bash
#SBATCH --partition=mono
#SBATCH --ntasks=1
#SBATCH --time=4-0:00
#SBATCH --mem-per-cpu=8000
#SBATCH -J <API key>
#SBATCH -e <API key>.err.txt
#SBATCH -o <API key>.out.txt
source /etc/profile.modules
module load gcc
module load matlab
cd ~/deepLearn && srun ./deepFunction 4 'RBM' 'DBM' '128 1000 1500 10' '0 1 1 1' '4_inc_bin' 'PARAL_base' "'iteration.n_epochs', 'learning.lrate', 'learning.cd_k', 'learning.persistent_cd', 'parallel_tempering.use'" '200 1e-3 1 0 1' "'iteration.n_epochs', 'learning.persistent_cd'" '200 1'
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Task Management System</title>
<!-- Bootstrap Core CSS -->
<link href="<?=base_url()?>assets/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="<?=base_url()?>assets/css/metisMenu.min.css" rel="stylesheet">
<!-- DataTables CSS -->
<link href="<?=base_url()?>assets/css/dataTables.bootstrap.css" rel="stylesheet">
<link href="<?=base_url()?>assets/css/bootstrap-editable.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?=base_url()?>assets/css/main.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="<?=base_url()?>assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Custom tab icons -->
<link rel="shortcut icon" href="<?=base_url()?>assets/images/favicon.ico" type="image/x-icon">
<link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="<?=base_url()?>assets/js/jquery-ui-1.11.4.custom/<API key>.css" rel="stylesheet" type="text/css" />
<input type="hidden" id="base-url" value="<?=base_url()?>"/>
<input type="hidden" id="current-page" value=""/>
<input type="hidden" id="<API key>" value=""/>
<input type="hidden" id="current-page-child" value=""/>
<input type="hidden" id="current-parentID" value=""/>
<input type="hidden" id="<API key>" value=""/>
<input type="hidden" id="<API key>" value=""/>
<style>
.inline-block{display:inline-block;}
</style>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top text-center" role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<a class="navbar-brand" href="<?=base_url();?>">
<div class="inline"> Welcome to Streamfream Task Management System </div>
</a>
</div>
</nav>
<!-- /.navbar-header -->
<!-- /.navbar-top-links -->
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Test Users Roles Demote</title>
</head>
<body>
<?php
require_once('test-util.php');
require_once(dirname(__FILE__) . '/../lib/ca-main.php');
echo '<div class="apitest">';
echo '<h1>users_roles_demote</h1>';
$ca = new CityApi();
$ca->debug = true;
$ca->json = true;
$userid = 238801;
$roleid = 986632;
$args = array('title' => 'Participant');
$results = $ca->users_roles_demote($userid, $roleid, $args);
echo '<h2>Formatted JSON results: </h2>';
echo '<pre>';
echo format_json($results);
echo '</pre>';
echo '</div>';
?>
</body>
</html>
|
# coffeehaus
A coffeescript shop for JVM locals.
## /!\ Extraction in progress
This library is the extraction of the coffeescript compiler used
in [coffeescripted-sbt](https://github.com/softprops/coffeescripted-sbt) for use as a standalone library
## install
(todo)
## usage
This library provides scala interfaces for compiling [vanilla][vanilla] and [iced][iced] CoffeeScript.
It uses the versions `1.6.3` and `1.6.3-b` respectively.
To compile vanilla coffeescript
scala
coffeehaus.Compile.vanilla()("alert 'vanilla'")
or simply
scala
coffeehaus.Compile("alert 'vanilla'")
To compile iced coffeescript
scala
coffeehaus.Compile.iced()("alert 'iced'")
These will return a `Either[coffeehaus.CompilerError, String]` with the compiled source.
Don't have time to wait while your coffee's being brewed? Try moving to the side of the counter.
scala
import coffeehaus.Compile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
Future(Compile("alert 'vanilla'")).map { coffee =>
Thread.sleep(1000)
coffee.fold(println, println)
}
println("checkin' my tweets")
Be Your Own Barista
This library will always make a best attempt at providing interfaces to the latest coffeescript compilers.
That doesn't mean you can't experiment with your own brews ( other versions of coffeescript ) by extending `coffeehaus.Compile` providing
a resource path to the source of the script. As an example the built-in vanilla coffeescript compiler is defined as follows
scala
Vanilla extends Compile("vanilla/coffee-script.js")
enjoy.
Doug Tangren (softprops) 2013
[vanilla]: http://coffeescript.org/
[iced]: http://maxtaco.github.io/coffee-script/
|
from common import *
if len(sys.argv) < 2:
log('ERROR output directory is required')
time.sleep(3)
exit()
# setup the output directory, create it if needed
output_dir = sys.argv[1]
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# log in and load personal library
api = open_api()
library = <API key>()
def playlist_handler(playlist_name, <API key>, playlist_tracks):
# skip empty and no-name playlists
if not playlist_name: return
if len(playlist_tracks) == 0: return
# setup output files
playlist_name = playlist_name.replace('/', '')
open_log(os.path.join(output_dir,playlist_name+u'.log'))
outfile = codecs.open(os.path.join(output_dir,playlist_name+u'.csv'),
encoding='utf-8',mode='w')
# keep track of stats
stats = create_stats()
export_skipped = 0
# keep track of songids incase we need to skip duplicates
song_ids = []
log('')
log('============================================================')
log(u'Exporting '+ unicode(len(playlist_tracks)) +u' tracks from '
+playlist_name)
log('============================================================')
# add the playlist description as a "comment"
if <API key>:
outfile.write(tsep)
outfile.write(<API key>)
outfile.write(os.linesep)
for tnum, pl_track in enumerate(playlist_tracks):
track = pl_track.get('track')
# we need to look up these track in the library
if not track:
library_track = [
item for item in library if item.get('id')
in pl_track.get('trackId')]
if len(library_track) == 0:
log(u'!! '+str(tnum+1)+repr(pl_track))
export_skipped += 1
continue
track = library_track[0]
result_details = <API key>(track)
if not allow_duplicates and result_details['songid'] in song_ids:
log('{D} '+str(tnum+1)+'. '+<API key>(result_details,True))
export_skipped += 1
continue
# update the stats
update_stats(track,stats)
# export the track
song_ids.append(result_details['songid'])
outfile.write(<API key>(result_details))
outfile.write(os.linesep)
# calculate the stats
stats_results = <API key>(stats,len(playlist_tracks))
# output the stats to the log
log('')
log_stats(stats_results)
log(u'export skipped: '+unicode(export_skipped))
# close the files
close_log()
outfile.close()
# the personal library is used so we can lookup tracks that fail to return
# info from the ...playlist_contents() call
playlist_contents = api.<API key>()
for playlist in playlist_contents:
playlist_name = playlist.get('name')
<API key> = playlist.get('description')
playlist_tracks = playlist.get('tracks')
playlist_handler(playlist_name, <API key>, playlist_tracks)
if export_thumbs_up:
# get thumbs up playlist
thumbs_up_tracks = []
for track in library:
if track.get('rating') is not None and int(track.get('rating')) > 1:
thumbs_up_tracks.append(track)
# modify format of each dictionary to match the data type
# of the other playlists
<API key> = []
for t in thumbs_up_tracks:
<API key>.append({'track': t})
playlist_handler('Thumbs up', 'Thumbs up tracks', <API key>)
if export_all:
<API key> = []
for t in library:
<API key>.append({'track': t})
playlist_handler('All', 'All tracks', <API key>)
close_api()
|
require "./test/test_helper"
require "pinker/rule"
include Pinker
regarding "remember helps gather up things that get returned if the rule is valid." do
class Request
def initialize(path_info, query_string=nil)
@path_info = path_info
@query_string = query_string
end
end
test "stick things in memory, return them with a successful result" do
rule =
RuleBuilder.new(Request) {
declare("Path must have at least three sections"){@path_info.split("/").length>=3}
remember { |memory|
memory[:resource_type] = @path_info.split("/")[2]
}
}.build
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:resource_type => "widgets"}
}
end
test "disregard the results of remembers" do
rule =
RuleBuilder.new(Request) {
remember { |memory, context|
memory[:x] = "y"
nil #caused explosions at one time
}
}.build
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:x => "y"}
}
end
test "cache useful things across calls using context" do
the_rule =
RuleBuilder.new(Request) {
declare("Path must have at least three sections") { |call, context|
(context[:path_parts]=@path_info.split("/")).length>=3
}
with_rule(:text_is_widgets){|rule, context|rule.apply_to(context[:path_parts][2])}
rule(:text_is_widgets) {
declare("Must be widgets"){self=="widgets"}
}
remember { |memory, context|
memory[:resource_type] = context[:path_parts][2]
}
}.build
assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).satisfied? }
assert{ the_rule.apply_to(Request.new("/v1/widgets/foo")).memory ==
{:resource_type => "widgets"}
}
end
test "if a remember fails and nothing else has, bubble up the error" do
rule =
RuleBuilder.new(Request) {
declare { |call, context|
(context[:path_parts]=@path_info.split("/")).length>=3 || call.fail("Path must have at least three sections")
}
remember { |memory, context|
raise StandardError.new("blam!")
}
}.build
assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.message ==
"blam!"
}
end
test "if something else has already failed, swallow the exception. this is a 'best effort'/completeness failure strategy." do
rule =
RuleBuilder.new(Request) {
declare { |call, context|
@path_info.split("/").length>=99 || call.fail("Path must have at least 99 sections")
}
remember { |memory, context|
raise StandardError.new("blam!")
}
}.build
assert{ rescuing{ rule.apply_to(Request.new("/v1/widgets/foo")) }.nil? }
assert{ rule.apply_to(Request.new("/v1/widgets/foo")).problems.first.message == "Path must have at least 99 sections" }
end
test "merge together memory hashes from rules" do
grammar =
RuleBuilder.new(:foo) {
rule(:a) {
remember{|memory|memory[:a] = 1}
with_rule(:b){|rule|rule.apply_to("y")}
}
rule(:b) {
remember{|memory|memory[:b] = 2}
}
}.build
assert{ grammar.apply_to("x").memory == {:a => 1, :b => 2} }
end
end
|
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Double-clicking selects the whole number as one word if it's all alphanumeric.
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
#include "key.h"
#include "script.h"
static const char* pszBase58 = "<API key>";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte
unsigned char nVersion;
// the actually encoded data
std::vector<unsigned char> vchData;
CBase58Data()
{
nVersion = 0;
vchData.clear();
}
~CBase58Data()
{
// zero the memory, as it may contain sensitive data
if (!vchData.empty())
memset(&vchData[0], 0, vchData.size());
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
{
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(nVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.empty())
{
vchData.clear();
nVersion = 0;
return false;
}
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
memset(&vchTemp[0], 0, vchTemp.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch(1, nVersion);
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (nVersion < b58.nVersion) return -1;
if (nVersion > b58.nVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Bitcoin addresses.
* <API key> have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* <API key> have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress;
class <API key> : public boost::static_visitor<bool>
{
private:
CBitcoinAddress *addr;
public:
<API key>(CBitcoinAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CBitcoinAddress : public CBase58Data
{
public:
enum
{
PUBKEY_ADDRESS = 25, // Basecoin: address begin with 'B'
SCRIPT_ADDRESS = 8,
PUBKEY_ADDRESS_TEST = 111,
SCRIPT_ADDRESS_TEST = 196,
};
bool Set(const CKeyID &id) {
SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(<API key>(this), dest);
}
bool IsValid() const
{
unsigned int nExpectedSize = 20;
bool fExpectTestNet = false;
switch(nVersion)
{
case PUBKEY_ADDRESS:
nExpectedSize = 20; // Hash of public key
fExpectTestNet = false;
break;
case SCRIPT_ADDRESS:
nExpectedSize = 20; // Hash of CScript
fExpectTestNet = false;
break;
case PUBKEY_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
case SCRIPT_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
}
CBitcoinAddress()
{
}
CBitcoinAddress(const CTxDestination &dest)
{
Set(dest);
}
CBitcoinAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CBitcoinAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid())
return false;
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
default: return false;
}
}
bool IsScript() const {
if (!IsValid())
return false;
switch (nVersion) {
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
return true;
}
default: return false;
}
}
};
bool inline <API key>::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline <API key>::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline <API key>::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CBitcoinSecret : public CBase58Data
{
public:
void SetSecret(const CSecret& vchSecret, bool fCompressed)
{
assert(vchSecret.size() == 32);
SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
if (fCompressed)
vchData.push_back(1);
}
CSecret GetSecret(bool &fCompressedOut)
{
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &vchData[0], 32);
fCompressedOut = vchData.size() == 33;
return vchSecret;
}
bool IsValid() const
{
bool fExpectTestNet = false;
switch(nVersion)
{
case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
break;
case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
{
SetSecret(vchSecret, fCompressed);
}
CBitcoinSecret()
{
}
};
#endif
|
/* Client-side router settings */
Router.configure({
layoutTemplate:"layout",
notFoundTemplate:"page_not_found",
loadingTemplate:"loading"
});
Router.route("/", {
name:"home",
template:"home"
});
Router.route("/profile", {
name:"profile",
template:"profile"
});
Router.route("/admin", {
name:"admin",
template:"admin"
});
Router.route("/user/:_id", {
name:"user",
template:"user",
data: function(){
return Meteor.users.findOne({_id: this.params._id});
}
});
|
#define _GNU_SOURCE
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <gtk/gtk.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <plugin.h>
#include <amixer-plugin.h>
void vol_increase (KTPreferences *preferences);
void vol_decrease (KTPreferences *preferences);
void vol_increase_10 (KTPreferences *preferences);
void vol_decrease_10 (KTPreferences *preferences);
void mute (KTPreferences *preferences);
static void create_window (VOLUMEBAR_INFO *volumebar_info);
static int get_current_volume (void);
static void update_volume_bar (GtkWidget *volume_bar);
static gboolean update_window (VOLUMEBAR_INFO *volumebar_info);
static void clean_exit (int sig);
static void start_window (void);
static char *<API key> (void);
static void change_volume (char *command);
static Boolean is_muted = FALSE;
KeytouchPlugin plugin_struct = {
{"Amixer", "Marvin Raaijmakers", "GPL 2", "2.3",
"This plugin allows you to change the volume. It also shows\n"
"the current volume when it changes. To use this plugin amixer\n"
"needs to be installed."},
"amixer.so",
5,
{{"Volume increase", <API key>, {.function = vol_increase}},
{"Volume decrease", <API key>, {.function = vol_decrease}},
{"Volume increase 10%", <API key>, {.function = vol_increase_10}},
{"Volume decrease 10%", <API key>, {.function = vol_decrease_10}},
{"Mute", <API key>, {.function = mute}},
}
};
void
create_window (VOLUMEBAR_INFO *volumebar_info)
/*
Input:
-
Output:
volumebar_info - The window element points to the created window and the
volume_bar element points to the volume progressbar in the
window
Returns:
-
Description:
This function creates a window with a progressbar with the following
properties:
- It is positioned in the center ot the screen.
- It has no window decorations and can not be resized by the user.
- It will allways be above other windows.
- It is visible on all desktops.
- It will not be visible in the taskbar an pager.
- It does not accept focus.
*/
{
volumebar_info->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
<API key> (GTK_WINDOW (volumebar_info->window), GTK_WIN_POS_CENTER);
<API key> (GTK_WINDOW (volumebar_info->window), FALSE);
<API key> (GTK_WINDOW (volumebar_info->window), FALSE);
/* The window will allways be above others */
<API key> (GTK_WINDOW (volumebar_info->window), TRUE);
/* Let the window be visible on all desktops: */
gtk_window_stick (GTK_WINDOW (volumebar_info->window));
/* This window will not be visible in the taskbar: */
<API key> (GTK_WINDOW (volumebar_info->window), TRUE);
/* This window will not be visible in the pager: */
<API key> (GTK_WINDOW (volumebar_info->window), TRUE);
<API key> (GTK_WINDOW (volumebar_info->window), FALSE);
volumebar_info->volume_bar = <API key>();
gtk_widget_show (volumebar_info->volume_bar);
gtk_container_add (GTK_CONTAINER (volumebar_info->window), volumebar_info->volume_bar);
<API key> (volumebar_info->volume_bar, 231, 24);
<API key> (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.52);
<API key> (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.02);
<API key> (GTK_PROGRESS_BAR (volumebar_info->volume_bar), "Volume");
}
int
get_current_volume (void)
/*
Returns:
The current volume retrieved from amixer. -1 will be returned when
retrieving the volume failed.
*/
{
FILE *amixer;
char c;
int volume = -1;
amixer = popen ("amixer sget Master | grep \"Front Left:\"", "r");
if (amixer)
{
do {
c = getc(amixer);
/* We have found the volume when the following appears:
* '[' followed by an integer followed by '%'
*/
if (c == '[' && fscanf(amixer, "%d", &volume) && (c = getc(amixer)) == '%')
{
break;
}
volume = -1;
} while (c != '\n' && c != EOF);
pclose (amixer);
}
return (volume);
}
void
update_volume_bar (GtkWidget *volume_bar)
/*
Output:
volume_bar - Will show the percentage of the current volume
*/
{
int volume;
gchar *text;
volume = get_current_volume();
if (volume && volume != -1)
{
text = g_strdup_printf("Volume %d%%", volume);
if (text)
{
<API key> (GTK_PROGRESS_BAR(volume_bar), text);
g_free (text);
}
}
else
{
volume = 0;
<API key> (GTK_PROGRESS_BAR(volume_bar), "Muted");
}
<API key> (GTK_PROGRESS(volume_bar), (gdouble)volume/100.0);
/* Directly draw the progressbar: */
while (<API key>(NULL, FALSE))
; /* NULL Statement */
}
gboolean
update_window (VOLUMEBAR_INFO *volumebar_info)
/*
Input:
volumebar_info->close_time - The time to close the window
Output:
volumebar_info - Will be updated
Returns:
TRUE if this function should be called again after UPDATE_INTERVAL
miliseconds, otherwise FALSE.
Description:
This function destroys volumebar_info->window and escapes from the GTK main
routine if the current time is later than volumebar_info->close_time. If not
then the volume bar will be updated with the current volume.
*/
{
MSGBUF msg;
Boolean close_window;
/* Check if there is a new message on the queue */
if (msgrcv(volumebar_info->msgqid, &msg, sizeof(msg.time), 1, IPC_NOWAIT) != -1)
{
volumebar_info->close_time = msg.time + SHOW_WINDOW_TIME;
}
close_window = (time(NULL) > volumebar_info->close_time);
if (!close_window)
{
update_volume_bar (volumebar_info->volume_bar);
}
else
{
gtk_widget_destroy (volumebar_info->window);
gtk_main_quit();
}
return !close_window;
}
void
start_window (void)
/*
Description:
This function creates a window with a volume bar and shows it
SHOW_WINDOW_TIME seconds when it receives a message on the message queue.
The key of the message queue is generated by running
ftok(<API key>(), MSGQ_AMIXER_PROJ_ID). The messages that are
sent to this queue should contain the time they are sent. The volume window
will be showed from the time this function receives the message, until the
time the message was sent plus SHOW_WINDOW_TIME seconds.
*/
{
MSGBUF msg;
VOLUMEBAR_INFO volumebar_info;
key_t msgq_key;
char *keytouch_user_dir;
gtk_init (0, NULL);
keytouch_user_dir = <API key>();
/* Get the key for the message queue */
msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
free (keytouch_user_dir);
if (msgq_key == -1)
{
perror ("keytouch amixer plugin");
return;
}
/* Get the message queue identifier and create the queue if necessary */
volumebar_info.msgqid = msgget(msgq_key, 0);
if (volumebar_info.msgqid == -1)
{
perror ("keytouch amixer plugin");
return;
}
while (1)
{
if (msgrcv(volumebar_info.msgqid, &msg, sizeof(msg.time), 1, 0) != -1)
{
volumebar_info.close_time = msg.time + SHOW_WINDOW_TIME;
if (time(NULL) <= volumebar_info.close_time)
{
create_window (&volumebar_info);
update_volume_bar (volumebar_info.volume_bar);
gtk_widget_show (volumebar_info.window);
g_timeout_add (UPDATE_INTERVAL, (GSourceFunc) update_window, &volumebar_info);
gtk_main();
}
}
}
}
char
*<API key> (void)
/*
Returns:
The address of some new allocated space which is a string containing the
value of the environment variable HOME followed by "/.keytouch2".
*/
{
char *keytouch_dir, *home;
home = getenv("HOME");
if (home == NULL)
{
fputs ("keytouch amixer plugin: could not get environment variable $HOME", stderr);
exit (EXIT_FAILURE);
}
if (asprintf(&keytouch_dir, "%s/.keytouch2", home) == -1)
{
fputs ("keytouch amixer plugin: asprintf() failed. "
"This is probably caused because it failed to allocate memory.", stderr);
exit (EXIT_FAILURE);
}
return (keytouch_dir);
}
void
clean_exit (int sig)
{
exit (EXIT_SUCCESS);
}
void
<API key> (void)
/*
Description:
This function sends a signal to the child program that manages the
volumebar. The child will receive the signal and will show the volumebar.
The child process will be created if it does not exist yet.
*/
{
static int qid = -1;
MSGBUF msg;
/* If this is the first time this function was called */
if (qid == -1)
{
key_t msgq_key;
char *keytouch_user_dir;
keytouch_user_dir = <API key>();
/* Get the key for the message queue */
msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
free (keytouch_user_dir);
if (msgq_key == -1)
{
perror ("keytouch amixer plugin");
return;
}
/* Get the message queue identifier and create the queue if necessary */
qid = msgget(msgq_key, MSGQ_PERMISSIONS | IPC_CREAT);
if (qid == -1)
{
perror ("keytouch amixer plugin");
return;
}
if (fork() == 0)
{
/* Trap key signals */
signal (SIGINT, clean_exit);
signal (SIGQUIT, clean_exit);
signal (SIGTERM, clean_exit);
/* We will now start the run_window() function in our
* child process for showing a volume bar to the user
*/
start_window();
exit (EXIT_SUCCESS); /* We will never get here because of
* the infinite loop in run_window()
*/
}
}
msg.mtype = 1;
msg.time = time(NULL);
if (msgsnd(qid, &msg, sizeof(msg.time), 0) == -1)
{
perror ("keytouch amixer plugin");
}
}
void
change_volume (char *command)
/*
Input:
command - The command that changes the volume.
Description:
This function executes 'command' in a child process and then calls
<API key>().
*/
{
if (fork() == 0)
{
execlp ("sh", "sh", "-c", command, NULL);
exit (EXIT_SUCCESS);
}
else
{
<API key>();
}
}
void
vol_increase (KTPreferences *preferences)
{
is_muted = FALSE;
change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_INCR) );
}
void
vol_decrease (KTPreferences *preferences)
{
is_muted &= !get_current_volume();
change_volume ( CHANGE_VOL_CMD(VOL_DEFAULT_DECR) );
}
void
vol_increase_10 (KTPreferences *preferences)
{
is_muted = FALSE;
change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_INCR) );
}
void
vol_decrease_10 (KTPreferences *preferences)
{
is_muted &= !get_current_volume();
change_volume ( CHANGE_VOL_CMD(VOL_10PERCENT_DECR) );
}
void
mute (KTPreferences *preferences)
{
static int prev_volume = -1;
int current_volume;
char *command = NULL;
current_volume = get_current_volume();
is_muted &= !current_volume;
if (is_muted)
{
/* Tell amixer to set the volume to prev_volume */
if (asprintf(&command, "amixer sset Master %d%% > /dev/null", prev_volume) == -1)
{
fputs ("keytouch amixer plugin: asprintf() failed. "
"This is probably caused because it failed to allocate memory.", stderr);
}
}
else if (current_volume)
{
/* Tell amixer to set the volume to 0 */
command = strdup("amixer sset Master 0% > /dev/null");
if (command == NULL)
{
perror ("keytouch amixer plugin");
}
prev_volume = current_volume;
}
/* Do we have to mute/unmute? */
if (command)
{
if (fork() == 0)
{
execlp ("sh", "sh", "-c", command, NULL);
exit (EXIT_SUCCESS);
}
else
{
<API key>();
}
free (command);
is_muted = !is_muted;
}
}
|
<?php
namespace S327at\L51blog\Models;
use Illuminate\Database\Eloquent\Model;
class Group extends Model {
}
|
package com.calebmeyer.bettercrafting.creativetab;
import com.calebmeyer.bettercrafting.constants.Project;
import com.calebmeyer.bettercrafting.initialization.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabBCT {
public static final CreativeTabs <API key> = new CreativeTabs(Project.MOD_ID) {
/**
* This method returns an item, whose icon is used for this creative tab
*
* @return an item to use for the creative tab's icon
*/
@Override
public Item getTabIconItem() {
return ModItems.craftingPanel;
}
/**
* Gets the label for this creative tab.
*
* @return the label
*/
@Override
public String <API key>() {
return Project.MOD_NAME;
}
};
}
|
//Change class of "Home" and "About"
function setActive() {
document.getElementById("about").className += "active"
document.getElementById("home").setAttribute('class','no')
}
|
<?php
class PostModel extends CI_Model
{
public $id;
public $title;
public $content;
public $date;
public $author;
public $upvotes = 0;
public $downvotes = 0;
public $voters;
public function __construct()
{
parent::__construct();
}
public function GetAll()
{
$this->db->order_by('date', 'desc');
$query = $this->db->get('posts');
return $query->result();
}
public function GetByID($id)
{
$query = $this->db->get_where('posts', array('id' => $id));
return $query->row();
}
private function Insert($post)
{
session_start();
$this->author = $_SESSION["username"];
return $this->db->insert('posts', $this);
}
private function Update($post)
{
$this->db->set('title', $this->title);
$this->db->set('content', $this->content);
$this->db->where('id', $this->id);
return $this->db->update('posts');
}
public function Delete()
{
$this->db->where('id', $this->id);
return $this->db->delete('posts');
}
public function Save()
{
if (isset($this->id))
{
return $this->Update();
}
else
{
return $this->Insert();
}
}
public function Vote()
{
$this->db->set('upvotes', $this->upvotes);
$this->db->set('downvotes', $this->downvotes);
$this->db->set('voters', $this->voters);
$this->db->where('id', $this->id);
return $this->db->update('posts');
}
}
?>
|
title: 'PB & Homemade J'
author: lbjay
layout: post
permalink: /2007/10/05/pb-homemade-j/
categories:
- "What's for Lunch"
<abbr class="unapi-id" title=""><!-- --></abbr>
<div style="float: right; margin-left: 10px; margin-bottom: 10px;">
<a href="http://www.flickr.com/photos/37849137@N00/1490397893/" title="photo sharing"><img src="http://farm2.static.flickr.com/1243/<API key>.jpg" alt="" style="border: solid 2px
</div>
This one’s been stuck in the Flickr queue for a couple of weeks. Also it wasn’t truly Peanut Butter, but Sunflower Butter. It just seems so awkward to call it a SFB & J.
The jelly is grape and was made by my neighbor Leah from <a href='http://en.wikipedia.org/wiki/Concord_grape' target='_blank'>Concord grapes</a> growing on a trellis right out her back door.
The pile ‘o’ orange in the foreground is some delicious carrot slaw made with honey, walnuts and dried cranberries.
<br clear="all" />
|
layout: default
<h2>{{ page.title }}</h2>
<div class="post">
{{ content }}
</div>
|
body {
color: #ffffff;
font-family: Monospace, sans-serif;
font-size: 13px;
text-align: center;
font-weight: bold;
background-color: #000000;
margin: 0;
overflow: hidden;
cursor: none;
-<API key>: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none;
}
ul {
list-style: none;
}
.found {
text-decoration: line-through;
color: #00ff00;
}
.player-information {
font-size: 1.2em;
font-weight: bold;
position: absolute;
left: 0;
top: 0;
padding: 1em;
z-index: 2147483647;
}
.items {
font-size: 1.2em;
font-weight: bold;
position: absolute;
right: 0;
top: 0;
padding-right: 1em;
z-index: 2147483647;
height: 90%;
overflow: hidden;
}
.refreshButton {
position: absolute;
left: 0;
top: 5.5em;
margin-left: 10px;
padding: 1.25em;
color: white;
font-size: larger;
text-decoration: none;
border-radius: 1em;
background-repeat: no-repeat;
background-image: url('./../ui/refresh.svg');
background-size: contain;
background-color: teal;
z-index: 2147483647;
}
#settings {
display: none;
width: 25%;
min-width: 300px;
margin: 1% auto;
}
#settings label {
display: block;
}
#settings label.inline {
display: inline-block;
}
#settings input {
padding: 5px 10px;
margin-bottom: 10px;
}
#settings input.small {
width: 25px;
}
#settings button {
display: block;
margin: 15px auto;
padding: 5px 10px;
}
|
<html><body>
<h4>Windows 10 x64 (18362.329)</h4><br>
<h2><API key></h2>
<font face="arial"> +0x000 PreparedCell : Uint4B<br>
+0x004 OldValueCell : Uint4B<br>
+0x008 NameLength : Uint2B<br>
+0x00c DataSize : Uint4B<br>
</font></body></html>
|
<reference types="xrm" />
export declare function findIndex(handlers: Xrm.Events.<API key>[], handler: Xrm.Events.<API key>): number;
|
<?php
namespace Vilks\DataObject;
use Vilks\DataObject\Exception\<API key>;
use Vilks\DataObject\Exception\<API key>;
use Vilks\DataObject\Exception\<API key>;
use Vilks\DataObject\Exception\<API key>;
use Vilks\DataObject\Validator\<API key>;
/**
* Base DataObject
*
* @package Vilks\DataObject
*/
abstract class DataObject
{
private static $validators = [];
/**
* Create instance of DataObject
*
* @return static
*/
public static function create()
{
return new static;
}
/**
* Create instance of DataObject with values based on related DataObject
*
* @param DataObject $source Data source object
*
* @return static
* @throws Exception\<API key> If DataObjects has different chain of inheritance
*/
public static function mutate(DataObject $source)
{
$replica = static::create();
if ($replica instanceof $source) {
$properties = get_object_vars($source);
} elseif ($source instanceof $replica) {
$properties = get_object_vars($replica);
} else {
throw new <API key>(
$replica,
$source,
sprintf('Class "%s" must be parent or child for "%s"', get_class($source), get_class($replica))
);
}
foreach ($properties as $name => $value) {
$replica->$name = $value;
}
return $replica;
}
/**
* Magic set property of DataObject
*
* IMPORTANT: For better performance in production you need
* to overwrite method for each property in final DataObjects
*
* @param string $name
* @param array $arguments
*
* @return static
*/
public function __call($name, array $arguments)
{
$this->_isPropertyExists($name);
if (!count($arguments)) {
return $this->$name;
} else {
$value = $arguments[0];
$this->_validateDataType($name, $value);
$replica = static::_isMutable() ? $this : clone $this;
$replica->$name = $value;
return $replica;
}
}
/**
* Magic get property of DataObject
*
* IMPORTANT: For better performance in production you need
* to make properties public in final DataObjects
*
* @param string $name
*
* @return mixed
*/
public function __get($name)
{
$this->_isPropertyExists($name);
return $this->$name;
}
/**
* Disallow direct setting of properties
*
* @param string $name
* @param string $value
*
* @throws Exception\<API key>
* @deprecated
*/
public function __set($name, $value)
{
throw new <API key>($name, $value, $this);
}
/**
* Turning off constructor outside object
* Use Class::create()
*/
protected function __construct()
{}
/**
* List of datatypes for properties
*
* @return string[]
*/
protected static function _getDataTypes()
{
return [];
}
/**
* Setting for DataObject which set behavior on property changing.
* If it's false changing of property will generate new DataObject with same values,
* if it's true changing of property will just change property in object
*
* @return bool
*/
protected static function _isMutable()
{
return false;
}
/**
* Exclude validators from serialization
*
* @return string[]
*/
public function __sleep()
{
$properties = array_keys(get_object_vars($this));
unset($properties['validators']);
return $properties;
}
private static function <API key>($class, $property)
{
$key = sprintf('%s.%s', $class, $property);
if (!array_key_exists($key, self::$validators)) {
$types = static::_getDataTypes();
self::$validators[$key] = array_key_exists($property, $types) ?
<API key>::getValidator($class)-><API key>($types[$property]) :
null;
}
return self::$validators[$key];
}
private function _validateDataType($property, $value)
{
if (!is_null($value)) {
$validator = self::<API key>(get_class($this), $property);
if ($validator && !$validator($value)) {
throw new <API key>(
$property,
$value,
static::_getDataTypes()[$property],
$this
);
}
}
}
private function _isPropertyExists($name, $strict = true)
{
$result = property_exists($this, $name);
if ($strict && !$result) {
throw new <API key>($this, $name);
}
return $result;
}
}
|
import _plotly_utils.basevalidators
class <API key>(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="showexponent",
parent_name="scatterpolar.marker.colorbar",
**kwargs
):
super(<API key>, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
values=kwargs.pop("values", ["all", "first", "last", "none"]),
**kwargs
)
|
<?php
namespace Midnight\Crawler\Plugin\TestData;
class MuryoTestData extends AbstractTestData
{
/**
* @var string
**/
protected $rss_name = 'muryo.xml';
/**
* @var array
**/
protected $html_paths = array(
'muryo/71340.html',
'muryo/71370.html',
'muryo/71376.html',
'muryo/error.html',
'muryo/error2.html'
);
}
|
using System;
using Argus.Extensions;
namespace Argus.Data
{
<summary>
Contains a string name/value pair seperated by an equals sign. The values can be set via the properties or by passing in a
delimited string. E.g. FirstName=Blake.
</summary>
<remarks></remarks>
public class Parameter
{
|
__author__ = 'miko'
from Tkinter import Frame
class GameState(Frame):
def __init__(self, *args, **kwargs):
self.stateName = kwargs["stateName"]
self.root = args[0]
self.id = kwargs["id"]
Frame.__init__(self, self.root.mainWindow)
self.config(
background="gold"
)
self.place(relwidth=1, relheight=1)
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Fri Feb 22 14:06:12 EET 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2013-02-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="javalabra.chess.core.impl.state (Chess 0.0.1-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
Package javalabra.chess.core.impl.state
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/AbstractGameState.html" title="class in javalabra.chess.core.impl.state">AbstractGameState</A></B></TD>
<TD>Abstract game state.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectMoveState.html" title="class in javalabra.chess.core.impl.state">SelectMoveState</A></B></TD>
<TD>State object representing state when piece on the board is selected and
game is waiting for a move to be choosen.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../../javalabra/chess/core/impl/state/SelectPieceState.html" title="class in javalabra.chess.core.impl.state">SelectPieceState</A></B></TD>
<TD>State object representing state when game is waiting for piece of concrete
color to be selected.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../javalabra/chess/core/impl/move/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../../../javalabra/chess/domain/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?javalabra/chess/core/impl/state/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright &
</BODY>
</HTML>
|
from csacompendium.csa_practice.models import PracticeLevel
from csacompendium.utils.pagination import <API key>
from csacompendium.utils.permissions import IsOwnerOrReadOnly
from csacompendium.utils.viewsutils import <API key>, CreateAPIViewHook
from rest_framework.filters import DjangoFilterBackend
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from .filters import <API key>
from csacompendium.csa_practice.api.practicelevel.<API key> import <API key>
def <API key>():
"""
Practice level views
:return: All practice level views
:rtype: Object
"""
<API key> = <API key>()
class <API key>(CreateAPIViewHook):
"""
Creates a single record.
"""
queryset = PracticeLevel.objects.all()
serializer_class = <API key>['<API key>']
permission_classes = [IsAuthenticated]
class <API key>(ListAPIView):
"""
API list view. Gets all records API.
"""
queryset = PracticeLevel.objects.all()
serializer_class = <API key>['<API key>']
filter_backends = (DjangoFilterBackend,)
filter_class = <API key>
pagination_class = <API key>
class <API key>(<API key>):
"""
Updates a record.
"""
queryset = PracticeLevel.objects.all()
serializer_class = <API key>['<API key>']
permission_classes = [IsAuthenticated, IsAdminUser]
lookup_field = 'slug'
return {
'<API key>': <API key>,
'<API key>': <API key>,
'<API key>': <API key>
}
|
export const ADD_COCKTAIL = 'ADD_COCKTAIL';
export const LOAD_COCKTAILS = 'LOAD_COCKTAILS';
export const ADD_SPIRIT = 'ADD_SPIRIT';
export const REMOVE_SPIRIT = 'REMOVE_SPIRIT';
export const UPDATE_HUE = 'UPDATE_HUE';
|
#include <algorithm>
#include <iostream>
#include "RustyFist/DrawMe.h"
#include "RustyFist/TouchSink.h"
#include "OpenGLLayer.h"
using namespace cocos2d;
using namespace std;
OpenGLLayer::OpenGLLayer()
{
}
OpenGLLayer::~OpenGLLayer()
{
}
bool OpenGLLayer::init()
{
return Layer::init();
}
cocos2d::Scene* OpenGLLayer::scene(DrawMe* drawMe, TouchSink* ts)
{
auto scene = Scene::create();
OpenGLLayer *layer = OpenGLLayer::create();
layer->setDrawMe(drawMe);
layer->setTouchSink(ts);
scene->addChild(layer);
return scene;
}
void OpenGLLayer::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags)
{
if (_drawMe)
_drawMe->draw();
}
void OpenGLLayer::setTouchSink(TouchSink* ts)
{
_ts = ts;
auto mouseEvents = EventListenerMouse::create();
mouseEvents->onMouseDown = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
mouseEvents->onMouseUp = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
mouseEvents->onMouseMove = [this](Event* e)
{
if(auto me = dynamic_cast<EventMouse*>(e))
{
if(_ts)
_ts->mouse({me->getCursorX(), me->getCursorY()});
}
};
_eventDispatcher-><API key>(mouseEvents, this);
}
void OpenGLLayer::onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::onTouchesCancelled(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* unused_event)
{
sendTouch(touches);
}
void OpenGLLayer::sendTouch(const std::vector<cocos2d::Touch*>& touches)
{
std::vector<::Touch> tochs;
std::transform(touches.begin(), touches.end(), back_inserter(tochs), [](cocos2d::Touch* t)
{
return ::Touch{t->getID(), t->getLocation().x, t->getLocation().y};
});
if(_ts)
_ts->touch(tochs);
}
|
// <API key>.h
// ximber
@import Foundation;
/**
* The connection transformation is a basic data structure that holds a block that is
* executed on each node found at the xpath
*/
@interface <API key> : NSObject
@property (nonatomic, copy, readonly) NSString *xPath;
@property (nonatomic, copy, readonly) NSString *(^keyTransformer)(NSString *key);
+ (instancetype)<API key>:(NSString *)xPath keyTransformer:(NSString *(^)(NSString *key))keyTransformer;
@end
|
/* icon */
.ico-file{width: 32px;height: 32px;display: inline-block;vertical-align: middle;background: url(../img/spr-icon.png) -384px 0 no-repeat;}
.ico-bt-file{background-position: 0 0}
.ico-bt-link{background-position: -32px 0}
.ico-chm{background-position: -64px 0}
.ico-xls{background-position: -96px 0}
.ico-link{background-position: -128px 0}
.ico-pdf{background-position: -160px 0}
.ico-doc{background-position: -192px 0}
.ico-ppt{background-position: -224px 0}
.ico-txt{background-position: -256px 0}
.ico-word{background-position: -288px 0}
.ico-install{background-position: -320px 0}
.ico-music{background-position: -352px 0}
.ico-unknow{background-position: -384px 0}
.ico-pic{background-position: -416px 0}
.ico-apk{background-position: -448px 0}
.ico-exe{background-position: -480px 0}
.ico-ipa{background-position: -512px 0}
.ico-ipsw{background-position: -544px 0}
.ico-iso{background-position: -576px 0}
.ico-group{background-position: -608px 0}
.ico-video{background-position: -832px 0}
.ico-avi{background-position: -640px 0}
.ico-flv{background-position: -672px 0}
.ico-mkv{background-position: -704px 0}
.ico-mov{background-position: -736px 0}
.ico-mp4{background-position: -768px 0}
.ico-mpg{background-position: -800px 0}
.ico-rm{background-position: -864px 0}
.ico-rmvb{background-position: -896px 0}
.ico-wmv{background-position: -928px 0}
.ico-rar{background-position: -960px 0}
/* vip */
.icvip{display:inline-block;width:42px;height:12px;background:url(../img/ic_vip.png) no-repeat 0 999em;overflow:hidden;vertical-align:-1px;margin: 0 0 0 2px;}
.icvip00{width: 36px;background-position: 0 0} .icvip01{background-position: -37px 0} .icvip02{background-position: -80px 0} .icvip03{background-position: -123px 0} .icvip04{background-position: -166px 0} .icvip05{background-position: -209px 0} .icvip06{background-position: -252px 0} .icvip00hui{background-position: 0 -18px}
.icvip00hui{width: 35px;background-position: 0px -18px}.icvip01hui{background-position: -37px -18px} .icvip02hui{background-position: -80px -18px} .icvip03hui{background-position: -123px -18px} .icvip04hui{background-position: -166px -18px} .icvip05hui{background-position: -209px -18px} .icvip06hui{background-position: -252px -18px}
/* gold vip */
.icgold00{width: 35px;background-position: 0 -36px} .icgold01{background-position: -37px -36px} .icgold02{background-position: -80px -36px} .icgold03{background-position: -123px -36px} .icgold04{background-position: -166px -36px} .icgold05{background-position: -209px -36px} .icgold06{background-position: -252px -36px} .icgold07{background-position: -295px -36px} .icgold00hui{background-position: 0 -54px}
.icgold00hui{width: 35px;background-position: 0px -54px} .icgold01hui{background-position: -37px -54px} .icgold02hui{background-position: -80px -54px} .icgold03hui{background-position: -123px -54px} .icgold04hui{background-position: -166px -54px} .icgold05hui{background-position: -209px -54px} .icgold06hui{background-position: -252px -54px} .icgold07hui{background-position: -295px -54px}
/* super vip */
.icsuper00{width: 35px;background-position: 0 -72px} .icsuper01{background-position: -37px -72px} .icsuper02{background-position: -80px -72px} .icsuper03{background-position: -123px -72px} .icsuper04{background-position: -166px -72px} .icsuper05{background-position: -209px -72px} .icsuper06{background-position: -252px -72px} .icsuper07{background-position: -295px -72px} .icsuper00hui{background-position: 0 -90px}
.icsuper00hui{width: 35px;background-position: 0px -90px} .icsuper01hui{background-position: -37px -90px} .icsuper02hui{background-position: -80px -90px} .icsuper03hui{background-position: -123px -90px} .icsuper04hui{background-position: -166px -90px} .icsuper05hui{background-position: -209px -90px}
/* another */
.icnian{width:12px;height:12px; background-position: 0px -108px;} .icnianhui{width:12px;height:12px; background-position: 0px -128px} .icdongjie{width:16px;height:16px; background-position: -19px -109px}
.icdongjiehui{width:16px;height:16px; background-position: -19px -128px} .icshuai{width:16px;height:16px; background-position: -38px -108px} .icshuaihui{width:16px;height:16px; background-position: -38px -128px}
.icqiye{width:16px;height:16px; background-position: -57px -109px} .icqiyehui{width:16px;height:16px; background-position: -57px -128px}
.ichongren{width:16px;height:16px; background-position: -76px -109px} .ichongrenhui{width:16px;height:16px; background-position: -76px -128px}
.icbao{width:16px;height:16px; background-position: -95px -109px} .icbaohui{width:16px;height:16px; background-position: -95px -128px}
.icxun{width:15px;height:16px; background-position: -116px -109px} .icxunhui{width:15px;height:16px; background-position: -116px -128px}
.icgold{width:15px;height:16px; background-position: -136px -109px} .icgoldhui{width:15px;height:14px; background-position: -136px -128px}
.icgrow{width:12px;height:14px; background-position: -155px -109px;} .icdown{width:12px;height:14px; background-position: -155px -128px;}
.ickuainiao{background-position: -338px 0;width: 36px;}
.ickuainiaohui{background-position: -338px -18px}
.icshangxing{background-position: -380px 0;width: 36px}
.icshangxinghui{background-position: -380px -18px;}
|
#include "tcp_socket.h"
using namespace easynet;
//TCPSocket
TCPSocket::TCPSocket(EPOLLSvrPtr s) {
socket_handler_ = nullptr;
svr_ = s;
msg_ = nullptr;
step_ = READ_HEAD;
}
void TCPSocket::SetHandler(On_Socket_Handler h){
socket_handler_ = h;
}
void TCPSocket::OnNetMessage(){
if( nullptr == socket_handler_){
LOG(FATAL) << "tcpsocket handler is nullptr!";
return;
}
//char *buff = svr_.get()->buff_; //,
for(;;){
char *buff = svr_.get()->buff_;
int32_t ret = NetPackage::Read(peer_.fd_, buff, MAX_SOCK_BUFF);
//LOG(INFO) << "read ok ret[" << ret << "]";
if(0 == ret ){
LOG(INFO) << "connection closed by peer fd[" << peer_.fd_ << "]";
this->KickOut();
return;
}
if( ret < 0 ){
if( EAGAIN == errno || EWOULDBLOCK == errno ){
//read, buff
//buff = svr_.get()->buff_;
//continue;
return;
}else{
LOG(INFO) << "read fail! fd[" << peer_.fd_ << "] errno[" << errno << "] msg[" << strerror(errno) << "]";
this->KickOut();
return;
}
}
int32_t more_data = ret;
while( more_data > 0){
if( nullptr == peer_.buff_ ){
peer_.buff_ = std::make_shared<DataBuffer>(peer_.fd_, HEADER_SZ);
}
auto data_buffer = peer_.buff_.get();
int32_t need_data = data_buffer->NeedData();
if( READ_HEAD == step_ ){
if( more_data < need_data ) {
data_buffer->AddData(more_data, buff);
return;
}
data_buffer->AddData(need_data, buff);
//body,
buff += need_data;
more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data);
msg_ = (MSG* )data_buffer->GetBuffPtr();
if(VERSION != msg_->header.version_ || IDENTIFY != msg_->header.identify_){
LOG(ERROR) << "version or identify is not fit! kick out client fd[" << peer_.fd_ << "] version["
<< (int)msg_->header.version_ << "] current version[" << (int)VERSION<<"]" << "identify["
<< (int)msg_->header.identify_ << "] current identify[" << (int)IDENTIFY << "]";
this->KickOut();
LOG(INFO) << "receive msg count[" << m.GetRecvPack() << "]";
return;
}
msg_->header.length_ = ntohs(msg_->header.length_);
msg_->header.type_ = ntohs(msg_->header.type_);
//body
data_buffer->Resize(msg_->header.length_ + HEADER_SZ);
//, msg_
msg_ = (MSG* )data_buffer->GetBuffPtr();
need_data = data_buffer->NeedData();
step_ = READ_BODY;
}
//step READ_BODY
if( more_data > 0 ) {
//body
if(more_data < need_data) {
data_buffer->AddData(more_data, buff);
return;
}
data_buffer->AddData(need_data, buff);
more_data = (more_data - need_data) < 0 ? 0:(more_data - need_data);
//buff
buff += need_data;
m.AddRecvPack();
char *pMsg = (char* )(data_buffer->GetBuffPtr());
pMsg += sizeof(HEADER);
auto f = socket_handler_;
try{
f(this->getID(), pMsg,msg_->header.length_, msg_->header.type_);
}catch(...){
LOG(ERROR) << "tcpsocket handler run fail!";
}
//packet
auto tmp = std::move(peer_.buff_);
tmp = nullptr;
peer_.buff_ = nullptr;//, , move peer_buff_ nullptr
step_ = READ_HEAD;
}
}
}
}
void TCPSocket::KickOut() {
IPlayer::KickOut();
//TODO EPOLLSvr map events_map_ player_map_
}
|
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-md-12">
<form action="/login" method="post">
{{ form.csrf_token }}
{{ form.next(value=next) }}
<div class="form-group">
{{ form.username.label }}
{{ form.username(class='form-control') }}
</div>
<div class="form-group">
{{ form.password.label }}
{{ form.password(class='form-control') }}
</div>
<div class="form-group">
<input type="submit" class="form-control" value="Login">
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
{% with messages = <API key>() %}
{% for message in messages %}
<div class="alert alert-info">{{ message }}</div>
{% endfor %}
{% endwith %}
</div>
</div>
{% endblock %}
|
using Android.OS;
using Android.Text;
using Android.Util;
using REKT.Graphics;
using REKT.Graphics.Unsafe;
using REKT.DI;
using SkiaSharp;
using System;
using System.Text;
using D = System.Diagnostics.Debug;
using NativeActivity = Android.App.Activity;
using NativeBitmap = Android.Graphics.Bitmap;
using NativeBitmapFactory = Android.Graphics.BitmapFactory;
using NativeContext = Android.Content.Context;
using NativeRect = Android.Graphics.Rect;
using NativeDialog = Android.Support.V7.App.AlertDialog;
using <API key> = Android.App.ProgressDialog;
using NativeColour = Android.Graphics.Color;
using NativeArrayAdapter = Android.Widget.ArrayAdapter;
using NativeView = Android.Views.View;
using System.Collections;
using NativeThread = System.Threading.Thread;
namespace REKT
{
public static class AndroidExtensions
{
// STRINGS
public static ISpanned ToSpannedHTML(this string rawHtml)
{
ISpanned html;
if (AndroidPlatform.Version >= BuildVersionCodes.N)
html = Html.FromHtml(rawHtml, FromHtmlOptions.ModeLegacy);
else
{
#pragma warning disable CS0618 //deprecation
html = Html.FromHtml(rawHtml);
#pragma warning restore CS0618
}
return html;
}
// CONTEXTS
public static SKColor ThemeColour(this NativeContext context, int themeColourID)
{
if (context == null)
throw new <API key>("context");
using (var typedValue = new TypedValue())
{
var theme = context.Theme;
theme.ResolveAttribute(themeColourID, typedValue, true);
var data = typedValue.Data;
return new SKColor(
(byte)NativeColour.GetRedComponent(data),
(byte)NativeColour.GetGreenComponent(data),
(byte)NativeColour.GetBlueComponent(data),
(byte)NativeColour.GetAlphaComponent(data));
}
}
public static NativeBitmap BitmapResource(this NativeContext context, int bitmapResourceID)
{
using (var opts = new NativeBitmapFactory.Options())
{
opts.<API key> = true;
return NativeBitmapFactory.DecodeResource(context.Resources, bitmapResourceID, opts);
}
}
public static SKBitmap BitmapResourceSkia(this NativeContext context, int bitmapResourceID)
{
using (var nativeBmp = context.BitmapResource(bitmapResourceID))
return nativeBmp.ToSkia();
}
private static void <API key>(this NativeContext context, Action action)
{
if (context is NativeActivity activity)
activity.RunOnUiThread(action);
else
action();
}
public static void ShowYesNoDialog(this NativeContext context, string title, string text,
Action yesAction = null, Action noAction = null)
{
if (context == null)
throw new <API key>("context");
context.<API key>(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton("Yes", (s, e) => { yesAction?.Invoke(); });
builder.SetNegativeButton("No", (s, e) => { noAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowOKDialog(this NativeContext context, string title, string text, Action okAction = null)
{
if (context == null)
throw new <API key>("context");
context.<API key>(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowWaitDialog(this NativeContext context, string title, string text, Action asyncTask)
{
if (context == null)
throw new <API key>("context");
if (asyncTask == null)
throw new <API key>("asyncTask");
context.<API key>(() =>
{
var dialog = <API key>.Show(context, (title ?? "").Trim(), (text ?? "").Trim(), true, false);
new NativeThread(() =>
{
asyncTask?.Invoke();
dialog.Dismiss();
dialog.Dispose();
}).Start();
});
}
public static void ShowListDialog(this NativeContext context, string title, IList data, Action<int> selectionAction,
Action cancelAction = null)
{
if (context == null)
throw new <API key>("context");
if (selectionAction == null)
throw new <API key>("selectionAction");
if (data == null)
throw new <API key>("data");
context.<API key>(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
var adapter = new NativeArrayAdapter(context, Android.Resource.Layout.SimpleListItem1, data);
builder.SetTitle((title ?? "").Trim())
.SetAdapter(adapter, (s, e) => { selectionAction.Invoke(e.Which); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowCustomDialog(this Activity activity, string title, int viewResID,
Action<NativeView> initAction = null,
Action<NativeView> okAction = null,
Action<NativeView> cancelAction = null)
{
if (activity == null)
throw new <API key>("context");
activity.<API key>(() =>
{
using (var builder = new NativeDialog.Builder(activity))
{
builder.SetTitle((title ?? "").Trim());
var view = activity.LayoutInflater.Inflate(viewResID, null);
initAction?.Invoke(view);
builder.SetView(view);
builder.SetPositiveButton(Android.Resource.String.Ok,
(s, e) => { okAction?.Invoke(view); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel,
(s, e) => { cancelAction.Invoke(view); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void Toast(this NativeContext context, string text)
{
Android.Widget.Toast.MakeText(context, text, Android.Widget.ToastLength.Long).Show();
}
public static void LaunchWebsite(this NativeContext context, string uri)
{
using (var _uri = Android.Net.Uri.Parse(uri))
using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView, _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
public static ISpanned GetSpannedHTML(this NativeContext context, int resid)
{
return context.GetString(resid).ToSpannedHTML();
}
public static void LaunchAppSettings(this NativeContext context)
{
using (var _uri = Android.Net.Uri.Parse("package:" + context.PackageName))
using (var intent = new Android.Content.Intent("android.settings.<API key>", _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
// ACTIVITIES
public static float CanvasScaleHint(this NativeActivity activity)
{
using (var displayMetrics = new DisplayMetrics())
{
activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics);
if (displayMetrics.ScaledDensity.IsZero()) //can this even happen??
return 1.0f;
return (displayMetrics.ScaledDensity / 3.0f).Clamp(0.4f, 1.5f);
}
}
public static void With<T>(this NativeActivity activity, int id, Action<T> viewAction) where T : Android.Views.View
{
using (var view = activity.FindViewById<T>(id))
viewAction(view);
}
// SKIA
public static NativeRect ToREKT(this SKRect rect)
{
return new NativeRect((int)rect.Left, (int)rect.Top,
(int)rect.Right, (int)rect.Bottom);
}
public static NativeColour ToNative(this SKColor col)
{
return new NativeColour(col.Red, col.Green, col.Blue, col.Alpha);
}
public static SKColor ToREKT(this NativeColour col)
{
return new SKColor(col.R, col.G, col.B, col.A);
}
// BITMAPS
public static SKBitmap ToSkia(this NativeBitmap source)
{
if (source == null)
throw new <API key>("source");
//init destination bitmap
var output = new SKBitmap(
source.Width,
source.Height,
SKColorType.Rgba8888,
SKAlphaType.Unpremul
);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.LockPixels();
var buffer = output.GetPixels();
unsafe
{
int* firstPixelAddr = (int*)buffer.ToPointer();
System.Threading.Tasks.Parallel.For(0, output.Height, (y) =>
{
int p = y * output.Width;
int* pixel = firstPixelAddr + p;
for (int x = 0; x < output.Width; x++, p++, pixel++)
*pixel = sourcePixels[p].SwapBytes02();
});
}
output.UnlockPixels();
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
public static Bitmap ToREKT(this NativeBitmap source)
{
if (source == null)
throw new <API key>("source");
#if DEBUG
StringBuilder sb = new StringBuilder("Bitmap: constructing from Android.Graphics.Bitmap:");
sb.AppendLine();
sb.AppendFormattedLine("Dimensions: {0} x {1}", source.Width, source.Height);
sb.AppendFormattedLine("AllocationByteCount: {0}", source.AllocationByteCount);
sb.AppendFormattedLine("ByteCount: {0}", source.ByteCount);
sb.AppendFormattedLine("RowBytes: {0}", source.RowBytes);
sb.AppendFormattedLine("Density: {0}", source.Density);
sb.AppendFormattedLine("HasAlpha: {0}", source.HasAlpha);
sb.AppendFormattedLine("IsPremultiplied: {0}", source.IsPremultiplied);
D.WriteLine(sb);
#endif
//init destination bitmap
var output = new Bitmap(source.Width, source.Height, SKColorType.Rgba8888);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.Lock((buffer) =>
{
unsafe
{
byte* firstPixelAddr = (byte*)buffer.ToPointer();
Thread.Distribute((threadIndex, threadCount) =>
{
for (long y = threadIndex; y < output.Height; y += threadCount)
{
long p = y * output.Width;
for (long x = 0; x < output.Width; x++, p++)
output.SetPixel(firstPixelAddr, x, y, ((uint)sourcePixels[p]));
}
});
}
});
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
// UUIDs
public static bool Equals(this Java.Util.UUID uuid, string uuidString)
{
if (uuid == null)
throw new <API key>("uuid");
if (uuidString == null)
throw new <API key>("uuidString");
return uuid.ToString().ToUpper() == uuidString.ToUpper();
}
}
}
|
// animating the scroll effect
$('.screenshots').on('click', function(e){
e.preventDefault();
$("html, body").animate({ scrollTop: "950px", duration: 500 });
});
|
#include "strm.h"
#include <math.h>
static int
num_plus(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)+strm_value_int(y));
return STRM_OK;
}
if (strm_number_p(x) && strm_number_p(y)) {
*ret = strm_float_value(strm_value_float(x)+strm_value_float(y));
return STRM_OK;
}
return STRM_NG;
}
static int
num_minus(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
if (argc == 1) {
if (strm_int_p(args[0])) {
*ret = strm_int_value(-strm_value_int(args[0]));
return STRM_OK;
}
if (strm_float_p(args[0])) {
*ret = strm_float_value(-strm_value_float(args[0]));
return STRM_OK;
}
}
else {
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)-strm_value_int(y));
return STRM_OK;
}
if (strm_number_p(x) && strm_number_p(y)) {
*ret = strm_float_value(strm_value_float(x)-strm_value_float(y));
return STRM_OK;
}
}
return STRM_NG;
}
static int
num_mult(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "NN", &x, &y);
if (strm_int_p(x) && strm_int_p(y)) {
*ret = strm_int_value(strm_value_int(x)*strm_value_int(y));
return STRM_OK;
}
*ret = strm_float_value(strm_value_float(x)*strm_value_float(y));
return STRM_OK;
}
static int
num_div(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_float_value(x/y);
return STRM_OK;
}
static int
num_bar(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x, y;
strm_get_args(strm, argc, args, "ii", &x, &y);
*ret = strm_int_value(strm_value_int(x)|strm_value_int(y));
return STRM_OK;
}
static int
num_mod(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_value x;
strm_int y;
strm_get_args(strm, argc, args, "Ni", &x, &y);
if (strm_int_p(x)) {
*ret = strm_int_value(strm_value_int(x)%y);
return STRM_OK;
}
if (strm_float_p(x)) {
*ret = strm_float_value(fmod(strm_value_float(x), y));
return STRM_OK;
}
return STRM_NG;
}
static int
num_gt(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x>y);
return STRM_OK;
}
static int
num_ge(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x>=y);
return STRM_OK;
}
static int
num_lt(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x<y);
return STRM_OK;
}
static int
num_le(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
double x, y;
strm_get_args(strm, argc, args, "ff", &x, &y);
*ret = strm_bool_value(x<=y);
return STRM_OK;
}
static int
num_number(strm_stream* strm, int argc, strm_value* args, strm_value* ret)
{
strm_get_args(strm, argc, args, "N", ret);
return STRM_OK;
}
strm_state* strm_ns_number;
void
strm_number_init(strm_state* state)
{
strm_ns_number = strm_ns_new(NULL, "number");
strm_var_def(strm_ns_number, "+", strm_cfunc_value(num_plus));
strm_var_def(strm_ns_number, "-", strm_cfunc_value(num_minus));
strm_var_def(strm_ns_number, "*", strm_cfunc_value(num_mult));
strm_var_def(strm_ns_number, "/", strm_cfunc_value(num_div));
strm_var_def(strm_ns_number, "%", strm_cfunc_value(num_mod));
strm_var_def(strm_ns_number, "|", strm_cfunc_value(num_bar));
strm_var_def(strm_ns_number, "<", strm_cfunc_value(num_lt));
strm_var_def(strm_ns_number, "<=", strm_cfunc_value(num_le));
strm_var_def(strm_ns_number, ">", strm_cfunc_value(num_gt));
strm_var_def(strm_ns_number, ">=", strm_cfunc_value(num_ge));
strm_var_def(state, "number", strm_cfunc_value(num_number));
}
|
<html>
<head>
</head>
<body>
<h2>
Their Antiquity
</h2>
<span class="oldenglish">
Who
</span>
<span class="oldenglish">
were
</span>
<span class="oldenglish">
the
</span>
originall
<span class="oldenglish">
writers
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
the
</span>
severall
<span class="oldenglish">
Books
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
Holy
</span>
Scripture, has
<span class="english">
not
</span>
been
<span class="oldenglish">
made
</span>
<span class="oldfrench">
evident
</span>
<span class="oldenglish">
by
</span>
<span class="oldenglish">
any
</span>
<span class="oldfrench">
sufficient
</span>
<span class="oldfrench">
testimony
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
other
</span>
History, (which
<span class="oldenglish">
is
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
only
</span>
<span class="oldfrench">
proof
</span>
<span class="oldenglish">
of
</span>
<span class="oldfrench">
matter
</span>
<span class="oldenglish">
of
</span>
fact);
<span class="english">
nor
</span>
<span class="oldenglish">
can
</span>
<span class="oldenglish">
be
</span>
<span class="oldenglish">
by
</span>
<span class="oldenglish">
any
</span>
<span class="oldfrench">
arguments
</span>
<span class="oldenglish">
of
</span>
naturall Reason;
<span class="oldenglish">
for
</span>
<span class="oldfrench">
Reason
</span>
serves
<span class="oldenglish">
only
</span>
<span class="oldenglish">
to
</span>
<span class="latin">
convince
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
truth
</span>
(not
<span class="oldenglish">
of
</span>
fact, but)
<span class="oldenglish">
of
</span>
consequence.
<span class="oldenglish">
The
</span>
<span class="oldenglish">
light
</span>
<span class="oldenglish">
therefore
</span>
<span class="oldenglish">
that
</span>
<span class="oldenglish">
must
</span>
<span class="oldfrench">
guide
</span>
<span class="oldenglish">
us
</span>
<span class="oldenglish">
in
</span>
<span class="oldenglish">
this
</span>
question,
<span class="oldenglish">
must
</span>
<span class="oldenglish">
be
</span>
<span class="oldenglish">
that
</span>
<span class="oldenglish">
which
</span>
<span class="oldenglish">
is
</span>
<span class="oldenglish">
held
</span>
<span class="oldenglish">
out
</span>
<span class="oldenglish">
unto
</span>
<span class="oldenglish">
us
</span>
<span class="oldenglish">
from
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
Bookes
</span>
themselves:
<span class="oldenglish">
And
</span>
<span class="oldenglish">
this
</span>
light,
<span class="oldenglish">
though
</span>
<span class="oldenglish">
it
</span>
<span class="americanenglish">
show
</span>
<span class="oldenglish">
us
</span>
<span class="english">
not
</span>
<span class="oldenglish">
the
</span>
<span class="oldenglish">
writer
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
every
</span>
book,
<span class="oldenglish">
yet
</span>
<span class="oldenglish">
it
</span>
<span class="oldenglish">
is
</span>
<span class="english">
not
</span>
unusefull
<span class="oldenglish">
to
</span>
<span class="oldenglish">
give
</span>
<span class="oldenglish">
us
</span>
<span class="english">
knowledge
</span>
<span class="oldenglish">
of
</span>
<span class="oldenglish">
the
</span>
time,
<span class="dutch">
wherein
</span>
<span class="oldnorse">
they
</span>
<span class="oldenglish">
were
</span>
written.
</body>
</html>
|
'use strict';
var path = require('path');
module.exports = path.join.bind(path, __dirname, '..');
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Master thesis presentation – OpenLaws</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Presentation of Master thesis @CEID">
<meta name="author" content="Kostas Plessas">
<meta name="keywords" content="publications">
<link rel="canonical" href="http:
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/pixyll.css" type="text/css">
<!-- Fonts -->
<link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Open Graph -->
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Master thesis presentation">
<meta property="og:description" content="A Project Opening Greek Legislation to Citizens">
<meta property="og:url" content="http:
<meta property="og:site_name" content="OpenLaws">
<!-- Icons -->
<link rel="apple-touch-icon" sizes="57x57" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="114x114" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="72x72" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="144x144" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="60x60" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="120x120" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="76x76" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="152x152" href="/<API key>.png">
<link rel="apple-touch-icon" sizes="180x180" href="/<API key>.png">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/<API key>.png" sizes="192x192">
</head>
<body class="">
<div class="site-wrap">
<header class="site-header px2 px-responsive">
<div class="mt2 wrap">
<div class="measure">
<div><a href="http:
<nav class="site-nav right">
<a href="/about/">About</a>
<a href="/roadmap/">Roadmap</a>
<!--<a href="/contact/">Contact</a>-->
</nav>
<div class="clearfix"></div>
<div class="social-icons">
<div class="right">
<a class="fa fa-github" href="https://github.com/OpenLawsGR"></a>
<a class="fa fa-rss" href="/feed.xml"></a>
<a class="fa fa-twitter" href="https://twitter.com/OpenLawsGR"></a>
<a class="fa fa-envelope" href="mailto:kplessas@ceid.upatras.gr"></a>
</div>
<div class="right">
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</header>
<div class="post p2 p-responsive wrap" role="main">
<div class="measure">
<div class="post-header mb2">
<h1>Master thesis presentation</h1>
<span class="post-meta">Oct 19, 2016</span><br>
<span class="post-meta small">1 minute read</span>
</div>
<article class="post-content">
<p>This project is implemented in the framework of a Master thesis for the postgraduate program Computer Science and Technology at the <a href="https:
<p>Last week, the defense presentation of the thesis took place successfully.</p>
<p><img src="/images/<API key>.jpg" alt="Master thesis presentation"></p>
<p>The text of the thesis (in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.<API key>.pdf">here</a>.</p>
<p>The presentation (also in Greek) can be found <a href="https://dl.dropboxusercontent.com/u/104921582/K.<API key>.pdf">here</a>. </p>
</article>
<div class="share-page">
Share this post!
<div class="share-links">
<a class = "fa fa-facebook" href="https:
<a class="fa fa-twitter" href="https:
<a class="fa fa-google-plus" href="https:
<a class="fa fa-linkedin" href="http:
<a class = "fa fa-hacker-news" onclick="parent.postMessage('submit','*')" href="https:
</div>
</div>
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'OpenLawsGR';
var disqus_identifier = '/publications/2016/10/19/<API key>';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.<API key>('head')[0] || document.<API key>('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
</div>
<footer class="footer">
<div class="p2 wrap">
<div class="measure mt1 center">
<small>
Based on <a href="https:
</small>
</div>
</div>
</footer>
</body>
</html>
|
<?php
namespace RunOpenCode\AssetsInjection\Tests\Mockup;
use RunOpenCode\AssetsInjection\Contract\Compiler\<API key>;
use RunOpenCode\AssetsInjection\Contract\ContainerInterface;
use RunOpenCode\AssetsInjection\Library\LibraryDefinition;
use RunOpenCode\AssetsInjection\Value\CompilerPassResult;
/**
* Class DummyCompilerPass
*
* Dummy compiler pass which will add definition with given name to container in order to check validity of executed test.
*
* @package RunOpenCode\AssetsInjection\Tests\Mockup
*/
final class DummyCompilerPass implements <API key>
{
/**
* @var string
*/
private $<API key>;
/**
* @var bool
*/
private $stopProcessing;
/**
* A constructor.
*
* @param string $<API key> LibraryDefinition marker name to add to container.
* @param bool|false $stopProcessing Should compilation be stopped.
*/
public function __construct($<API key>, $stopProcessing = false)
{
$this-><API key> = $<API key>;
$this->stopProcessing = $stopProcessing;
}
/**
* {@inheritdoc}
*/
public function process(ContainerInterface $container)
{
$container->getLibraries()->addDefinition(new LibraryDefinition($this-><API key>));
return new CompilerPassResult($container, $this->stopProcessing);
}
}
|
var markdown = window.markdownit();
$(document).ready(function() {
var $wish = $('#wish');
var <API key> = $('#todos .notification-area');
var <API key> = $('#todos .notification-area > i');
var <API key> = $('#todos .notification-area > span');
$('#news-stream .menu .item').tab({history:false});
$('.todo.menu .item').tab({history:false});
$('.top.menu .item').tab({history:false});
$('body').on('click', '.button', function() {
$(this).transition('pulse');
})
$('#todos').ready(function() {
$.each($('#todos .segment'), function(index, $element){
var $html, $md;
$element = $($element);
$md = $element.find('.md-content-name');
$html = $element.find('.html-content-name');
$html.html(markdown.render($md.val()));
$md = $element.find('.md-content');
$html = $element.find('.html-content');
$html.html(markdown.render($md.val()));
});
});
$('#todos').on('click', '.edit.button', function() {
var $button = $(this);
var $html = $button.parent().siblings('.html-content');
var $md = $button.parent().siblings('.md-content');
var $htmlname = $button.parent().siblings('.html-content-name');
var $mdname = $button.parent().siblings('.md-content-name');
if($html.css('display') == 'none') {
var result = markdown.render($md.val());
$html.html(result);
result = markdown.render($mdname.val());
$htmlname.html(result);
$button.text('Edit');
}
else {
$button.text('Preview');
}
$md.toggle();
$html.toggle();
$mdname.toggle();
$htmlname.toggle();
});
$('#todos').on('click', '.save.button', function() {
var $button = $(this);
var $mdname = $button.parent().parent().find('input');
var $md = $button.parent().parent().find('textarea');
var id = $button.parent().parent().attr('data-tab');
$.post('/todos/save', {id:id, name: $mdname.val(), content: $md.val()}, function(resp){
console.log('Saved');
});
});
$('#todos').on('click', '.delete.button', function() {
var $button = $(this);
var id = $button.parent().parent().attr('data-tab');
$.post('/todos/delete', {id:id}, function(resp){
$('*[data-tab="'+id+'"]').remove();
});
});
$('#new-todo').click(function(e) {
$button = $(this);
$.post('/todos/create', function(resp) {
var $menuItem = $('<a>').addClass('item').attr('data-tab', resp.id)
.html(resp.name);
var $todoContent = $('<div>').addClass('ui tab basic segment basic')
.attr('data-tab', resp.id)
.append(
$('<div>').addClass('ui text menu right floated')
.append($('<div>').addClass('ui edit basic button item').text('Edit'))
.append($('<div>').addClass('ui save basic button item').text('Save'))
.append($('<div>').addClass('ui download basic button item').text('Download'))
.append($('<div>').addClass('ui delete basic button item').text('Delete'))
)
.append(
$('<div>').addClass('ui section divider')
)
.append(
$('<input>').addClass('ui fluid md-content-name')
.attr('style', 'display:none;').val(resp.name)
)
.append(
$('<div>').addClass('html-content-name').html(markdown.render(resp.name))
)
.append(
$('<div>').addClass('ui horizontal divider')
)
.append(
$('<textarea>').addClass('md-content')
.attr('style', 'display:none;').html(resp.content)
)
.append(
$('<div>').addClass('html-content')
);
$button.parent().append($menuItem);
$button.parent().parent().next().prepend($todoContent);
$button.parent().children().last().tab({history:false});
})
.fail(function() {
uiModules.showError('Something went wrong while creating a Todo');
});
})
$('#reminders').on('click', 'i.delete', function(e){
var $parentTr = $(this).parents("tr");
$.post('/reminders/' + $parentTr.attr('id') + '/delete', function(resp) {
$parentTr.remove();
})
});
$('#wish-form').submit(function(e){
e.preventDefault();
var wish = $wish.val();
$.get('/wish', {wish: wish}, function(resp) {
var targetType = resp.type;
if(targetType === 'remind') {
var value = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
$('#reminders table tbody').append(
$('<tr>').attr('id', value.id)
.append($('<td>').html(value.m))
.append($('<td>').html(value.t))
.append($('<td>').html(value.d))
.append($('<td>').append($('<i>').addClass('ui delete red icon')))
);
}
else if(targetType === 'comic') {
var link = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
var $webcomicmodal = $('#webcomic-modal');
$webcomicmodal.find('.header').html(link.title);
$webcomicmodal.find('a').attr('href', link.url);
var showModal = true;
if (link.content_type == 'image') {
$webcomicmodal.find('img').attr('src', link.content_url);
}
else if (link.content_type == 'page') {
alert('Page found');
}
else {
showModal = false;
uiModules.showError('Unsuported content_type ' + link.content_type);
}
if( showModal ) {
$webcomicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$webcomicmodal.modal("refresh");
}
}).modal('show');
}
}
else if(targetType === 'astro') {
var url = resp.response;
var error = resp.error
if (error) {
uiModules.showError(error);
return;
}
$('#astro-modal iframe').attr('src', url);
$('#astro-modal').modal({
onVisible: function () {
$("#astro-modal").modal("refresh");
}
}).modal('show');
}
else {
uiModules.showError('Invalid type ' + resp.type);
}
// $('#reply').addClass('animated slideInDown').html(resp.response.message);
// setTimeout(function() {
// $('#reply').removeClass('animated slideInDown');
// }, 1000);
});
$wish.val(null);
});
$.get('/commands', function(resp) {
$('#commands').html(resp);
});
$('#webcomics .button').click(function(e) {
var $comic = $(this).parent()
var comic_id = $comic.attr('id');
var $button = $comic.find('.button');
$button.addClass('disabled');
$.post('/webcomics/' + comic_id + '/sync', function(response) {
$comic.find('p').text(response.resp.links_count);
$comic.find('label').text(response.resp.last_sync);
}).
always(function() {
$button.removeClass('disabled');
});
});
$('#astros .button').click(function(e) {
var $astro = $(this).parent()
var astro_id = $astro.attr('id');
var $button = $astro.find('.button');
$button.addClass('disabled');
$.post('/astros/' + astro_id + '/sync', function(response) {
$astro.find('p').text(response.resp.links_count);
$astro.find('label').text(response.resp.last_sync);
}).
always(function() {
$button.removeClass('disabled');
});
});
$('#<API key>').click(function(e) {
var $playlist_name = $('#playlist-name');
var name = $playlist_name.val();
if(!name) {
uiModules.showError('Playlist name cannot be empty');
return;
}
name = name.trim();
$.post('/music/playlist/create', {name:name}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
$('#music .playlists').append(resp.html);
$playlist_name.val(null);
});
});
$('#music').on('click', 'i.delete-playlist', function(e) {
var $playlist_element = $(this).parents('div');
var playlist_id = $playlist_element.attr('id');
$.post('/music/playlist/delete', {id:playlist_id}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
if(resp.resp) {
$('#' + playlist_id).remove();
uiModules.notify('Playlist deleted successfully');
}
else {
uiModules.showError('Playlist not deleted');
}
})
});
$('#music').on('click', '.youtube-link button', function(e) {
var $button = $(this);
var $link_input = $(this).siblings('input');
var link = $link_input.val();
if(!link) {
$link_input.parent().addClass('error');
uiModules.showError('No link found');
return;
}
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
$button.addClass('loading');
$.post('/music/playlist/'+ playlist_id +'/add', {link: link, site: 'youtube'}, function(resp) {
if(resp.error) {
uiModules.showError(resp.error);
return;
}
$playlist_element.find('.update-field').text(resp.resp.updated_at);
$playlist_element.find('.links-count').text(resp.resp.links_count)
}).always(function(){
$link_input.val(null);
$button.removeClass('loading');
});
});
$('#music').on('click', '.random-music', function(e) {
var $button = $(this);
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
$.get('/music/playlist/'+ playlist_id +'/random', function(resp) {
var video_id = resp.resp.video_id;
var $musicmodal = $('#music-modal');
$musicmodal.find('.header').html(resp.resp.title);
$musicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$musicmodal.modal("refresh");
music_player.loadVideoById(video_id, 0, "large")
},
onHidden: function() {
music_player.stopVideo();
}
}).modal('show');
}).fail(function(response) {
uiModules.showError(response.responseText);
})
});
$('#music').on('click', '.full-playlist', function(e) {
var $button = $(this);
var playlist_id = $button.parents('div.playlist').attr('id');
var $playlist_element = $('#' + playlist_id);
var playlist_name = $playlist_element.find('a.header').text();
$.get('/music/playlist/'+ playlist_id +'/all', function(resp) {
var $musicmodal = $('#music-modal');
$musicmodal.find('.header').html(resp.resp.title);
$musicmodal.modal({
context: 'html',
observeChanges: true,
onVisible: function () {
$musicmodal.modal("refresh");
var ids = [];
for( var i = 0; i < 100 && i < resp.resp.length ; i++ ) {
var video = resp.resp[i];
ids.push(video.video_id);
}
music_player.loadPlaylist(ids);
},
onHidden: function() {
music_player.stopVideo();
}
}).modal('show');
}).fail(function(response) {
uiModules.showError(response.responseText);
})
});
});
|
// AWSAppDelegate.h
// TAWS
@import UIKit;
@interface AWSAppDelegate : UIResponder <<API key>>
@property (strong, nonatomic) UIWindow *window;
@end
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-erasure: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">8.10.dev / metacoq-erasure - 1.0~alpha+8.8</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-erasure
<small>
1.0~alpha+8.8
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2020-07-17 06:06:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-17 06:06:32 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.10.dev Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.8"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <aa755@cs.cornell.edu>"
"Simon Boulier <simon.boulier@inria.fr>"
"Cyril Cohen <cyril.cohen@inria.fr>"
"Yannick Forster <forster@ps.uni-saarland.de>"
"Fabian Kunze <fkunze@fakusb.de>"
"Gregory Malecha <gmalecha@gmail.com>"
"Matthieu Sozeau <matthieu.sozeau@inria.fr>"
"Nicolas Tabareau <nicolas.tabareau@inria.fr>"
"Théo Winterhalter <theo.winterhalter@inria.fr>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j%{jobs}%" "-C" "erasure"]
[make "test-suite"] {with-test}
]
install: [
[make "-C" "erasure" "install"]
]
depends: [
"ocaml" {> "4.02.3"}
"coq" {>= "8.8" & < "8.9~"}
"<API key>" {= version}
"coq-metacoq-checker" {= version}
"coq-metacoq-pcuic" {= version}
"<API key>" {= version}
]
synopsis: "Implementation and verification of an erasure procedure for Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
The Erasure module provides a complete specification of Coq's so-called
\"extraction\" procedure, starting from the PCUIC calculus and targeting
untyped call-by-value lambda-calculus.
The `erasure` function translates types and proofs in well-typed terms
into a dummy `tBox` constructor, following closely P. Letouzey's PhD
thesis.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.8.tar.gz"
checksum: "sha256=<SHA256-like>"
}</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-erasure.1.0~alpha+8.8 coq.8.10.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.dev).
The following dependencies couldn't be met:
- coq-metacoq-erasure -> coq < 8.9~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-erasure.1.0~alpha+8.8</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
# This file is part of beets.
# 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,
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# included in all copies or substantial portions of the Software.
"""The Query type hierarchy for DBCore.
"""
import re
from operator import mul
from beets import util
from datetime import datetime, timedelta
import unicodedata
from functools import reduce
class ParsingError(ValueError):
"""Abstract class for any unparseable user-requested album/query
specification.
"""
class InvalidQueryError(ParsingError):
"""Represent any kind of invalid query.
The query should be a unicode string or a list, which will be space-joined.
"""
def __init__(self, query, explanation):
if isinstance(query, list):
query = " ".join(query)
message = f"'{query}': {explanation}"
super().__init__(message)
class <API key>(ParsingError):
"""Represent a query argument that could not be converted as expected.
It exists to be caught in upper stack levels so a meaningful (i.e. with the
query) InvalidQueryError can be raised.
"""
def __init__(self, what, expected, detail=None):
message = f"'{what}' is not {expected}"
if detail:
message = f"{message}: {detail}"
super().__init__(message)
class Query:
"""An abstract class representing a query into the item database.
"""
def clause(self):
"""Generate an SQLite expression implementing the query.
Return (clause, subvals) where clause is a valid sqlite
WHERE clause implementing the query and subvals is a list of
items to be substituted for ?s in the clause.
"""
return None, ()
def match(self, item):
"""Check whether this query matches a given Item. Can be used to
perform queries on arbitrary sets of Items.
"""
raise NotImplementedError
def __repr__(self):
return f"{self.__class__.__name__}()"
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return 0
class FieldQuery(Query):
"""An abstract query that searches in a specific field for a
pattern. Subclasses must provide a `value_match` class method, which
determines whether a certain pattern string matches a certain value
string. Subclasses may also provide `col_clause` to implement the
same matching functionality in SQLite.
"""
def __init__(self, field, pattern, fast=True):
self.field = field
self.pattern = pattern
self.fast = fast
def col_clause(self):
return None, ()
def clause(self):
if self.fast:
return self.col_clause()
else:
# Matching a flexattr. This is a slow query.
return None, ()
@classmethod
def value_match(cls, pattern, value):
"""Determine whether the value matches the pattern. Both
arguments are strings.
"""
raise NotImplementedError()
def match(self, item):
return self.value_match(self.pattern, item.get(self.field))
def __repr__(self):
return ("{0.__class__.__name__}({0.field!r}, {0.pattern!r}, "
"{0.fast})".format(self))
def __eq__(self, other):
return super().__eq__(other) and \
self.field == other.field and self.pattern == other.pattern
def __hash__(self):
return hash((self.field, hash(self.pattern)))
class MatchQuery(FieldQuery):
"""A query that looks for exact matches in an item field."""
def col_clause(self):
return self.field + " = ?", [self.pattern]
@classmethod
def value_match(cls, pattern, value):
return pattern == value
class NoneQuery(FieldQuery):
"""A query that checks whether a field is null."""
def __init__(self, field, fast=True):
super().__init__(field, None, fast)
def col_clause(self):
return self.field + " IS NULL", ()
def match(self, item):
return item.get(self.field) is None
def __repr__(self):
return "{0.__class__.__name__}({0.field!r}, {0.fast})".format(self)
class StringFieldQuery(FieldQuery):
"""A FieldQuery that converts values to strings before matching
them.
"""
@classmethod
def value_match(cls, pattern, value):
"""Determine whether the value matches the pattern. The value
may have any type.
"""
return cls.string_match(pattern, util.as_string(value))
@classmethod
def string_match(cls, pattern, value):
"""Determine whether the value matches the pattern. Both
arguments are strings. Subclasses implement this method.
"""
raise NotImplementedError()
class StringQuery(StringFieldQuery):
"""A query that matches a whole string in a specific item field."""
def col_clause(self):
search = (self.pattern
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_'))
clause = self.field + " like ? escape '\\'"
subvals = [search]
return clause, subvals
@classmethod
def string_match(cls, pattern, value):
return pattern.lower() == value.lower()
class SubstringQuery(StringFieldQuery):
"""A query that matches a substring in a specific item field."""
def col_clause(self):
pattern = (self.pattern
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_'))
search = '%' + pattern + '%'
clause = self.field + " like ? escape '\\'"
subvals = [search]
return clause, subvals
@classmethod
def string_match(cls, pattern, value):
return pattern.lower() in value.lower()
class RegexpQuery(StringFieldQuery):
"""A query that matches a regular expression in a specific item
field.
Raises InvalidQueryError when the pattern is not a valid regular
expression.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
pattern = self._normalize(pattern)
try:
self.pattern = re.compile(self.pattern)
except re.error as exc:
# Invalid regular expression.
raise <API key>(pattern,
"a regular expression",
format(exc))
@staticmethod
def _normalize(s):
"""Normalize a Unicode string's representation (used on both
patterns and matched values).
"""
return unicodedata.normalize('NFC', s)
@classmethod
def string_match(cls, pattern, value):
return pattern.search(cls._normalize(value)) is not None
class BooleanQuery(MatchQuery):
"""Matches a boolean field. Pattern should either be a boolean or a
string reflecting a boolean.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
if isinstance(pattern, str):
self.pattern = util.str2bool(pattern)
self.pattern = int(self.pattern)
class BytesQuery(MatchQuery):
"""Match a raw bytes field (i.e., a path). This is a necessary hack
to work around the `sqlite3` module's desire to treat `bytes` and
`unicode` equivalently in Python 2. Always use this query instead of
`MatchQuery` when matching on BLOB values.
"""
def __init__(self, field, pattern):
super().__init__(field, pattern)
# Use a buffer/memoryview representation of the pattern for SQLite
# matching. This instructs SQLite to treat the blob as binary
# rather than encoded Unicode.
if isinstance(self.pattern, (str, bytes)):
if isinstance(self.pattern, str):
self.pattern = self.pattern.encode('utf-8')
self.buf_pattern = memoryview(self.pattern)
elif isinstance(self.pattern, memoryview):
self.buf_pattern = self.pattern
self.pattern = bytes(self.pattern)
def col_clause(self):
return self.field + " = ?", [self.buf_pattern]
class NumericQuery(FieldQuery):
"""Matches numeric fields. A syntax using Ruby-style range ellipses
(``..``) lets users specify one- or two-sided ranges. For example,
``year:2001..`` finds music released since the turn of the century.
Raises InvalidQueryError when the pattern does not represent an int or
a float.
"""
def _convert(self, s):
"""Convert a string to a numeric type (float or int).
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
# This is really just a bit of fun premature optimization.
if not s:
return None
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise <API key>(s, "an int or a float")
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
parts = pattern.split('..', 1)
if len(parts) == 1:
# No range.
self.point = self._convert(parts[0])
self.rangemin = None
self.rangemax = None
else:
# One- or two-sided range.
self.point = None
self.rangemin = self._convert(parts[0])
self.rangemax = self._convert(parts[1])
def match(self, item):
if self.field not in item:
return False
value = item[self.field]
if isinstance(value, str):
value = self._convert(value)
if self.point is not None:
return value == self.point
else:
if self.rangemin is not None and value < self.rangemin:
return False
if self.rangemax is not None and value > self.rangemax:
return False
return True
def col_clause(self):
if self.point is not None:
return self.field + '=?', (self.point,)
else:
if self.rangemin is not None and self.rangemax is not None:
return ('{0} >= ? AND {0} <= ?'.format(self.field),
(self.rangemin, self.rangemax))
elif self.rangemin is not None:
return f'{self.field} >= ?', (self.rangemin,)
elif self.rangemax is not None:
return f'{self.field} <= ?', (self.rangemax,)
else:
return '1', ()
class CollectionQuery(Query):
"""An abstract query class that aggregates other queries. Can be
indexed like a list to access the sub-queries.
"""
def __init__(self, subqueries=()):
self.subqueries = subqueries
# Act like a sequence.
def __len__(self):
return len(self.subqueries)
def __getitem__(self, key):
return self.subqueries[key]
def __iter__(self):
return iter(self.subqueries)
def __contains__(self, item):
return item in self.subqueries
def clause_with_joiner(self, joiner):
clause_parts = []
subvals = []
for subq in self.subqueries:
subq_clause, subq_subvals = subq.clause()
if not subq_clause:
# Fall back to slow query.
return None, ()
clause_parts.append('(' + subq_clause + ')')
subvals += subq_subvals
clause = (' ' + joiner + ' ').join(clause_parts)
return clause, subvals
def __repr__(self):
return "{0.__class__.__name__}({0.subqueries!r})".format(self)
def __eq__(self, other):
return super().__eq__(other) and \
self.subqueries == other.subqueries
def __hash__(self):
"""Since subqueries are mutable, this object should not be hashable.
However and for conveniences purposes, it can be hashed.
"""
return reduce(mul, map(hash, self.subqueries), 1)
class AnyFieldQuery(CollectionQuery):
"""A query that matches if a given FieldQuery subclass matches in
any field. The individual field query class is provided to the
constructor.
"""
def __init__(self, pattern, fields, cls):
self.pattern = pattern
self.fields = fields
self.query_class = cls
subqueries = []
for field in self.fields:
subqueries.append(cls(field, pattern, True))
super().__init__(subqueries)
def clause(self):
return self.clause_with_joiner('or')
def match(self, item):
for subq in self.subqueries:
if subq.match(item):
return True
return False
def __repr__(self):
return ("{0.__class__.__name__}({0.pattern!r}, {0.fields!r}, "
"{0.query_class.__name__})".format(self))
def __eq__(self, other):
return super().__eq__(other) and \
self.query_class == other.query_class
def __hash__(self):
return hash((self.pattern, tuple(self.fields), self.query_class))
class <API key>(CollectionQuery):
"""A collection query whose subqueries may be modified after the
query is initialized.
"""
def __setitem__(self, key, value):
self.subqueries[key] = value
def __delitem__(self, key):
del self.subqueries[key]
class AndQuery(<API key>):
"""A conjunction of a list of other queries."""
def clause(self):
return self.clause_with_joiner('and')
def match(self, item):
return all(q.match(item) for q in self.subqueries)
class OrQuery(<API key>):
"""A conjunction of a list of other queries."""
def clause(self):
return self.clause_with_joiner('or')
def match(self, item):
return any(q.match(item) for q in self.subqueries)
class NotQuery(Query):
"""A query that matches the negation of its `subquery`, as a shorcut for
performing `not(subquery)` without using regular expressions.
"""
def __init__(self, subquery):
self.subquery = subquery
def clause(self):
clause, subvals = self.subquery.clause()
if clause:
return f'not ({clause})', subvals
else:
# If there is no clause, there is nothing to negate. All the logic
# is handled by match() for slow queries.
return clause, subvals
def match(self, item):
return not self.subquery.match(item)
def __repr__(self):
return "{0.__class__.__name__}({0.subquery!r})".format(self)
def __eq__(self, other):
return super().__eq__(other) and \
self.subquery == other.subquery
def __hash__(self):
return hash(('not', hash(self.subquery)))
class TrueQuery(Query):
"""A query that always matches."""
def clause(self):
return '1', ()
def match(self, item):
return True
class FalseQuery(Query):
"""A query that never matches."""
def clause(self):
return '0', ()
def match(self, item):
return False
# Time/date queries.
def _to_epoch_time(date):
"""Convert a `datetime` object to an integer number of seconds since
the (local) Unix epoch.
"""
if hasattr(date, 'timestamp'):
# The `timestamp` method exists on Python 3.3+.
return int(date.timestamp())
else:
epoch = datetime.fromtimestamp(0)
delta = date - epoch
return int(delta.total_seconds())
def _parse_periods(pattern):
"""Parse a string containing two dates separated by two dots (..).
Return a pair of `Period` objects.
"""
parts = pattern.split('..', 1)
if len(parts) == 1:
instant = Period.parse(parts[0])
return (instant, instant)
else:
start = Period.parse(parts[0])
end = Period.parse(parts[1])
return (start, end)
class Period:
"""A period of time given by a date, time and precision.
Example: 2014-01-01 10:50:30 with precision 'month' represents all
instants of time during January 2014.
"""
precisions = ('year', 'month', 'day', 'hour', 'minute', 'second')
date_formats = (
('%Y',), # year
('%Y-%m',), # month
('%Y-%m-%d',), # day
('%Y-%m-%dT%H', '%Y-%m-%d %H'), # hour
('%Y-%m-%dT%H:%M', '%Y-%m-%d %H:%M'), # minute
('%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S') # second
)
relative_units = {'y': 365, 'm': 30, 'w': 7, 'd': 1}
relative_re = '(?P<sign>[+|-]?)(?P<quantity>[0-9]+)' + \
'(?P<timespan>[y|m|w|d])'
def __init__(self, date, precision):
"""Create a period with the given date (a `datetime` object) and
precision (a string, one of "year", "month", "day", "hour", "minute",
or "second").
"""
if precision not in Period.precisions:
raise ValueError(f'Invalid precision {precision}')
self.date = date
self.precision = precision
@classmethod
def parse(cls, string):
"""Parse a date and return a `Period` object or `None` if the
string is empty, or raise an <API key> if
the string cannot be parsed to a date.
The date may be absolute or relative. Absolute dates look like
`YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative
dates have three parts:
- Optionally, a ``+`` or ``-`` sign indicating the future or the
past. The default is the future.
- A number: how much to add or subtract.
- A letter indicating the unit: days, weeks, months or years
(``d``, ``w``, ``m`` or ``y``). A "month" is exactly 30 days
and a "year" is exactly 365 days.
"""
def <API key>(string):
for ord, format in enumerate(cls.date_formats):
for format_option in format:
try:
date = datetime.strptime(string, format_option)
return date, ord
except ValueError:
# Parsing failed.
pass
return (None, None)
if not string:
return None
# Check for a relative date.
match_dq = re.match(cls.relative_re, string)
if match_dq:
sign = match_dq.group('sign')
quantity = match_dq.group('quantity')
timespan = match_dq.group('timespan')
# Add or subtract the given amount of time from the current
# date.
multiplier = -1 if sign == '-' else 1
days = cls.relative_units[timespan]
date = datetime.now() + \
timedelta(days=int(quantity) * days) * multiplier
return cls(date, cls.precisions[5])
# Check for an absolute date.
date, ordinal = <API key>(string)
if date is None:
raise <API key>(string,
'a valid date/time string')
precision = cls.precisions[ordinal]
return cls(date, precision)
def open_right_endpoint(self):
"""Based on the precision, convert the period to a precise
`datetime` for use as a right endpoint in a right-open interval.
"""
precision = self.precision
date = self.date
if 'year' == self.precision:
return date.replace(year=date.year + 1, month=1)
elif 'month' == precision:
if (date.month < 12):
return date.replace(month=date.month + 1)
else:
return date.replace(year=date.year + 1, month=1)
elif 'day' == precision:
return date + timedelta(days=1)
elif 'hour' == precision:
return date + timedelta(hours=1)
elif 'minute' == precision:
return date + timedelta(minutes=1)
elif 'second' == precision:
return date + timedelta(seconds=1)
else:
raise ValueError(f'unhandled precision {precision}')
class DateInterval:
"""A closed-open interval of dates.
A left endpoint of None means since the beginning of time.
A right endpoint of None means towards infinity.
"""
def __init__(self, start, end):
if start is not None and end is not None and not start < end:
raise ValueError("start date {} is not before end date {}"
.format(start, end))
self.start = start
self.end = end
@classmethod
def from_periods(cls, start, end):
"""Create an interval with two Periods as the endpoints.
"""
end_date = end.open_right_endpoint() if end is not None else None
start_date = start.date if start is not None else None
return cls(start_date, end_date)
def contains(self, date):
if self.start is not None and date < self.start:
return False
if self.end is not None and date >= self.end:
return False
return True
def __str__(self):
return f'[{self.start}, {self.end})'
class DateQuery(FieldQuery):
"""Matches date fields stored as seconds since Unix epoch time.
Dates can be specified as ``year-month-day`` strings where only year
is mandatory.
The value of a date field can be matched against a date interval by
using an ellipsis interval syntax similar to that of NumericQuery.
"""
def __init__(self, field, pattern, fast=True):
super().__init__(field, pattern, fast)
start, end = _parse_periods(pattern)
self.interval = DateInterval.from_periods(start, end)
def match(self, item):
if self.field not in item:
return False
timestamp = float(item[self.field])
date = datetime.fromtimestamp(timestamp)
return self.interval.contains(date)
_clause_tmpl = "{0} {1} ?"
def col_clause(self):
clause_parts = []
subvals = []
if self.interval.start:
clause_parts.append(self._clause_tmpl.format(self.field, ">="))
subvals.append(_to_epoch_time(self.interval.start))
if self.interval.end:
clause_parts.append(self._clause_tmpl.format(self.field, "<"))
subvals.append(_to_epoch_time(self.interval.end))
if clause_parts:
# One- or two-sided interval.
clause = ' AND '.join(clause_parts)
else:
# Match any date.
clause = '1'
return clause, subvals
class DurationQuery(NumericQuery):
"""NumericQuery that allow human-friendly (M:SS) time interval formats.
Converts the range(s) to a float value, and delegates on NumericQuery.
Raises InvalidQueryError when the pattern does not represent an int, float
or M:SS time interval.
"""
def _convert(self, s):
"""Convert a M:SS or numeric string to a float.
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.
"""
if not s:
return None
try:
return util.raw_seconds_short(s)
except ValueError:
try:
return float(s)
except ValueError:
raise <API key>(
s,
"a M:SS string or a float")
# Sorting.
class Sort:
"""An abstract class representing a sort operation for a query into
the item database.
"""
def order_clause(self):
"""Generates a SQL fragment to be used in a ORDER BY clause, or
None if no fragment is used (i.e., this is a slow sort).
"""
return None
def sort(self, items):
"""Sort the list of objects and return a list.
"""
return sorted(items)
def is_slow(self):
"""Indicate whether this query is *slow*, meaning that it cannot
be executed in SQL and must be executed in Python.
"""
return False
def __hash__(self):
return 0
def __eq__(self, other):
return type(self) == type(other)
class MultipleSort(Sort):
"""Sort that encapsulates multiple sub-sorts.
"""
def __init__(self, sorts=None):
self.sorts = sorts or []
def add_sort(self, sort):
self.sorts.append(sort)
def _sql_sorts(self):
"""Return the list of sub-sorts for which we can be (at least
partially) fast.
A contiguous suffix of fast (SQL-capable) sub-sorts are
executable in SQL. The remaining, even if they are fast
independently, must be executed slowly.
"""
sql_sorts = []
for sort in reversed(self.sorts):
if not sort.order_clause() is None:
sql_sorts.append(sort)
else:
break
sql_sorts.reverse()
return sql_sorts
def order_clause(self):
order_strings = []
for sort in self._sql_sorts():
order = sort.order_clause()
order_strings.append(order)
return ", ".join(order_strings)
def is_slow(self):
for sort in self.sorts:
if sort.is_slow():
return True
return False
def sort(self, items):
slow_sorts = []
switch_slow = False
for sort in reversed(self.sorts):
if switch_slow:
slow_sorts.append(sort)
elif sort.order_clause() is None:
switch_slow = True
slow_sorts.append(sort)
else:
pass
for sort in slow_sorts:
items = sort.sort(items)
return items
def __repr__(self):
return f'MultipleSort({self.sorts!r})'
def __hash__(self):
return hash(tuple(self.sorts))
def __eq__(self, other):
return super().__eq__(other) and \
self.sorts == other.sorts
class FieldSort(Sort):
"""An abstract sort criterion that orders by a specific field (of
any kind).
"""
def __init__(self, field, ascending=True, case_insensitive=True):
self.field = field
self.ascending = ascending
self.case_insensitive = case_insensitive
def sort(self, objs):
# TODO: Conversion and null-detection here. In Python 3,
# comparisons with None fail. We should also support flexible
# attributes with different types without falling over.
def key(item):
field_val = item.get(self.field, '')
if self.case_insensitive and isinstance(field_val, str):
field_val = field_val.lower()
return field_val
return sorted(objs, key=key, reverse=not self.ascending)
def __repr__(self):
return '<{}: {}{}>'.format(
type(self).__name__,
self.field,
'+' if self.ascending else '-',
)
def __hash__(self):
return hash((self.field, self.ascending))
def __eq__(self, other):
return super().__eq__(other) and \
self.field == other.field and \
self.ascending == other.ascending
class FixedFieldSort(FieldSort):
"""Sort object to sort on a fixed field.
"""
def order_clause(self):
order = "ASC" if self.ascending else "DESC"
if self.case_insensitive:
field = '(CASE ' \
'WHEN TYPEOF({0})="text" THEN LOWER({0}) ' \
'WHEN TYPEOF({0})="blob" THEN LOWER({0}) ' \
'ELSE {0} END)'.format(self.field)
else:
field = self.field
return f"{field} {order}"
class SlowFieldSort(FieldSort):
"""A sort criterion by some model field other than a fixed field:
i.e., a computed or flexible field.
"""
def is_slow(self):
return True
class NullSort(Sort):
"""No sorting. Leave results unsorted."""
def sort(self, items):
return items
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
return False
def __eq__(self, other):
return type(self) == type(other) or other is None
def __hash__(self):
return 0
|
require_relative '../animation'
module NixonPi
module Animations
class <API key> < Animation
register :count_from_to, self
accepted_commands :start_value, :single_digit?
# TODO: unfinished and untested
def initialize(options = {})
super(options)
@options[:single_digit?] ||= true
from = @options[:start_value]
to = from
if @options[:single_digit?]
from.each_char { |f| to[i] = (f.to_i += 1).to_s }
from.reverse.each_char.with_index do |number|
@output << number
end
end
end
def write
<API key>(@output.shift)
end
end
end
end
|
FROM python:3
ADD ./simplesocial /simplesocial
WORKDIR /simplesocial
RUN pip install -r requirements.txt
EXPOSE 8000
CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000"]
|
layout: post
title: "Class Based Views"
date: 2013-05-13 07:04
tags: [python, django, yakindanegitim]
icons: [python]
Web development is a bit repetitive and web frameworks try to reduce this burden. One of the best features of Django for making object manipulation easier is class based views(CBV). We are usually good to go by only setting model in class based views and in the background, it handles all form processing.
There is also function based views(FBV) which have the same power and some more. I think, difference between them can be best explained by the analogy of C vs Python. Python is compact and writing Python is more fun. That's why it enables to do lots of work in a few lines. On the other hand, C is verbose and fast since there is no boilerplate and you directly do what you want but whenever you go off the standard lines and need some more control, you have to use C.
Even if CBVs get attention recently, FBVs aren't deprecated. Python gets traction but C is always [there](http:
CBVs enables to write more compact code as a result of more enjoyable reading, that is quite important for maintenance. Moreover, CBVs are better to write tests for. Therefore, we should stick to them when possible.
Mainly, CBVs have two disadvantages; namely, a very steep learning curve and the difficulty of handling multiple forms.
1- How is context data created? How is object retrieved? How is form validated? In FBVs, most of the time, we write these logic ourselves explicitly but in CBVs, we should aware of how and when our methods are called. Getting used to it takes some time but later, I think, CBV makes us more productive.
2- Even if inline formsets makes possible multi model form handling in CBVs, it is hard. It seems this is the only reason to use FBVs.
Now, I would like to show inline formset usage via CBVs with an example(adding album with songs):
Our models:
python
# models.py
from django.db import models
class Album(models.Model):
name = models.CharField(max_length=255)
class Song(models.Model):
name = models.CharField(max_length=255)
lyrics = models.TextField(blank=True, null=True)
album = models.ForeignKey(Album)
Our forms:
python
# forms.py
from django.forms import ModelForm
from django.forms.models import <API key>
from .models import Album, Song
class AlbumForm(ModelForm):
class Meta:
model = Album
AlbumSongFormSet = <API key>(Album, Song, form=AlbumForm, extra=3)
Our create view:
python
# views.py
from django.core.urlresolvers import reverse
from django.http import <API key>
from django.shortcuts import get_object_or_404
from django.views.generic import CreateView
from django.utils.text import slugify
from django.utils.translation import ugettext as _
from braces.views import LoginRequiredMixin
from core.mixins import ActionMixin
from .models import Album, Song
from .forms import AlbumForm
class AlbumCreateView(LoginRequiredMixin, ActionMixin, CreateView):
model = Album
form_class = AlbumForm
template_name = 'music/album_add.html'
action = _("Album is successfully added") # ActionMixin is written in an earlier post
def form_valid(self, form):
context = self.get_context_data()
albumsong_form = context['albumsong_formset']
if albumsong_form.is_valid():
self.object = form.save(commit=False) # to set extra attributes that doesn't come from form
self.object.artist = Artist.objects.get(<API key>=self.kwargs.get("username"))
self.object.slug = slugify(self.object.name)
self.object.save()
for song_form in albumsong_form:
song = song_form.save(commit=False)
song.slug = slugify(song.name)
song.album = self.object
song.save()
return <API key>(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(AlbumCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['albumsong_formset'] = AlbumSongFormSet(self.request.POST)
else:
context['albumsong_formset'] = AlbumSongFormSet()
return context
def get_success_url(self):
return reverse('artist_detail', kwargs=self.kwargs)
And finally, our urlconf:
python
# urls.py
from django.conf.urls import patterns, url
from .views import *
urlpatterns = patterns('',
url(r'^(?P<username>[-_\.\w]+)/add/$',
AlbumCreateView.as_view(), name="album_add"),
)
That's it!
|
local Swapout = require('sconce.Swapout')
return function(tester)
local suite = torch.TestSuite()
function suite.<API key>()
local swapout = Swapout.new(1.0)
local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}})
local expected = torch.Tensor{4, 4}
tester:eq(actual, expected)
end
function suite.<API key>()
local swapout = Swapout.new(0.0)
local actual = swapout:forward({torch.Tensor{1, 2}, torch.Tensor{3, 2}})
local expected = torch.Tensor{0, 0}
tester:eq(actual, expected)
end
function suite.<API key>()
torch.manualSeed(1234)
local swapout = Swapout.new(0.5)
local actual = swapout:forward({
torch.Tensor(4):fill(1), torch.Tensor(4):fill(2)
})
local expected = torch.Tensor{3, 1, 0, 0}
tester:eq(actual, expected)
end
tester:add(suite)
return suite
end
|
"use strict";
var http_1 = require("@angular/http");
var AppSettings = (function () {
function AppSettings() {
}
Object.defineProperty(AppSettings, "API_OPTIONS", {
get: function () {
var headers = new http_1.Headers({ 'Content-Type': 'application/json' }), options = new http_1.RequestOptions({ headers: headers });
return options;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "API_URL", {
get: function () {
var devMode = true, prodPath = "http://cristi.red:8080/api", apiSecured = false, apiHost = "localhost", apiPort = "8080/api";
return (devMode) ? ("http" + ((apiSecured) ? "s" : "") + "://" + apiHost + ":" + apiPort) : prodPath;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AppSettings, "SOCKETG_URL", {
get: function () {
var devMode = true, prodPath = "http:
return (devMode) ? local : prodPath;
},
enumerable: true,
configurable: true
});
return AppSettings;
}());
exports.AppSettings = AppSettings;
//# sourceMappingURL=app.settings.js.map
|
const fs = require('fs')
const path = require('path')
const {<API key>, getConfig} = require('./common')
const buildCache = {}
module.exports = (params) => {
const baseConfig = getConfig(params)
const config = Object.assign({}, baseConfig)
config.outputPath = path.join(__dirname, '../dist-' + config.app)
return {
entry: config.sourcePath + '/tools/initdb.js',
context: config.sourcePath,
target: 'node',
output: {
path: config.outputPath,
filename: 'initdb.js'
},
stats: {
colors: true,
reasons: true,
chunks: false
},
cache: buildCache,
module: {
rules: [<API key>({node: 'current'}, config)]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: baseConfig.aliases
},
devServer: {
contentBase: config.sourcePath
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using tomware.Microwf.Domain;
using tomware.Microwf.Infrastructure;
namespace tomware.Microwf.Engine
{
public interface <API key>
{
Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync();
Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync(PagingParameters parameters);
Task<PaginatedList<WorkItemViewModel>> GetFailedAsync(PagingParameters parameters);
Task Reschedule(WorkItemViewModel model);
}
public class <API key> : <API key>
{
private readonly IJobQueueService service;
private readonly IWorkItemService workItemService;
public <API key>(
IJobQueueService service,
IWorkItemService workItemService
)
{
this.service = service;
this.workItemService = workItemService;
}
public async Task<IEnumerable<WorkItemViewModel>> GetSnapshotAsync()
{
var result = this.service.GetSnapshot();
return await Task.FromResult(result.Select(x => ToViewModel(x)));
}
public async Task<PaginatedList<WorkItemViewModel>> GetUpCommingsAsync(
PagingParameters parameters
)
{
var result = await this.workItemService.GetUpCommingsAsync(parameters);
return new PaginatedList<WorkItemViewModel>(
result.Select(x => ToViewModel(x)),
result.AllItemsCount,
parameters.PageIndex,
parameters.PageSize
);
}
public async Task<PaginatedList<WorkItemViewModel>> GetFailedAsync(
PagingParameters parameters
)
{
var result = await this.workItemService.GetFailedAsync(parameters);
return new PaginatedList<WorkItemViewModel>(
result.Select(x => ToViewModel(x)),
result.AllItemsCount,
parameters.PageIndex,
parameters.PageSize
);
}
public async Task Reschedule(WorkItemViewModel model)
{
await this.workItemService.Reschedule(new Infrastructure.WorkItemDto
{
Id = model.Id,
DueDate = model.DueDate
});
}
private WorkItemViewModel ToViewModel(Domain.WorkItemDto dto)
{
return PropertyMapper<Domain.WorkItemDto, WorkItemViewModel>.From(dto);
// return new WorkItemViewModel
// Id = dto.Id,
// TriggerName = dto.TriggerName,
// EntityId = dto.EntityId,
// WorkflowType = dto.WorkflowType,
// Retries = dto.Retries,
// Error = dto.Error,
// DueDate = dto.DueDate
}
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.c
Label Definition File: <API key>.strings.label.xml
Template File: sources-sink-18.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sink: w32spawnl
* BadSink : execute command with wspawnl
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#include <process.h>
#ifndef OMITBAD
void <API key>()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
goto source;
source:
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
/* wspawnl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
goto source;
source:
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
/* wspawnl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_wspawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL);
}
void <API key>()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
<API key>();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
<API key>();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 200);
$table->string('provider');
$table->string('provider_id');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
|
<html><body>
<h4>Windows 10 x64 (19041.208) 2004</h4><br>
<h2><API key></h2>
<font face="arial"> +0x000 Key : Uint4B<br>
+0x000 <API key> : Pos 0, 16 Bits<br>
+0x000 LargePageCost : Pos 16, 8 Bits<br>
+0x000 UnitCount : Pos 24, 8 Bits<br>
</font></body></html>
|
<?php
namespace RDF\<API key>\Type;
/**
*
*
* @author Richard Fullmer <richardfullmer@gmail.com>
*/
class CMYKColor
{
/**
* @var float
*/
protected $cyan;
/**
* @var float
*/
protected $magenta;
/**
* @var float
*/
protected $yellow;
/**
* @var float
*/
protected $black;
/**
* @param float $cyan
* @param float $magenta
* @param float $yellow
* @param float $black
*/
public function __construct($cyan, $magenta, $yellow, $black)
{
$this->cyan = (float) $cyan;
$this->magenta = (float) $magenta;
$this->yellow = (float) $yellow;
$this->black = (float) $black;
}
/**
* @param float $black
*/
public function setBlack($black)
{
$this->black = (float) $black;
}
/**
* @return float
*/
public function getBlack()
{
return $this->black;
}
/**
* @param float $cyan
*/
public function setCyan($cyan)
{
$this->cyan = (float) $cyan;
}
/**
* @return float
*/
public function getCyan()
{
return $this->cyan;
}
/**
* @param float $magenta
*/
public function setMagenta($magenta)
{
$this->magenta = (float) $magenta;
}
/**
* @return float
*/
public function getMagenta()
{
return $this->magenta;
}
/**
* @param float $yellow
*/
public function setYellow($yellow)
{
$this->yellow = (float) $yellow;
}
/**
* @return float
*/
public function getYellow()
{
return $this->yellow;
}
}
|
<html>
<head>
<title> Install SEO Commerce</title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<style>
#container {
margin:auto;
}
label, input {
display: block;
}
</style>
</head>
<body>
<div class="container">
<form action="pasang_p.php" method="POST">
<label> Nama Situs </label>
<input type="text" name="s_name">
<label> Author (Nama Pemilik) </label>
<input type="text" name="s_author">
<label> Username </label>
<input type="text" name="a_username">
<label> Password </label>
<input type="password" name="a_password">
<input type="submit" value="kirim">
</form>
</div>
</body>
<html>
|
{{ define "main" }}
<!-- Header -->
{{ partial "header" . }}
<div class="container">
<section id="projects">
<h4 class="my-5">{{ .Site.Data.projects.name }}</h4>
<div class="panel">
<div class="panel-body">
{{ range $el := .Site.Data.projects.source }}
<h5>
<i class="{{ .icon }}"></i>
<b><a href="{{ .url }}">{{ $el.name }}</a></b> - {{ $el.description }}
</h5>
{{ end }}
</div>
</div>
</section>
</div>
{{ end }}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DebtSnowBall2017
{
class LoanList
{
private List<Loan> loanList;
public LoanList()
{
this.loanList = new List<Loan>();
}
public void addLoan(Loan newLoan)
{
this.loanList.Add(newLoan);
this.loanList.Sort(delegate(Loan L1, Loan L2){ return L1.getTotalOwed().CompareTo(L2.getTotalOwed()); });
}
public void printToScreen(TableLayoutPanel panel)
{
panel.Controls.Clear();
foreach(Loan loan in loanList)
{
Label principle = new Label();
principle.Text = Convert.ToString(loan.getPrinciple());
panel.Controls.Add(principle);
Label interest = new Label();
interest.Text = Convert.ToString(loan.getInterest() * 100) + "%";
panel.Controls.Add(interest);
Label monthsToPay = new Label();
if (loan.getMonthsToPay() <= 0)
{
monthsToPay.Text = "Not Yet Calculated";
}
else
{
monthsToPay.Text = Convert.ToString(loan.getMonthsToPay());
}
panel.Controls.Add(monthsToPay);
Label totalPaid = new Label();
if (loan.getTotalPaid() < 0)
{
totalPaid.Text = "Not Yet Calculated";
}
else
{
totalPaid.Text = Convert.ToString(loan.getTotalPaid());
}
panel.Controls.Add(totalPaid);
}
}
public bool allPaid()
{
foreach(Loan loan in loanList)
{
if (!loan.isFullyPaid())
{
return false;
}
}
return true;
}
public void calculate(double salary)
{
while (!allPaid())
{
double thisMonthsSalary = salary;
foreach (Loan nextLoan in this.loanList)
{
thisMonthsSalary = nextLoan.payMonthlyBill(thisMonthsSalary);
}
foreach (Loan nextLoan in this.loanList)
{
if (!nextLoan.isFullyPaid())
{
nextLoan.payExtra(thisMonthsSalary);
break;
}
}
}
}
}
}
|
package render
import (
"github.com/gin-gonic/gin"
)
func Error(c *gin.Context, msg string) {
String(c, msg, 400)
}
|
#include "glut_viewer_gui.h"
#include <GLsdk/gl_stuff.h>
#include <GL/glut.h>
#include <iostream>
#include <stdarg.h>
#include <math.h>
#include <stdio.h>
namespace GlutViewerGUI {
static void printf_xy(GLfloat x, GLfloat y, const char *format, ...) {
va_list args;
char buffer[1024], *p;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
glPushMatrix();
glTranslatef(x, y, 0);
for (p = buffer; *p; p++) {
glutStrokeCharacter(<API key>, *p);
}
glPopMatrix();
}
static void circle_arc_vertices(
GLfloat x, GLfloat y, GLfloat r1, GLfloat r2, GLfloat theta1, GLfloat theta2
) {
const GLfloat delta_theta = 1.0f ;
if(theta2 > theta1) {
for(GLfloat theta = theta1; theta <= theta2; theta += delta_theta) {
GLfloat theta_rad = theta * 3.14159f / 200.0f ;
glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ;
}
} else {
for(GLfloat theta = theta1; theta >= theta2; theta -= delta_theta) {
GLfloat theta_rad = theta * 3.14159f / 200.0f ;
glVertex2f(x + r1 * cos(theta_rad), y + r2 * sin(theta_rad)) ;
}
}
}
static void circle_arc_vertices(
GLfloat x, GLfloat y, GLfloat r, GLfloat theta1, GLfloat theta2
) {
circle_arc_vertices(x,y,r,r,theta1,theta2) ;
}
static void circle(GLfloat x, GLfloat y, GLfloat r) {
glBegin(GL_LINE_LOOP) ;
circle_arc_vertices(x,y,r,0.0f,400.0f) ;
glEnd() ;
}
static void fill_circle(GLfloat x, GLfloat y, GLfloat r) {
glBegin(GL_POLYGON) ;
circle_arc_vertices(x,y,r,0.0f,400.0f) ;
glEnd() ;
}
static void <API key>(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r
) {
glVertex2f(x1+r,y2) ;
glVertex2f(x2-r,y2) ;
circle_arc_vertices(x2-r, y2-r, r, 100.0f, 0.0f) ;
glVertex2f(x2,y2-r) ;
glVertex2f(x2,y1+r) ;
circle_arc_vertices(x2-r, y1+r, r, 0.0f, -100.0f) ;
glVertex2f(x2-r,y1) ;
glVertex2f(x1+r,y1) ;
circle_arc_vertices(x1+r, y1+r, r, -100.0f, -200.0f) ;
glVertex2f(x1,y1+r) ;
glVertex2f(x1,y2-r) ;
circle_arc_vertices(x1+r, y2-r, r, -200.0f, -300.0f) ;
}
static void round_rectangle(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) {
glBegin(GL_LINE_LOOP) ;
<API key>(x1, y1, x2, y2, r) ;
glEnd() ;
}
static void <API key>(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLfloat r) {
glBegin(GL_POLYGON) ;
<API key>(x1, y1, x2, y2, r) ;
glEnd() ;
}
static void arrow_vertices(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
GLfloat x12 = 0.5 * (x1 + x2) ;
GLfloat y12 = 0.5 * (y1 + y2) ;
switch(dir) {
case DOWN:
glVertex2f(x1,y2) ;
glVertex2f(x2,y2) ;
glVertex2f(x12,y1) ;
break ;
case UP:
glVertex2f(x1,y1) ;
glVertex2f(x2,y1) ;
glVertex2f(x12,y2) ;
break ;
case LEFT:
glVertex2f(x2,y2) ;
glVertex2f(x2,y1) ;
glVertex2f(x1,y12) ;
break ;
case RIGHT:
glVertex2f(x1,y2) ;
glVertex2f(x1,y1) ;
glVertex2f(x2,y12) ;
break ;
}
}
static void arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
glBegin(GL_LINE_LOOP) ;
arrow_vertices(dir, x1, y1, x2, y2) ;
glEnd() ;
}
static void fill_arrow(Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2) {
glBegin(GL_POLYGON) ;
arrow_vertices(dir, x1, y1, x2, y2) ;
glEnd() ;
}
Widget::Widget(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2
) : style_(BlueStyle), visible_(true), highlight_(false) {
set_geometry(x1, y1, x2, y2) ;
r_ = 100.0f ;
}
Widget::~Widget() {
}
void Widget::glColor(ColorRole role_in) {
ColorRole role = role_in ;
if(highlight_) {
switch(role_in) {
case Background:
role = Foreground ; break ;
case Middleground:
role = Middleground ; break ;
case Foreground:
role = Foreground ; break ;
}
}
switch(style_) {
case RedStyle: {
switch(role) {
case Background:
glColor4f(0.5f, 0.0f, 0.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(1.0f, 0.5f, 0.5f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case GreenStyle: {
switch(role) {
case Background:
glColor4f(0.0f, 0.5f, 0.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.5f, 1.0f, 0.5f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case BlueStyle: {
switch(role) {
case Background:
glColor4f(0.0f, 0.0f, 0.5f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.5f, 0.5f, 1.0f, 1.0f) ;
break ;
case Foreground:
glColor4f(5.0f, 5.0f, 5.0f, 1.0f) ;
break ;
}
} break ;
case BWStyle: {
switch(role) {
case Background:
glColor4f(5.0f, 5.0f, 5.0f, 0.5f) ;
break ;
case Middleground:
glColor4f(0.2f, 0.2f, 0.2f, 1.0f) ;
break ;
case Foreground:
glColor4f(0.0f, 0.0f, 0.0f, 1.0f) ;
break ;
}
} break ;
}
}
GLboolean Widget::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
return contains(int(x),int(y)) ;
}
void Widget::draw() {
if(!visible()) { return ; }
draw_background() ;
draw_border() ;
}
void Widget::draw_background() {
glEnable(GL_BLEND) ;
glBlendFunc(GL_SRC_ALPHA, <API key>) ;
glColor(Background) ;
<API key>(x1_, y1_, x2_, y2_, r_) ;
glDisable(GL_BLEND) ;
}
void Widget::draw_border() {
glColor(Foreground) ;
glLineWidth(2.0) ;
round_rectangle(x1_, y1_, x2_, y2_, r_) ;
}
Container* Container::main_widget_ = NULL ;
Container::~Container() {
if(main_widget_ == this) {
main_widget_ = NULL ;
}
for(size_t i=0; i<children_.size(); i++) {
delete children_[i] ;
}
}
void Container::draw() {
if(!visible()) {
return ;
}
for(size_t i=0; i<children_.size(); i++) {
children_[i]->draw() ;
}
}
GLboolean Container::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) { return GL_FALSE ; }
switch(event) {
case GLUT_VIEWER_DOWN: {
for(size_t i=0; i<children_.size(); i++) {
if(children_[i]->contains(x,y) && children_[i]->process_mouse_event(x, y, button, event)) {
active_child_ = children_[i] ;
return GL_TRUE ;
}
}
} break ;
case GLUT_VIEWER_MOVE: {
if(active_child_ != NULL) {
return active_child_->process_mouse_event(x, y, button, event) ;
}
} break ;
case GLUT_VIEWER_UP: {
if(active_child_ != NULL) {
Widget* w = active_child_ ;
active_child_ = NULL ;
return w->process_mouse_event(x, y, button, event) ;
}
} break ;
}
return GL_FALSE ;
}
void Container::draw_handler() {
if(main_widget_ != NULL) {
main_widget_->draw() ;
}
}
GLboolean Container::mouse_handler(float x, float y, int button, enum GlutViewerEvent event) {
if(main_widget_ != NULL) {
return main_widget_->process_mouse_event(x, y, button, event) ;
}
return GL_FALSE ;
}
void Container::set_as_main_widget() {
main_widget_ = this ;
<API key>(draw_handler) ;
<API key>(mouse_handler) ;
}
void Panel::draw() {
Widget::draw() ;
Container::draw() ;
}
GLboolean Panel::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible() || !contains(x,y)) {
return GL_FALSE ;
}
return Container::process_mouse_event(x,y,button,event) ;
}
void Button::draw() {
Widget::draw() ;
}
GLboolean Button::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(visible() && contains(x,y) && event == GLUT_VIEWER_DOWN) {
pressed() ;
highlight_ = GL_TRUE ;
return GL_TRUE ;
}
if(visible() && contains(x,y) && event == GLUT_VIEWER_UP) {
highlight_ = GL_FALSE ;
return GL_TRUE ;
}
return GL_FALSE ;
}
void Button::pressed() {
if(callback_ != NULL) {
callback_(client_data_) ;
}
}
void Checkbox::draw() {
if(!visible()) { return ; }
Button::draw() ;
glColor(Foreground) ;
GLfloat x = 0.5f * (x1_ + x2_) ;
GLfloat y = 0.5f * (y1_ + y2_) ;
if(toggle_) {
glColor(Middleground) ;
fill_circle(x,y,d_) ;
glColor(Foreground) ;
glLineWidth(1.0f) ;
circle(x,y,d_) ;
}
}
void Checkbox::pressed() {
toggle_ = !toggle_ ;
}
ArrowButton::ArrowButton(
Direction dir, GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2
) : Button(x1, y1, x2, y2), direction_(dir) {
d_ /= 1.5 ;
r_ /= 2.0 ;
}
void ArrowButton::draw() {
Button::draw() ;
glColor(Middleground) ;
fill_arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ;
glColor(Foreground);
arrow(direction_, x1_ + d_, y1_ + d_, x2_ - d_, y2_ - d_) ;
}
void Slider::set_value(GLfloat x, bool update) {
if(integer_) { x = GLfloat(GLint(x)) ; }
if(x < min_) { x = min_ ; }
if(x > max_) { x = max_ ; }
value_ = x ;
if(update && callback_ != NULL) { callback_(value_) ; }
}
void Slider::set_range(GLfloat x1, GLfloat x2) {
min_ = x1 ;
max_ = x2 ;
if(value_ < min_) { set_value(min_) ; }
if(value_ > max_) { set_value(max_) ; }
}
void Slider::draw() {
if(!visible()) { return ; }
Widget::draw() ;
glColor(Middleground) ;
glLineWidth(2.0f) ;
glBegin(GL_LINES) ;
glVertex2f(x1_+d_, 0.5f*(y1_+y2_)) ;
glVertex2f(x2_-d_, 0.5f*(y1_+y2_)) ;
glEnd() ;
GLfloat w = (value_ - min_) / (max_ - min_) ;
GLfloat x = w*(x2_ - d_) + (1.0f - w)*(x1_ + d_) ;
GLfloat y = 0.5f*(y1_+y2_) ;
glColor(Middleground) ;
fill_circle(x,y,d_) ;
glColor(Foreground) ;
glLineWidth(1.0f) ;
circle(x,y,d_) ;
}
GLboolean Slider::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) { return GL_FALSE ; }
if(event == GLUT_VIEWER_DOWN || event == GLUT_VIEWER_MOVE) {
GLfloat w = GLfloat(x - x1_ - d_) / GLfloat(x2_ - x1_ - 2.0f * d_) ;
set_value((1.0f - w) * min_ + w * max_, continuous_update_ == GL_TRUE) ;
return GL_TRUE ;
} else if(event == GLUT_VIEWER_UP) {
set_value(value_) ;
}
return GL_FALSE ;
}
void CurveEditor::draw() {
if(!visible()) { return ; }
draw_background() ;
// Draw grid
glColor(Middleground) ;
glLineWidth(1.0) ;
glBegin(GL_LINES) ;
for(unsigned int i=1; i<10; i++) {
float x = x1_ + (x2_ - x1_) * float(i) / 10.0f ;
glVertex2f(x, y1_) ;
glVertex2f(x, y2_) ;
}
for(unsigned int i=1; i<4; i++) {
float y = y1_ + (y2_ - y1_) * float(i) / 4.0f ;
glVertex2f(x1_, y) ;
glVertex2f(x2_, y) ;
}
glEnd() ;
// Draw curve
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_STRIP) ;
for(unsigned int i=0; i<CurveSize; i++) {
glVertex2f(
x1_ + (float)i * (x2_ - x1_) / (float)(CurveSize - 1),
y1_ + curve_[i] * (y2_ - y1_)
) ;
}
glEnd() ;
draw_border() ;
}
GLboolean CurveEditor::process_mouse_event(float x, float y, int button, GlutViewerEvent event) {
if(!visible()) {
return GL_FALSE ;
}
if(event == GLUT_VIEWER_DOWN && !contains(x,y)) {
return GL_FALSE ;
}
int i = int((x - x1_) * (CurveSize - 1) / (x2_ - x1_)) ;
GLfloat v = GLfloat(y - y1_) / GLfloat(y2_ - y1_) ;
if(v < 0.0) { v = 0.0 ; }
if(v > 1.0) { v = 1.0 ; }
if(i < 0) { i = 0 ; }
if(i >= CurveSize) { i = CurveSize - 1 ; }
if(event == GLUT_VIEWER_DOWN) {
last_i_ = i ;
last_v_ = v ;
return GL_TRUE ;
}
if(event == GLUT_VIEWER_UP) {
if(callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
return GL_TRUE ;
}
if(event == GLUT_VIEWER_MOVE) {
if(i > last_i_) {
set_curve(last_i_, last_v_, i, v) ;
} else {
set_curve(i, v, last_i_, last_v_) ;
}
}
last_i_ = i ;
last_v_ = v ;
return GL_TRUE ;
}
void CurveEditor::set_curve(int i1, float val1, int i2, float val2) {
if(i1 == i2) {
curve_[i1] = val1 ;
} else {
for(int i=i1; i<=i2; i++) {
curve_[i] = val1 + (float)(i - i1) * (val2 - val1) / (float)(i2 - i1) ;
}
}
}
void CurveEditor::set_curve(GLfloat* curve, bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = curve[i] ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
void CurveEditor::reset(bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = 0.5f ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
void CurveEditor::reset_ramp(bool update) {
for(unsigned int i=0; i<CurveSize; i++) {
curve_[i] = float(i) / float(CurveSize - 1) ;
}
if(update && callback_ != NULL) {
callback_(curve_, CurveSize) ;
}
}
GLfloat CurveEditor::value(GLfloat x) const {
if(x < 0.0f) { x = 0.0f ; }
if(x > 1.0f) { x = 1.0f ; }
return curve_[int(x * (CurveSize - 1))] ;
}
void ColormapEditor::draw() {
if(!visible()) { return ; }
draw_background() ;
// Draw curve
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_STRIP) ;
for(unsigned int i=0; i<ColormapSize; i++) {
glVertex2f(
x1_ + (float)i * (x2_ - x1_) / (float)(ColormapSize - 1),
y1_ + curve()[i] * (y2_ - y1_)
) ;
}
glEnd() ;
draw_border() ;
}
void ColormapEditor::draw_background() {
glEnable(GL_BLEND) ;
glBlendFunc(GL_SRC_ALPHA, <API key>) ;
drawBackgroundCB_(curve(), ColormapSize) ;
glDisable(GL_BLEND) ;
}
void ColormapEditor::draw_border() {
glColor(Foreground) ;
glLineWidth(2.0) ;
glBegin(GL_LINE_LOOP) ;
glVertex2f(x1_, y1_) ;
glVertex2f(x1_, y2_) ;
glVertex2f(x2_, y2_) ;
glVertex2f(x2_, y1_) ;
glEnd() ;
}
void ColormapEditor::update(unsigned char* cmap_data, int size, int component) {
for(unsigned int i = 0; i < ColormapSize; ++i) {
int idx = (double(i) / double(ColormapSize)) * (size-1) ;
curve()[i] = double(cmap_data[4*idx + component]) / 255.0 ;
}
}
void TextLabel::draw() {
if(!visible()) { return ; }
glLineWidth(textwidth_) ;
printf_xy(x1_+10, y1_+50, (char*)text_.c_str()) ;
}
Spinbox::Spinbox(
GLfloat x, GLfloat y, GLenum& value, const std::vector<std::string>& labels
) : Container(x, y, x+3000, y+170), value_(value), labels_(labels) {
down_ = new ArrowButton(DOWN, x, y, x+170, y+170) ;
up_ = new ArrowButton(UP, x+200, y, x+370, y+170) ;
up_->set_callback(increment_CB, this) ;
down_->set_callback(decrement_CB, this) ;
if(value_ < 0) { value_ = 0 ; }
if(value_ >= int(labels_.size())) { value_ = (GLenum)(labels_.size() - 1) ; }
text_ = new TextLabel(x+450,y,labels_[value_]) ;
add_child(up_) ;
add_child(down_) ;
add_child(text_) ;
show() ;
}
void Spinbox::draw() {
Container::draw() ;
}
void Spinbox::increment() {
value_++ ;
if(value_ >= labels_.size()) { value_ = 0 ; }
text_->set_text(labels_[value_]) ;
}
void Spinbox::decrement() {
if(int(value_) - 1 < 0) {
value_ = (GLenum)(labels_.size() - 1) ;
} else {
value_
}
text_->set_text(labels_[value_]) ;
}
void Spinbox::increment_CB(void* spinbox) {
static_cast<Spinbox*>(spinbox)->increment() ;
}
void Spinbox::decrement_CB(void* spinbox) {
static_cast<Spinbox*>(spinbox)->decrement() ;
}
void MessageBox::draw() {
if(!visible()) { return ; }
Panel::draw() ;
glLineWidth(2) ;
for(unsigned int i=0; i<message_.size(); i++) {
printf_xy(x1_+100, y2_-200-i*150, (char*)message_[i].c_str()) ;
}
}
PropertyPage::PropertyPage(
GLfloat x_in, GLfloat y_in, const std::string& caption
) : Panel(x_in,y_in-10,x_in+Width,y_in) {
y_ = y2_ - 200 ;
x_caption_ = x1_ + 100 ;
x_widget_ = x1_ + 1300 ;
caption_ = add_separator(caption) ;
y1_ = y_ ;
}
TextLabel* PropertyPage::add_separator(const std::string& text) {
TextLabel* w = new TextLabel(x1_ + 400, y_, text, 2.0f) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
TextLabel* PropertyPage::add_string(const std::string& text) {
TextLabel* w = new TextLabel(x1_ + 200, y_, text, 1.0f) ;
add_child(w) ;
y_ -= 150 ;
y1_ = y_ ;
return w ;
}
Slider* PropertyPage::add_slider(
const std::string& caption, GLfloat& value, GLfloat vmin, GLfloat vmax
) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Slider* w = new Slider(x_widget_, y_, x_widget_+800, y_+200, value) ;
w->set_range(vmin, vmax) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
Checkbox* PropertyPage::add_toggle(
const std::string& caption, GLboolean& value
) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Checkbox* w = new Checkbox(x_widget_, y_, x_widget_+200, y_+200, value) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
Spinbox* PropertyPage::add_enum(
const std::string& caption, GLenum& value, const std::vector<std::string>& labels) {
add_child(new TextLabel(x_caption_, y_, caption)) ;
Spinbox* w = new Spinbox(x_widget_, y_, value, labels) ;
add_child(w) ;
y_ -= 250 ;
y1_ = y_ ;
return w ;
}
ViewerProperties::ViewerProperties(GLfloat x_left, GLfloat y_top) : PropertyPage(
x_left, y_top, "Viewer"
) {
add_toggle("Rot. light", *<API key>(<API key>)) ;
if(<API key>(GLUT_VIEWER_HDR)) {
add_slider("Exposure", *<API key>(<API key>), 0.001, 3.0) ;
add_slider("Gamma", *<API key>(<API key>), 0.2, 1.5) ;
add_toggle("Vignette", *<API key>(<API key>)) ;
add_slider("Blur amount", *<API key>(<API key>)) ;
add_slider("Blur width", *<API key>(<API key>), 1.0, 20.0) ;
add_toggle("UnMsk.", *<API key>(<API key>)) ;
add_toggle("UnMsk.+", *<API key>(<API key>)) ;
add_slider("UnMsk. Gamm", *<API key>(<API key>), 0.2, 1.5) ;
}
}
void ViewerProperties::draw() {
if(<API key>(<API key>)) {
static char buff[256] ;
sprintf(buff, " [%4d FPS]", glut_viewer_fps()) ;
caption_->set_text("Viewer" + std::string(buff)) ;
} else {
caption_->set_text("Viewer") ;
}
PropertyPage::draw() ;
}
void ViewerProperties::apply() {
}
Image::Image(
GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2, GLint texture, GLint target
) : Widget(x1, y1, x2, y2), texture_(texture), texture_target_(target) {
}
void Image::draw() {
if(texture_ == 0) { return ; }
glEnable(texture_target_) ;
glBindTexture(texture_target_, texture_) ;
glBegin(GL_QUADS) ;
glTexCoord2f(0.0, 0.0) ;
glVertex2f(x1_, y1_) ;
glTexCoord2f(1.0, 0.0) ;
glVertex2f(x2_, y1_) ;
glTexCoord2f(1.0, 1.0) ;
glVertex2f(x2_, y2_) ;
glTexCoord2f(0.0, 1.0) ;
glVertex2f(x1_, y2_) ;
glEnd() ;
glDisable(texture_target_) ;
}
}
|
<?php
/**
* Description of aSites
*
* @author almaz
*/
class aSitesUsers extends Action {
protected $defaultAct = 'List';
protected function configure() {
require_once $this->module->pathModels . 'as_Sites.php';
require_once $this->module->pathModels . 'as_SitesUsers.php';
$authModule = General::$loadedModules['Auth'];
require_once $authModule->pathModels . 'au_Users.php';
}
public function act_List() {
if ($this->request->isAjax()) {
$this->context->setTopTpl('html_list');
} else {
$this->_parent();
$this->context->setTpl('content', 'html_list');
}
$sql = Stmt::prepare2(as_Stmt::<API key>, array('user_id' => $this->userInfo['user']['id']));
$tbl = new oTable(DBExt::selectToTable($sql));
$tbl->setIsDel();
$tbl->setIsEdit();
$tbl->setNamesColumns(array('host'=>'Сайт'));
$tbl->addRulesView('password', '******');
$tbl->sort(Navigation::get('field'), Navigation::get('order'));
$this->context->set('tbl', $tbl);
$this->context->set('h1', 'Мои сайты');
}
public function act_Add() {
if ($this->request->isAjax()) {
$this->context->setTopTpl('site_add_html');
} else {
$this->_parent();
$this->context->setTpl('content', 'site_add_html');
}
$sqlSites = Stmt::prepare2(as_Stmt::ALL_SITES, array(), array (Stmt::ORDER => 'sort'));
$listSites = new oList(DBExt::selectToList($sqlSites));
$fields['site_id'] = array('title' => 'Сайт', 'value' => '', 'data' => $listSites, 'type'=>'select', 'required' => true, 'validator' => null, 'info'=>'Список поддерживаемых на данный момент сайтов', 'error' => false, 'attr' => '', $checked = array());
$fields['login'] = array('title' => 'Логин', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array());
$fields['password'] = array('title' => 'Пароль', 'value'=>'', 'type'=>'text', 'required' => true, 'validator' => null, 'info'=>'', 'error' => false, 'attr' => '', $checked = array());
$form = new oForm($fields);
$this->context->set('form', $form);
$this->context->set('info_text', 'Добавление настроек для нового сайта...');
if ($this->request->is('POST')) {
$form->fill($this->request->get('POST'));
if ($form->isComplited()) {
$siteUser = new as_SitesUsers();
$siteUser->site_id = $form->getFieldValue('site_id');
$siteUser->login = $form->getFieldValue('login');
$siteUser->password = $form->getFieldValue('password');
$siteUser->user_id = $this->userInfo['user']['id'];
$siteUser->save();
$this->context->del('form');
$this->context->set('info_text', 'Настройки добавлены');
}
}
}
function act_Del () {
$id = (int)$this->request->get('id', 0);
$sqlSites = Stmt::prepare2(as_Stmt::DEL_SITE_USER, array('user_id' => $this->userInfo['user']['id'], 'site_id' => $id));
DB::execute($prepare_stmt);
$sql = Stmt::prepare(se_Stmt::IS_KEYWORDS_SET, array('set_id' => $id, Stmt::LIMIT => 1));
$sitesUsers = new as_SitesUsers((int)$this->request->get('id'));
$sets->delete();
$iRoute = new InternalRoute();
$iRoute->module = 'SEParsing';
$iRoute->action = 'Sets';
$actR = new ActionResolver();
$act = $actR->getInternalAction($iRoute);
$act->runAct();
}
function _parent(InternalRoute $iRoute = null) {
$this->context->set('title', 'Сайты');
if (!$iRoute) {
$iRoute = new InternalRoute();
$iRoute->module = 'Pages';
$iRoute->action = 'Pages';
}
$actR = new ActionResolver();
$act = $actR->getInternalAction($iRoute);
$act->runParentAct();
}
}
|
package cz.muni.fi.pa165.mushrooms.service.exceptions;
/**
* @author bkompis
*/
public class <API key> extends <API key> {
public <T> <API key>(String what, String operation, T entity, Throwable e) {
super("Could not " + operation + " " + what + " (" + entity + ").", e);
}
public <API key>(String msg) {
super(msg);
}
public <API key>(String msg, Throwable cause) {
super(msg, cause);
}
}
|
#!/usr/bin/env python
import subprocess
import praw
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringIO
from base64 import b64encode
from base64 import b64decode
from ConfigParser import ConfigParser
import OAuth2Util
import os
import markdown
import bleach
# encoding=utf8
import sys
from <API key> import <API key>
reload(sys)
sys.setdefaultencoding('utf8')
# Edit Me!
# Each day after you post a signup post, copy its 6-character ID to this array.
<API key> = [ '7zrrj1', '7zxkpq', '8055hn', '80ddrf', '80nbm1', '80waq3' ]
flaskport = 8993
app = Flask(__name__)
app.debug = True
<API key> = {}
def <API key>():
config = ConfigParser()
config.read("../<API key>.cfg")
user = config.get("Reddit", "user")
password = config.get("Reddit", "password")
# TODO: password auth is going away, and we will soon need to do oauth.
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
redditSession.login(user, password, disable_warning=True)
# submissions = redditSession.get_subreddit('pornfree').get_hot(limit=5)
# print [str(x) for x in submissions]
return redditSession
def loginO<API key>():
redditSession = praw.Reddit(user_agent='Test Script by /u/foobarbazblarg')
# New version of praw does not require explicit use of the OAuth2Util object. Presumably because reddit now REQUIRES oauth.
# o = OAuth2Util.OAuth2Util(redditSession, print_log=True, configfile="../<API key>.cfg")
# TODO: Testing comment of refresh. We authenticate fresh every time, so presumably no need to do o.refresh().
# o.refresh(force=True)
return redditSession
def <API key>(redditSession):
# submissions = [redditSession.get_submission(submission_id=submissionId) for submissionId in <API key>]
submissions = [redditSession.submission(id=submissionId) for submissionId in <API key>]
for submission in submissions:
submission.comments.replace_more(limit=None)
# submission.<API key>(limit=None, threshold=0)
return submissions
def <API key>(submissions):
comments = []
for submission in submissions:
commentForest = submission.comments
comments += [comment for comment in commentForest.list() if comment.__class__ == praw.models.Comment]
return comments
def retireCommentHash(commentHash):
with open("<API key>.txt", "a") as commentHashFile:
commentHashFile.write(commentHash + '\n')
def <API key>():
with open("<API key>.txt", "r") as commentHashFile:
# return commentHashFile.readlines()
return commentHashFile.read().splitlines()
@app.route('/moderatesignups.html')
def moderatesignups():
global <API key>
<API key> = {}
stringio = StringIO()
stringio.write('<html>\n<head>\n</head>\n\n')
# redditSession = <API key>()
redditSession = loginO<API key>()
submissions = <API key>(redditSession)
flat_comments = <API key>(submissions)
retiredHashes = <API key>()
i = 1
stringio.write('<iframe name="invisibleiframe" style="display:none;"></iframe>\n')
stringio.write("<h3>")
stringio.write(os.getcwd())
stringio.write("<br>\n")
for submission in submissions:
stringio.write(submission.title)
stringio.write("<br>\n")
stringio.write("</h3>\n\n")
stringio.write('<form action="<API key>.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" value="Copy <API key>.py stdout to clipboard">')
stringio.write('</form>')
for comment in flat_comments:
# print comment.is_root
# print comment.score
i += 1
commentHash = sha1()
commentHash.update(comment.fullname)
commentHash.update(comment.body.encode('utf-8'))
commentHash = commentHash.hexdigest()
if commentHash not in retiredHashes:
<API key>[commentHash] = comment
authorName = str(comment.author) # can be None if author was deleted. So check for that and skip if it's None.
stringio.write("<hr>\n")
stringio.write('<font color="blue"><b>')
stringio.write(authorName) # can be None if author was deleted. So check for that and skip if it's None.
stringio.write('</b></font><br>')
if <API key>().hasParticipantNamed(authorName):
stringio.write(' <small><font color="green">(member)</font></small>')
# if <API key>().participantNamed(authorName).isStillIn:
# stringio.write(' <small><font color="green">(in)</font></small>')
# else:
# stringio.write(' <small><font color="red">(out)</font></small>')
else:
stringio.write(' <small><font color="red">(not a member)</font></small>')
stringio.write('<form action="takeaction.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" name="actiontotake" value="Signup" style="color:white;background-color:green">')
# stringio.write('<input type="submit" name="actiontotake" value="Signup and checkin">')
# stringio.write('<input type="submit" name="actiontotake" value="Relapse">')
# stringio.write('<input type="submit" name="actiontotake" value="Reinstate">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment">')
stringio.write('<input type="submit" name="actiontotake" value="Skip comment and don\'t upvote">')
stringio.write('<input type="hidden" name="username" value="' + b64encode(authorName) + '">')
stringio.write('<input type="hidden" name="commenthash" value="' + commentHash + '">')
# stringio.write('<input type="hidden" name="commentpermalink" value="' + comment.permalink + '">')
stringio.write('</form>')
stringio.write(bleach.clean(markdown.markdown(comment.body.encode('utf-8')), tags=['p']))
stringio.write("\n<br><br>\n\n")
stringio.write('</html>')
pageString = stringio.getvalue()
stringio.close()
return Response(pageString, mimetype='text/html')
@app.route('/takeaction.html', methods=["POST"])
def takeaction():
username = b64decode(request.form["username"])
commentHash = str(request.form["commenthash"])
# commentPermalink = request.form["commentpermalink"]
actionToTake = request.form["actiontotake"]
# print <API key>
comment = <API key>[commentHash]
# print "comment: " + str(comment)
if actionToTake == 'Signup':
print "signup - " + username
subprocess.call(['./signup.py', username])
comment.upvote()
retireCommentHash(commentHash)
# if actionToTake == 'Signup and checkin':
# print "signup and checkin - " + username
# subprocess.call(['./signup-and-checkin.sh', username])
# comment.upvote()
# retireCommentHash(commentHash)
# elif actionToTake == 'Relapse':
# print "relapse - " + username
# subprocess.call(['./relapse.py', username])
# comment.upvote()
# retireCommentHash(commentHash)
# elif actionToTake == 'Reinstate':
# print "reinstate - " + username
# subprocess.call(['./reinstate.py', username])
# comment.upvote()
# retireCommentHash(commentHash)
elif actionToTake == 'Skip comment':
print "Skip comment - " + username
comment.upvote()
retireCommentHash(commentHash)
elif actionToTake == "Skip comment and don't upvote":
print "Skip comment and don't upvote - " + username
retireCommentHash(commentHash)
return Response("hello", mimetype='text/html')
@app.route('/<API key>.html', methods=["POST"])
def <API key>():
print "TODO: Copy display to clipboard"
subprocess.call(['./<API key>.py'])
return Response("hello", mimetype='text/html')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=flaskport)
|
#![cfg_attr(all(feature = "nightly", test), feature(test))]
#![cfg(all(feature = "nightly", test))]
extern crate test;
extern crate cxema;
#[cfg(test)]
use cxema::sha2::{Sha256};
use cxema::digest::Digest;
use test::Bencher;
#[bench]
pub fn sha256_10(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 10];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_1k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
|
using System.Collections.Generic;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
namespace JsonApiDotNetCore.Serialization.Building
{
<summary>
Responsible for converting resources into <see cref="ResourceObject" />s given a collection of attributes and relationships.
</summary>
public interface <API key>
{
<summary>
Converts <paramref name="resource" /> into a <see cref="ResourceObject" />. Adds the attributes and relationships that are enlisted in
<paramref name="attributes" /> and <paramref name="relationships" />.
</summary>
<param name="resource">
Resource to build a <see cref="ResourceObject" /> for.
</param>
<param name="attributes">
Attributes to include in the building process.
</param>
<param name="relationships">
Relationships to include in the building process.
</param>
<returns>
The resource object that was built.
</returns>
ResourceObject Build(IIdentifiable resource, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<<API key>> relationships);
}
}
|
<html>
<head>
<title>User agent detail - Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>piwik/device-detector<br /><small>/Tests/fixtures/tablet.yml</small></td><td>Android Browser </td><td>Android 4.0.3</td><td>WebKit </td><td style="border-left: 1px solid #555">Asus</td><td>Eee Pad MeMO 171</td><td>tablet</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[user_agent] => Mozilla/5.0 (Linux; U; Android 4.0.3; zh-tw; ME171 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30
[os] => Array
(
[name] => Android
[short_name] => AND
[version] => 4.0.3
[platform] =>
)
[client] => Array
(
[type] => browser
[name] => Android Browser
[short_name] => AN
[version] =>
[engine] => WebKit
)
[device] => Array
(
[type] => tablet
[brand] => AU
[model] => Eee Pad MeMO 171
)
[os_family] => Android
[browser_family] => Android Browser
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.02101</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.0.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/
|
<html>
<head>
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
<script src='<API key>.js'></script>
<script>
var selectedPreset=<API key>;
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContextFunc();
var player=new WebAudioFontPlayer();
player.adjustPreset(audioContext,selectedPreset);
function startWaveTableNow(pitch) {
var <API key> = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0, pitch, 0.4);
var <API key> = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.4, pitch, 0.2);
var <API key> = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.6, pitch, 0.2);
var <API key> = player.queueWaveTable(audioContext, audioContext.destination, selectedPreset, audioContext.currentTime + 0.8, pitch, 4);
}
</script>
</head>
<body>
<p>file: <API key>.js<br/>
variable: <API key><br/>
MIDI: 41. Viola: Strings</p>
<p><a href='javascript:player.cancelQueue(audioContext);'>stop</a></p>
<p>chords:
<a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+0); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+2); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>Am</a>
| <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+3); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+1); startWaveTableNow(4+12*6+0);'>C</a>
| <a href='javascript:startWaveTableNow(4+12*4+0); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+2); startWaveTableNow(7+12*5+1); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+0);'>E</a>
| <a href='javascript:startWaveTableNow(4+12*4+3); startWaveTableNow(9+12*4+2); startWaveTableNow(2+12*5+0); startWaveTableNow(7+12*5+0); startWaveTableNow(11+12*5+0); startWaveTableNow(4+12*6+3);'>G</a>
</p>
<p>1.
<a href='javascript:startWaveTableNow(0+12*1);'>C</a>
<a href='javascript:startWaveTableNow(1+12*1);'>C
<a href='javascript:startWaveTableNow(2+12*1);'>D</a>
<a href='javascript:startWaveTableNow(3+12*1);'>D
<a href='javascript:startWaveTableNow(4+12*1);'>E</a>
<a href='javascript:startWaveTableNow(5+12*1);'>F</a>
<a href='javascript:startWaveTableNow(6+12*1);'>F
<a href='javascript:startWaveTableNow(7+12*1);'>G</a>
<a href='javascript:startWaveTableNow(8+12*1);'>G
<a href='javascript:startWaveTableNow(9+12*1);'>A</a>
<a href='javascript:startWaveTableNow(10+12*1);'>A
<a href='javascript:startWaveTableNow(11+12*1);'>B</a>
</p>
<p>2.
<a href='javascript:startWaveTableNow(0+12*2);'>C</a>
<a href='javascript:startWaveTableNow(1+12*2);'>C
<a href='javascript:startWaveTableNow(2+12*2);'>D</a>
<a href='javascript:startWaveTableNow(3+12*2);'>D
<a href='javascript:startWaveTableNow(4+12*2);'>E</a>
<a href='javascript:startWaveTableNow(5+12*2);'>F</a>
<a href='javascript:startWaveTableNow(6+12*2);'>F
<a href='javascript:startWaveTableNow(7+12*2);'>G</a>
<a href='javascript:startWaveTableNow(8+12*2);'>G
<a href='javascript:startWaveTableNow(9+12*2);'>A</a>
<a href='javascript:startWaveTableNow(10+12*2);'>A
<a href='javascript:startWaveTableNow(11+12*2);'>B</a>
</p>
<p>3.
<a href='javascript:startWaveTableNow(0+12*3);'>C</a>
<a href='javascript:startWaveTableNow(1+12*3);'>C
<a href='javascript:startWaveTableNow(2+12*3);'>D</a>
<a href='javascript:startWaveTableNow(3+12*3);'>D
<a href='javascript:startWaveTableNow(4+12*3);'>E</a>
<a href='javascript:startWaveTableNow(5+12*3);'>F</a>
<a href='javascript:startWaveTableNow(6+12*3);'>F
<a href='javascript:startWaveTableNow(7+12*3);'>G</a>
<a href='javascript:startWaveTableNow(8+12*3);'>G
<a href='javascript:startWaveTableNow(9+12*3);'>A</a>
<a href='javascript:startWaveTableNow(10+12*3);'>A
<a href='javascript:startWaveTableNow(11+12*3);'>B</a>
</p>
<p>4.
<a href='javascript:startWaveTableNow(0+12*4);'>C</a>
<a href='javascript:startWaveTableNow(1+12*4);'>C
<a href='javascript:startWaveTableNow(2+12*4);'>D</a>
<a href='javascript:startWaveTableNow(3+12*4);'>D
<a href='javascript:startWaveTableNow(4+12*4);'>E</a>
<a href='javascript:startWaveTableNow(5+12*4);'>F</a>
<a href='javascript:startWaveTableNow(6+12*4);'>F
<a href='javascript:startWaveTableNow(7+12*4);'>G</a>
<a href='javascript:startWaveTableNow(8+12*4);'>G
<a href='javascript:startWaveTableNow(9+12*4);'>A</a>
<a href='javascript:startWaveTableNow(10+12*4);'>A
<a href='javascript:startWaveTableNow(11+12*4);'>B</a>
</p>
<p>5.
<a href='javascript:startWaveTableNow(0+12*5);'>C</a>
<a href='javascript:startWaveTableNow(1+12*5);'>C
<a href='javascript:startWaveTableNow(2+12*5);'>D</a>
<a href='javascript:startWaveTableNow(3+12*5);'>D
<a href='javascript:startWaveTableNow(4+12*5);'>E</a>
<a href='javascript:startWaveTableNow(5+12*5);'>F</a>
<a href='javascript:startWaveTableNow(6+12*5);'>F
<a href='javascript:startWaveTableNow(7+12*5);'>G</a>
<a href='javascript:startWaveTableNow(8+12*5);'>G
<a href='javascript:startWaveTableNow(9+12*5);'>A</a>
<a href='javascript:startWaveTableNow(10+12*5);'>A
<a href='javascript:startWaveTableNow(11+12*5);'>B</a>
</p>
<p>6.
<a href='javascript:startWaveTableNow(0+12*6);'>C</a>
<a href='javascript:startWaveTableNow(1+12*6);'>C
<a href='javascript:startWaveTableNow(2+12*6);'>D</a>
<a href='javascript:startWaveTableNow(3+12*6);'>D
<a href='javascript:startWaveTableNow(4+12*6);'>E</a>
<a href='javascript:startWaveTableNow(5+12*6);'>F</a>
<a href='javascript:startWaveTableNow(6+12*6);'>F
<a href='javascript:startWaveTableNow(7+12*6);'>G</a>
<a href='javascript:startWaveTableNow(8+12*6);'>G
<a href='javascript:startWaveTableNow(9+12*6);'>A</a>
<a href='javascript:startWaveTableNow(10+12*6);'>A
<a href='javascript:startWaveTableNow(11+12*6);'>B</a>
</p>
<p>7.
<a href='javascript:startWaveTableNow(0+12*7);'>C</a>
<a href='javascript:startWaveTableNow(1+12*7);'>C
<a href='javascript:startWaveTableNow(2+12*7);'>D</a>
<a href='javascript:startWaveTableNow(3+12*7);'>D
<a href='javascript:startWaveTableNow(4+12*7);'>E</a>
<a href='javascript:startWaveTableNow(5+12*7);'>F</a>
<a href='javascript:startWaveTableNow(6+12*7);'>F
<a href='javascript:startWaveTableNow(7+12*7);'>G</a>
<a href='javascript:startWaveTableNow(8+12*7);'>G
<a href='javascript:startWaveTableNow(9+12*7);'>A</a>
<a href='javascript:startWaveTableNow(10+12*7);'>A
<a href='javascript:startWaveTableNow(11+12*7);'>B</a>
</p>
<p>8.
<a href='javascript:startWaveTableNow(0+12*8);'>C</a>
<a href='javascript:startWaveTableNow(1+12*8);'>C
<a href='javascript:startWaveTableNow(2+12*8);'>D</a>
<a href='javascript:startWaveTableNow(3+12*8);'>D
<a href='javascript:startWaveTableNow(4+12*8);'>E</a>
<a href='javascript:startWaveTableNow(5+12*8);'>F</a>
<a href='javascript:startWaveTableNow(6+12*8);'>F
<a href='javascript:startWaveTableNow(7+12*8);'>G</a>
<a href='javascript:startWaveTableNow(8+12*8);'>G
<a href='javascript:startWaveTableNow(9+12*8);'>A</a>
<a href='javascript:startWaveTableNow(10+12*8);'>A
<a href='javascript:startWaveTableNow(11+12*8);'>B</a>
</p>
</body>
</html>
|
'use strict';
var page = 'projects';
module.exports = {
renderPage: function(req, res) {
if (!req.user) {
res.redirect('/login');
} else {
res.render(page, {
helpers: {
activeClass: function(section) {
if (section === 'projects') {
return 'active';
} else {
return '';
}
}
},
user: req.user ? req.user.toJSON() : null
});
}
}
}
|
[> callback, const QString& text, const QString& yesLabel, const QString& noLabel)
: MenuScreen(mainClass), text(text) {
menuOptions.append(buildMenuItem([this, callback]() {
root->popState();
callback(true);
}, yesLabel));
menuOptions.append(buildMenuItem([this, callback]() {
root->popState();
callback(false);
}, noLabel));
cancelItem = buildMenuItem([this, callback]() {
root->popState();
callback(false);
}, noLabel);
setMenuItemSelected(0);
}
ConfirmationMenu::~ConfirmationMenu() {
}
void ConfirmationMenu::renderTick(bool, bool) {
auto canvas = root->getCanvas();
uint viewWidth = canvas->getView().getSize().x;
uint viewHeight = canvas->getView().getSize().y;
BitmapString::drawString(canvas, root->getFont(), text, viewWidth / 2, viewHeight / 2 - 50, FONT_ALIGN_CENTER);
menuOptions[0]->text->drawString(canvas, viewWidth / 2 - 100, viewHeight / 2 + 50);
menuOptions[1]->text->drawString(canvas, viewWidth / 2 + 100, viewHeight / 2 + 50);
}
void ConfirmationMenu::<API key>(const ControlEvent& e) {
MenuScreen::<API key>(e);
switch (e.first.keyboardKey) {
case Qt::Key_Left:
setMenuItemSelected(-1, true);
break;
case Qt::Key_Right:
setMenuItemSelected(1, true);
break;
}
}
|
'use strict';
//Ghost service used for communicating with the ghost api
angular.module('ghost').factory('Ghost', ['$http', 'localStorageService',
function($http, localStorageService) {
return {
login: function() {
return $http.get('api/ghost/login').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
data.authenticator = '<API key>:o<API key>;
data.expires_at = data.expires_in + Date.now();
localStorageService.set('ghost-cms:session',data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('ghost login failure');
});
}
};
}
]).factory('GhostPosts', ['$http',
function($http) {
return {
read: function(options) {
return $http.get('api/ghost/posts/slug/' + options.slug).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
},
query: function(options) {
return $http.get('api/ghost/posts/tag/' + options.tag).
success(function(data, status, headers, config) {
//console.log(data);
return data;
});
}
};
}
]);
|
from flask_webapi import status
from unittest import TestCase
class TestStatus(TestCase):
def <API key>(self):
self.assertFalse(status.is_informational(99))
self.assertFalse(status.is_informational(200))
for i in range(100, 199):
self.assertTrue(status.is_informational(i))
def test_is_success(self):
self.assertFalse(status.is_success(199))
self.assertFalse(status.is_success(300))
for i in range(200, 299):
self.assertTrue(status.is_success(i))
def test_is_redirect(self):
self.assertFalse(status.is_redirect(299))
self.assertFalse(status.is_redirect(400))
for i in range(300, 399):
self.assertTrue(status.is_redirect(i))
def <API key>(self):
self.assertFalse(status.is_client_error(399))
self.assertFalse(status.is_client_error(500))
for i in range(400, 499):
self.assertTrue(status.is_client_error(i))
def <API key>(self):
self.assertFalse(status.is_server_error(499))
self.assertFalse(status.is_server_error(600))
for i in range(500, 599):
self.assertTrue(status.is_server_error(i))
|
package org.sfm.tuples;
public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> {
private final T20 element19;
public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) {
super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18);
this.element19 = element19;
}
public final T20 getElement19() {
return element19;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tuple20 tuple20 = (Tuple20) o;
if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (element19 != null ? element19.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple20{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
", element2=" + getElement2() +
", element3=" + getElement3() +
", element4=" + getElement4() +
", element5=" + getElement5() +
", element6=" + getElement6() +
", element7=" + getElement7() +
", element8=" + getElement8() +
", element9=" + getElement9() +
", element10=" + getElement10() +
", element11=" + getElement11() +
", element12=" + getElement12() +
", element13=" + getElement13() +
", element14=" + getElement14() +
", element15=" + getElement15() +
", element16=" + getElement16() +
", element17=" + getElement17() +
", element18=" + getElement18() +
", element19=" + getElement19() +
'}';
}
public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) {
return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20);
}
}
|
<?php
$districts = array('Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kaluthara', 'Kandy', 'Kilinochchi', 'Kegalle', 'Mannar', 'Matale', 'Matara', 'Monaragala', 'Mulattivu', 'Nuwaraeliya', 'Polonnaruwa', 'Rathnapura', 'Trincomalee', 'Vavuniya');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../plugins/select2/select2.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="../plugins/iCheck/square/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="../plugins/select2/select2.full.min.js"></script>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="../index2.html"><b>SCHOOL</b> LOGIN</a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Choose your school and enter password</p>
<form action="./index.php" method="post">
<div class="row">
<div class="form-group has-feedback">
<label for="name" class="col-sm-2 control-label">District</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;"
onchange="<API key>(this.value)" name="district" id="district">
<option></option>
<?php
foreach ($districts as $district) {
?>
<option><?php echo $district; ?></option>
<?php
}
?>
</select>
</div>
<br><br><br><br>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">School</label>
<div class="col-sm-12">
<select class="form-control select2" style="width: 100%;" name="schoolsfordistrict" id="schoolsfordistrict" >
</select>
</div>
</div>
</div>
</div>
<br>
<label for="name" class=" control-label">Password</label>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock <API key>"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
<input type="hidden" id="login" name="login">
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.1.4 -->
<script src="../plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="../plugins/select2/select2.full.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: '<API key>',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
$('#Date').datepicker({
autoclose: true,
todayHighlight: true,
format: 'yyyy-mm-dd'
});
function <API key>(district) {
if (district != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('schoolsfordistrict').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "<API key>.php?district=" + district, true);
xmlhttp.send();
}
}
function <API key>(school_id) {
if (school_id != "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
alert(string);
document.getElementById('studentsforschool').innerHTML = string;
}
};
xmlhttp.open("GET", "<API key>.php?school_id=" + school_id, true);
xmlhttp.send();
}
}
</script>
<script>
$(function () {
//Initialize Select2 Elements
$(".select2").select2();
//Datemask dd/mm/yyyy
$("#datemask").inputmask("dd/mm/yyyy", {"placeholder": "dd/mm/yyyy"});
//Datemask2 mm/dd/yyyy
$("#datemask2").inputmask("mm/dd/yyyy", {"placeholder": "mm/dd/yyyy"});
//Money Euro
$("[data-mask]").inputmask();
//Date range picker
$('#reservation').daterangepicker();
//Date range picker with time picker
$('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
},
function (start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: '<API key>',
radioClass: 'iradio_minimal-blue'
});
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: '<API key>',
radioClass: 'iradio_minimal-red'
});
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: '<API key>',
radioClass: 'iradio_flat-green'
});
//Colorpicker
$(".my-colorpicker1").colorpicker();
//color picker with addon
$(".my-colorpicker2").colorpicker();
//Timepicker
$(".timepicker").timepicker({
showInputs: false
});
});
</script>
</body>
</html>
|
#ifndef _TWI_H_
#define _TWI_H_
#define TW_START 0x08 // Start condition transmitted
#define TW_REP_START 0x10 // Repeated Start condition transmitted
#define TW_MT_SLA_ACK 0x18 // SLA+W transmitted, ACK received
#define TW_MT_SLA_NACK 0x20
#define TW_MT_DATA_ACK 0x28 // Data transmitted, ACK received
#define TW_MT_DATA_NACK 0x30
#define TW_MT_ARB_LOST 0x38
#define TW_MR_ARB_LOST 0x38
#define TW_MR_SLA_ACK 0x40 // SLA+R transmitted, ACK received
#define TW_MR_SLA_NACK 0x48
#define TW_MR_DATA_ACK 0x50 // Data received, ACK returned
#define TW_MR_DATA_NACK 0x58 // Data received, NACK returned
#define TW_ST_SLA_ACK 0xA8
#define <API key> 0xB0
#define TW_ST_DATA_ACK 0xB8
#define TW_ST_DATA_NACK 0xC0
#define TW_ST_LAST_DATA 0xC8
#define TW_SR_SLA_ACK 0x60
#define <API key> 0x68
#define TW_SR_GCALL_ACK 0x70
#define <API key> 0x78
#define TW_SR_DATA_ACK 0x80
#define TW_SR_DATA_NACK 0x88
#define <API key> 0x90
#define <API key> 0x98
#define TW_SR_STOP 0xA0
#define TW_NO_INFO 0xF8
#define TW_BUS_ERROR 0x00
#define TW_STATUS (TWSR & TW_NO_INFO) // Grab the status bits
#define TW_READ 1 // Read-mode flag
#define TW_WRITE 0 // Write-mode flag
#endif // #ifndef _TWI_H_
|
package com.viaversion.viaversion.protocols.<API key>;
import com.viaversion.viaversion.api.protocol.AbstractProtocol;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.protocols.<API key>.<API key>;
import com.viaversion.viaversion.protocols.<API key>.<API key>;
public class <API key> extends AbstractProtocol<<API key>, <API key>, <API key>, <API key>> {
public <API key>() {
super(<API key>.class, <API key>.class, <API key>.class, <API key>.class);
}
@Override
protected void registerPackets() {
registerClientbound(<API key>.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT, Type.LONG);
}
});
registerServerbound(<API key>.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.LONG, Type.VAR_INT);
}
});
}
}
|
//config file for bae
if(sumeru.BAE_VERSION){
sumeru.config.database({
dbname : '',
user: '',//bae 3.0 required
password: ''//bae 3.0 required
});
sumeru.config({
site_url : '' //with tailing slash
});
}
|
.<API key> {
display: flex;
align-items: center;
justify-content: center;
background-color: #eee;
position: fixed;
z-index: 100;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.collapsible header {
background-color: #546e7a !important;
}
|
#include <cassert>
#include <cmath>
#include "gtest/gtest.h"
#include "interlude.hpp"
// defined in the header
// #define MAT_SIZE 5
using std::cout;
using std::endl;
// void matDiagSum(int a[][MAT_SIZE], int rows, int cols){
// 1 2 3 4 5 1 2 3 4 5
// 6 7 8 9 10 6 8 10 12 14
// 11 12 13 14 15 11 18 21 24 27
// 16 17 18 19 20 16 28 36 40 44
// 21 22 23 24 25 21 38 51 60 65
// 0,0 0,1 0,2 0,3 0,4
// 1,0 1,1 1,2 1,3 1,4
// 2,0 2,1 2,2 2,3 2,4
// 3,0 3,1 3,2 3,3 3,4
// 4,0 4,1 4,2 4,3 4,4
void printArr(int arr[][MAT_SIZE], int rows, int cols) {
cout << "The two dimensional array:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
// int digitMultiSeq(int n){
// int multiplyDigits(int a){
// bool isPermutation(unsigned int n, unsigned int m){
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerE3.html
// double standardDeviation(double values[], int length, int size){
// The formula for standard deviation
// a is the avarage of of the values r1 ... rN
// sqrt( ( ((r1 - a) x (r1 - a)) + ((r2-a) x (r2-a)) + ... + ((rN - a) x (rN - a)) ) / N )
// assert(length <= size);
// From http://www.doc.ic.ac.uk/~wjk/C++Intro/RobMillerL6.html#S6-2
double average(double list[], int length, int size){
double total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += list[count];
return (total / length);
}
// TEST(Functions, digit_multi_seq){
// EXPECT_EQ(38, digitMultiSeq(8));
// EXPECT_EQ(62, digitMultiSeq(9));
// EXPECT_EQ(74, digitMultiSeq(10));
// TEST(Functions, multiply_digits){
// int a = 1234;
// EXPECT_EQ(24, multiplyDigits(a));
// TEST(Matrix, mat_diag_sum){
// int mat[MAT_SIZE][MAT_SIZE] = { { 1, 2, 3, 4, 5},
// { 6, 7, 8, 9, 10},
// { 11, 12, 13, 14, 15},
// { 16, 17, 18, 19, 20},
// { 21, 22, 23, 24, 25}};
// int ans[MAT_SIZE][MAT_SIZE] = { {1, 2, 3, 4, 5},
// {6, 8, 10, 12, 14},
// {11, 18,21, 24, 27},
// {16, 28, 36, 40, 44},
// {21, 38, 51, 60, 65}};
// matDiagSum(mat,MAT_SIZE,MAT_SIZE);
// printArr(mat,MAT_SIZE,MAT_SIZE);
// printArr(ans,MAT_SIZE,MAT_SIZE);
// for(int i = 0; i < MAT_SIZE; i++){
// for(int j = 0; j < MAT_SIZE; j++){
// EXPECT_EQ(ans[i][j], mat[i][j]);
// TEST(Arrays, is_permutation){
// int n = 1234;
// int m = 4231;
// int n2 = 456723;
// int m2 = 456724;
// int n3 = 45647235;
// int m3 = 45657234;
// EXPECT_TRUE(isPermutation(n,m));
// EXPECT_FALSE(isPermutation(n2,m2));
// EXPECT_TRUE(isPermutation(n3,m3));
TEST(Functions, average){
int length = 5;
int size = 5;
double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
EXPECT_DOUBLE_EQ(13226.693, average(list,length,size));
}
// TEST(Arrays, standard_deviation){
// int length = 5;
// int size = 5;
// double list[] = {2.51, 5.468, 89.12, 546.49, 65489.877};
// double epsilon = 0.001;
// EXPECT_TRUE( abs(26132.36913 - standardDeviation(list,length,size)) <= epsilon);
|
<?php
namespace Metrol\HTML\Table;
/**
* Defines an HTML Table Foot Area
*/
class Foot extends Section
{
public function __construct()
{
parent::__construct('tfoot');
$this->rows = array();
}
}
|
clean_zsh_history
==============
Erase tautological history in `.zsh_history`.
# Usage
python ./clean_zsh_history.py [path/to/.zsh_history]
default arguments is `$HOME/.zsh_history`
|
import sys
sys.path.insert(0,'../')
from fast_guided_filter import blur
print("hello")
|
#include "core/bomberman.hpp"
#include "core/menu.hpp"
#include "core/screens.hpp"
#include "core/view.hpp"
#include "core/views/menu.hpp"
MenuView::MenuView(Screen *screen, Menu *menu)
: View(screen)
, menu(menu)
, clock(Timer::get(2))
{
}
MenuView::~MenuView()
{
delete this->menu;
}
void MenuView::update(const Events &events)
{
Vec2u pos(events.touch.x, events.touch.y);
if (events.touch.isTouch && this->clock.current() > 10000)
{
this->clock.reset();
this->menu->onClick(pos);
}
}
void MenuView::render()
{
swiWaitForVBlank();
dmaCopy(this->menu->bgSrc, bgGetGfxPtr(this->getScreen().bg), this->menu->bgSize);
}
void MenuView::setMenu(Menu *menu)
{
if (menu != nullptr)
{
menu->setView(this);
}
Menu *old = this->menu;
Bomberman::getInstance().nextTick([old]() {
delete old;
});
this->menu = menu;
}
Menu &MenuView::getMenu()
{
return *this->menu;
}
const Menu &MenuView::getMenu() const
{
return *this->menu;
}
|
<reference src="js/tempus-dominus"/>
/*global $ */
tempusDominus.jQueryInterface = function (option, argument) {
if (this.length === 1) {
return tempusDominus.jQueryHandleThis(this, option, argument);
}
// "this" is jquery here
return this.each(function () {
tempusDominus.jQueryHandleThis(this, option, argument);
});
};
tempusDominus.jQueryHandleThis = function (me, option, argument) {
let data = $(me).data(tempusDominus.Namespace.dataKey);
if (typeof option === 'object') {
$.extend({}, tempusDominus.DefaultOptions, option);
}
if (!data) {
data = new tempusDominus.TempusDominus($(me)[0], option);
$(me).data(tempusDominus.Namespace.dataKey, data);
}
if (typeof option === 'string') {
if (data[option] === undefined) {
throw new Error(`No method named "${option}"`);
}
if (argument === undefined) {
return data[option]();
} else {
if (option === 'date') {
data.<API key> = true;
}
const ret = data[option](argument);
data.<API key> = false;
return ret;
}
}
};
tempusDominus.<API key> = function ($element) {
let selector = $element.data('target'),
$selector;
if (!selector) {
selector = $element.attr('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
$selector = $(selector);
if ($selector.length === 0) {
return $element;
}
if (!$selector.data(tempusDominus.Namespace.dataKey)) {
$.extend({}, $selector.data(), $(this).data());
}
return $selector;
};
$(document)
.on(
`click${tempusDominus.Namespace.events.key}.data-api`,
`[data-toggle="${tempusDominus.Namespace.dataKey}"]`,
function () {
const $originalTarget = $(this),
$target = tempusDominus.<API key>($originalTarget),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (
config._options.allowInputToggle &&
$originalTarget.is('input[data-toggle="datetimepicker"]')
) {
return;
}
tempusDominus.jQueryInterface.call($target, 'toggle');
}
)
.on(
tempusDominus.Namespace.events.change,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.<API key>($(this));
if ($target.length === 0 || event.isInit) {
return;
}
tempusDominus.jQueryInterface.call($target, '_change', event);
}
)
.on(
tempusDominus.Namespace.events.blur,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.<API key>($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (config._options.debug || window.debug) {
return;
}
tempusDominus.jQueryInterface.call($target, 'hide', event);
}
)
.on(
tempusDominus.Namespace.events.focus,
`.${tempusDominus.Namespace.NAME}-input`,
function (event) {
const $target = tempusDominus.<API key>($(this)),
config = $target.data(tempusDominus.Namespace.dataKey);
if ($target.length === 0) {
return;
}
if (!config._options.allowInputToggle) {
return;
}
tempusDominus.jQueryInterface.call($target, 'show', event);
}
);
const name = 'tempusDominus';
$.fn[name] = tempusDominus.jQueryInterface;
$.fn[name].Constructor = tempusDominus.TempusDominus;
$.fn[name].noConflict = function () {
$.fn[name] = $.fn[name];
return tempusDominus.jQueryInterface;
};
|
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'sanitizeHtml',
pure: false
})
export class SanitizerPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(v: string): SafeHtml {
const html = this._sanitizer.<API key>(v);
if (html.hasOwnProperty('<API key>') &&
/^<p>\d+\./.test(html['<API key>'])) {
html['<API key>'] =
'<p>' + html['<API key>']
.substr(html['<API key>'].indexOf('.') + 1);
}
return html;
}
}
|
<?php
namespace Nexy\PayboxDirect\Tests\Symfony\Bridge\DependencyInjection;
use Matthias\<API key>\PhpUnit\<API key>;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\Configuration;
use Nexy\PayboxDirect\Bridge\Symfony\DependencyInjection\<API key>;
use SebastianBergmann\Diff\<API key>;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
/**
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*/
class ConfigurationTest extends <API key>
{
public function <API key>()
{
$<API key> = [
'client' => null,
'options' => [],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_minimal.yml',
];
$this-><API key>($<API key>, $sources);
}
public function <API key>()
{
$<API key> = [
'client' => 'fake',
'options' => [
'timeout' => 20,
'production' => true,
],
'paybox' => [
'version' => 'direct_plus',
'site' => '1999888',
'rank' => '32',
'identifier' => '107904482',
'key' => '1999888I',
'default_currency' => 'us_dollar',
'default_activity' => 'recurring_payment',
],
];
$sources = [
__DIR__.'/../../../fixtures/config/config_full.yml',
];
$this-><API key>($<API key>, $sources);
}
public function <API key>()
{
$this-><API key>('/"paybox".*"nexy_paybox_direct" must be configured.$/');
$sources = [
__DIR__.'/../../../fixtures/config/config_none.yml',
];
$this-><API key>([], $sources);
}
protected function <API key>(): ExtensionInterface
{
return new <API key>();
}
protected function getConfiguration(): Configuration
{
return new Configuration();
}
}
|
.jqCron-selector {
position: relative;
}
.jqCron-cross,
.<API key> {
cursor: pointer;
border-radius: 3px;
border: 1px solid #ddd;
margin: 0 0.2em;
padding: 0 0.5em;
}
.jqCron-container.disable .jqCron-cross:hover,
.jqCron-container.disable .<API key>:hover,
.jqCron-cross,
.<API key> {
background: #eee;
border-color: #ddd;
}
.jqCron-cross:hover,
.<API key>:hover {
background-color: #ddd;
border-color: #aaa;
}
.jqCron-cross {
border-radius: 1em;
font-size: 80%;
padding: 0 0.3em;
}
.<API key> {
background: #eee;
border: 1px solid #aaa;
-webkit-box-shadow: 2px 2px 3px #ccc;
box-shadow: 2px 2px 3px #ccc;
left: 0.2em;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 1.5em;
z-index: 1;
}
.<API key> li {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
cursor: default;
display: inline-block;
margin: 0;
padding: 0.1em 0.4em;
width: 100%;
}
.<API key> li.selected {
background: #0088cc;
color: white;
}
.<API key> li:hover {
background: #5fb9e7;
color: white;
}
.<API key>.cols2 {
width: 4em;
}
.<API key>.cols2 li {
width: 50%;
}
.<API key>.cols3 {
width: 6em;
}
.<API key>.cols3 li {
width: 33%;
}
.<API key>.cols4 {
width: 8em;
}
.<API key>.cols4 li {
width: 25%;
}
.<API key>.cols5 {
width: 10em;
}
.<API key>.cols5 li {
width: 20%;
}
.jqCron-error .<API key> {
background: #fee;
border: 1px solid #fdd;
color: red;
}
.jqCron-container.disable * {
color: #888;
}
.jqCron-container.disable .<API key> {
background: #eee !important;
}
|
# from test_plus.test import TestCase
# class TestUser(TestCase):
# def setUp(self):
# self.user = self.make_user()
# def test__str__(self):
# self.assertEqual(
# self.user.__str__(),
# 'testuser' # This is the default username for self.make_user()
# def <API key>(self):
# self.assertEqual(
# self.user.get_absolute_url(),
# '/users/testuser/'
|
<?php
class <API key> {
const NOTICE_ID = '<API key>';
const NOTICE_GROUP = '<API key>';
/**
* @var WPML_Notices
*/
private $admin_notices;
public function __construct( WPML_Notices $admin_notices ) {
$this->admin_notices = $admin_notices;
}
/**
* @param int $track_strings
*/
public function add( $track_strings ) {
if ( ! $track_strings ) {
return;
}
$options_nonce = '<API key>';
$message = __( 'For String Tracking to work, the option', '<API key>' );
$message .= '<strong> ' . __( 'Assume that all texts in PHP strings are in English', '<API key>' ) . ' </strong>';
$message .= __( 'was automatically disabled. To enable it back, go to WPML->Theme and Plugins localization.', '<API key>' );
$message .= '<input type="hidden" id="' . $options_nonce . '" name="' . $options_nonce . '" value="' . wp_create_nonce( $options_nonce ) . '">';
$notice = $this->admin_notices->get_new_notice( self::NOTICE_ID, $message, self::NOTICE_GROUP );
$notice->set_css_class_types( 'info' );
$notice->add_action( $this->admin_notices-><API key>( __( 'Cancel and undo changes', '<API key>' ), '#', false, false, 'button-primary' ) );
$notice->add_action( $this->admin_notices-><API key>( __( 'Skip', '<API key>' ), '#', false, true ) );
$this->admin_notices->add_notice( $notice );
}
public function remove() {
$this->admin_notices->remove_notice(
self::NOTICE_GROUP,
self::NOTICE_ID
);
}
}
|
using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
<summary>
<API key>.
</summary>
public class <API key> : AopResponse
{
}
}
|
#ifndef ACCOUNTDIALOG_H
#define ACCOUNTDIALOG_H
#include <QDialog>
namespace Ui {
class AccountDialog;
}
class AccountDialog : public QDialog
{
Q_OBJECT
public:
explicit AccountDialog(QWidget *parent = 0);
~AccountDialog();
private slots:
// TODO:
void <API key>();
void <API key>();
void <API key>();
void <API key>();
void <API key>();
private:
Ui::AccountDialog *ui;
};
#endif // ACCOUNTDIALOG_H
|
import Telescope from 'meteor/nova:lib';
import Posts from "meteor/nova:posts";
import Comments from "meteor/nova:comments";
import Users from 'meteor/nova:users';
serveAPI = function(terms){
var posts = [];
var parameters = Posts.parameters.get(terms);
const postsCursor = Posts.find(parameters.selector, parameters.options);
postsCursor.forEach(function(post) {
var url = Posts.getLink(post);
var postOutput = {
title: post.title,
headline: post.title, // for backwards compatibility
author: post.author,
date: post.postedAt,
url: url,
pageUrl: Posts.getPageUrl(post, true),
guid: post._id
};
if(post.body)
postOutput.body = post.body;
if(post.url)
postOutput.domain = Telescope.utils.getDomain(url);
if (post.thumbnailUrl) {
postOutput.thumbnailUrl = Telescope.utils.addHttp(post.thumbnailUrl);
}
var twitterName = Users.getTwitterNameById(post.userId);
if(twitterName)
postOutput.twitterName = twitterName;
var comments = [];
Comments.find({postId: post._id}, {sort: {postedAt: -1}, limit: 50}).forEach(function(comment) {
var commentProperties = {
body: comment.body,
author: comment.author,
date: comment.postedAt,
guid: comment._id,
parentCommentId: comment.parentCommentId
};
comments.push(commentProperties);
});
var commentsToDelete = [];
comments.forEach(function(comment, index) {
if (comment.parentCommentId) {
var parent = comments.filter(function(obj) {
return obj.guid === comment.parentCommentId;
})[0];
if (parent) {
parent.replies = parent.replies || [];
parent.replies.push(JSON.parse(JSON.stringify(comment)));
commentsToDelete.push(index);
}
}
});
commentsToDelete.reverse().forEach(function(index) {
comments.splice(index,1);
});
postOutput.comments = comments;
posts.push(postOutput);
});
return JSON.stringify(posts);
};
|
class ImportResult < ActiveRecord::Base
belongs_to :import
enum status: [ :starting, :running, :finishing, :finished, :stalled, :aborted ]
serialize :found_listing_keys
serialize :<API key>
serialize :snapshots
def <API key>
previous_run = self.import.import_results.where(['start_time < ?', self.start_time]).order("start_time DESC").limit(1).first
previous_run.present? ? self.found_listing_keys.count - previous_run.found_listing_keys.count : nil
end
end
|
package fr.pizzeria.exception;
public class StockageException extends Exception {
public StockageException() {
super();
}
public StockageException(String message, Throwable cause) {
super(message, cause);
}
public StockageException(String message) {
super(message);
}
public StockageException(Throwable cause) {
super(cause);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.