answer stringlengths 15 1.25M |
|---|
\author AMD Developer Tools Team
\file <API key>.cpp
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTOSWrappers/Include/osProcess.h>
#include <AMDTOSWrappers/Include/osDebugLog.h>
#include <AMDTOSWrappers/Include/osStringConstants.h>
// Local:
#include <AMDTServerUtilities/Include/<API key>.h>
#include <AMDTServerUtilities/Include/suStringConstants.h>
#include <AMDTServerUtilities/Include/<API key>.h>
// Name: <API key>::<API key>
// Description: Constructor
<API key>::<API key>(): <API key>(true)
{
// Register to the Technology Monitors manager:
<API key>::instance().<API key>(this);
// Add the default context to the list of context:
suContextMonitor& nonContextMonitor = suContextMonitor::<API key>();
_contextsMonitors.push_back(&nonContextMonitor);
// Check the environment variables that contain information for performance counters monitoring:
gtString <API key>;
bool rcPerfCounters = <API key>(<API key>, <API key>);
GT_IF_WITH_ASSERT(rcPerfCounters)
{
// If this environment variable is set to TRUE
if (<API key> == <API key>)
{
<API key>(true);
}
else
{
// If this variable is set at all, we expect it to be TRUE or FALSE:
<API key>(false);
}
}
}
// Name: <API key>::~<API key>
// Description: Destructor
<API key>::~<API key>()
{
// Unregister from the Technology Monitors manager:
<API key>::instance().<API key>(this);
// Delete the context monitors:
// Do not clear the first one, cause it is shared by all technology monitors:
int noOfRenderContexts = (int)_contextsMonitors.size();
for (int i = 1; i < noOfRenderContexts; i++)
{
delete _contextsMonitors[i];
_contextsMonitors[i] = NULL;
}
_contextsMonitors.clear();
}
// Name: <API key>::amountOfContexts
// for this technology monitor
int <API key>::amountOfContexts() const
{
return (int)_contextsMonitors.size();
}
// Name: <API key>::contextMonitor
// Description: Inputs a render context id and returns its context monitor.
// (Or null, if a context of that id does not exist)
const suContextMonitor* <API key>::contextMonitor(int contextId) const
{
const suContextMonitor* retVal = NULL;
// Index range test:
int contextsAmount = amountOfContexts();
if ((0 <= contextId) && (contextId < contextsAmount))
{
retVal = (const suContextMonitor*)_contextsMonitors[contextId];
}
return retVal;
}
// Name: <API key>::contextMonitor
// Description: Inputs a render context id and returns its context monitor.
// (Or null, if a context of that id does not exist)
suContextMonitor* <API key>::contextMonitor(int contextId)
{
suContextMonitor* retVal = NULL;
// Index range test:
int contextsAmount = amountOfContexts();
if ((0 <= contextId) && (contextId < contextsAmount))
{
retVal = (suContextMonitor*)_contextsMonitors[contextId];
}
return retVal;
}
// Name: <API key>::<API key>
// Description: Handles start recoding into the HTML log files event.
void <API key>::<API key>()
{
bool <API key> = true;
// Iterate over the existing contexts:
int amountOfContexts = (int)_contextsMonitors.size();
for (int i = 0; i < amountOfContexts; i++)
{
// Start the current context log file recording:
<API key>* pCallsHistoryLogger = _contextsMonitors[i]->callsHistoryLogger();
GT_IF_WITH_ASSERT(pCallsHistoryLogger != NULL)
{
bool rc = pCallsHistoryLogger-><API key>();
<API key> = <API key> && rc;
}
}
GT_ASSERT_EX(<API key>, L"Log files recording start has failed");
}
// Name: <API key>::<API key>
// Description: Handles stop recoding into the HTML log files event.
void <API key>::<API key>()
{
// Iterate over the existing contexts:
int amountOfContexts = (int)_contextsMonitors.size();
for (int i = 0; i < amountOfContexts; i++)
{
// Stop the current context log file recording:
<API key>* pCallsHistoryLogger = _contextsMonitors[i]->callsHistoryLogger();
GT_IF_WITH_ASSERT(pCallsHistoryLogger != NULL)
{
pCallsHistoryLogger-><API key>();
}
}
}
// Name: <API key>::getHTMLLogFilePath
// Description: Get a context log files path (HTML)
// Arguments: apContextID contextId
// gtString& logFilesPath
// Return Val: bool - Success / failure.
bool <API key>::getHTMLLogFilePath(int contextId, bool& isLogFileExist, osFilePath& logFilesPath)
{
bool retVal = false;
// Get the appropriate context monitor:
const suContextMonitor* pContextMonitor = contextMonitor(contextId);
if (pContextMonitor)
{
// Get its monitored functions calls logger:
const <API key>* pCallsLogger = pContextMonitor->callsHistoryLogger();
GT_IF_WITH_ASSERT(pCallsLogger != NULL)
{
isLogFileExist = pCallsLogger->getHTMLLogFilePath(logFilesPath);
retVal = true;
}
}
return retVal;
}
// Name: <API key>::<API key>
// Description: By default do nothing
void <API key>::<API key>()
{
}
// Name: <API key>::<API key>
// Description: By default do nothing
// Arguments: <API key> breakpointType
// bool isOn
void <API key>::<API key>(<API key> breakpointType, bool isOn)
{
(void)(breakpointType); // unused
(void)(isOn); // unused
} |
package brdgme
// CommandResponse is data relating to a successful command.
type CommandResponse struct {
Logs []Log
CanUndo bool
Remaining string
}
type Status struct {
Active *StatusActive `json:",omitempty"`
Finished *StatusFinished `json:",omitempty"`
}
type StatusActive struct {
WhoseTurn []int `json:"whose_turn"`
Eliminated []int `json:"eliminated"`
}
func (sa StatusActive) ToStatus() Status {
return Status{
Active: &sa,
}
}
type StatusFinished struct {
Placings []int `json:"placings"`
Stats []interface{} `json:"stats"`
}
func (sf StatusFinished) ToStatus() Status {
return Status{
Finished: &sf,
}
}
// Gamer is a playable game.
type Gamer interface {
New(players int) ([]Log, error)
PubState() interface{}
PlayerState(player int) interface{}
Command(
player int,
input string,
players []string,
) (CommandResponse, error)
Status() Status
CommandSpec(player int) *Spec
PlayerCount() int
PlayerCounts() []int
PubRender() string
PlayerRender(player int) string
Points() []float32
} |
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
namespace GuySerializer.Properties
{
[global::System.Runtime.CompilerServices.<API key>()]
[global::System.CodeDom.Compiler.<API key>("Microsoft.VisualStudio.Editors.SettingsDesigner.<API key>", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.<API key>
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.<API key>.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
} |
category: Components
type: Data Display
title: Icon
subtitle:
SVG ([ svg iconfont](https://github.com/ant-design/ant-design-mobile/wiki/Why-use-svg-icon))
:
- `-o` `question-circle`() `question-circle-o`()
- `[icon]-[]-[]-[]`
## (WEB )
.
sh
npm install svg-sprite-loader -D
> Tip: [svg-sprite-loader](https://github.com/kisenka/svg-sprite-loader) sprite
svg
. `webpack.config.js`
# webpack
js
const path = require('path');
const svgDirs = [
require.resolve('antd-mobile').replace(/warn\.js$/, ''), // 1. antd-mobile svg
// path.resolve(__dirname, 'src/<API key>'), // 2. svg
];
module.exports = {
module: {
loaders: [
{
test: /\.(svg)$/i,
loader: 'svg-sprite',
include: svgDirs, // svgDirs svg svg-sprite-loader
},
]
}
};
js
const path = require('path');
module.exports = function(webpackConfig, env) {
const svgDirs = [
require.resolve('antd-mobile').replace(/warn\.js$/, ''), // 1. antd-mobile svg
// path.resolve(__dirname, 'src/<API key>'), // 2. svg
];
// SVG . atool-build svgsvg-url-loade exclude svg-sprite-loader
// https://github.com/ant-tool/atool-build/blob/master/src/<API key>.js#L162
webpackConfig.module.loaders.forEach(loader => {
if (loader.test && typeof loader.test.test === 'function' && loader.test.test('.svg')) {
loader.exclude = svgDirs;
}
});
// 4. webpack loader
webpackConfig.module.loaders.unshift({
test: /\.(svg)$/i,
loader: 'svg-sprite',
include: svgDirs, // svgDirs svg svg-sprite-loader
});
return webpackConfig;
}
> roadhog >= 0.6.0-beta1
html
<Icon type="check" />
> [demo](https:
> [dva-cli](https:
>
svg `<Icon type={require('./reload.svg')} />` `webpack.config.js` `svgDirs` svg-sprite-loader
> `<Icon type={require('!svg-sprite!./reload.svg')} />`
svg `svgDirs`[ webpack loaders-in-require](http://webpack.github.io/docs/using-loaders.html#loaders-in-require)
> RN Icon UI native
- `https://at.alicdn.com/t/font_r5u29ls31bgldi.ttf` `anticon.ttf`
- iOS `info.plist` `Fonts provided by application` item `anticon.ttf` `anticon.ttf`
- Android `anticon.ttf` `android/app/src/main/assets/fonts/` ;
html
<Icon type="check" size="md" color="red" />
<Icon type={'\ue601'} size={55} /> ( demo)
> unicode ant.design chrome
## API
WEBReact-Native
| | | | |
|
| type | icon require (`web`) unicode (`RN`) | String / reqiure('xxx') |
| size | | 'xxs'/'xs'/'sm'/'md'/'lg' (`RN/WEB`)/ number(`RN Only`) | `md` |
| color(`RN Only`) | | Color | '#000' | |
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode rHead = null;
ListNode rTail = null;
ListNode vHead = head;
ListNode vTail = null;
boolean uniq = false;
while (vHead != null) {
uniq = true;
vTail = vHead;
while (vTail.next != null) {
if (vTail.next.val != vHead.val) {
break;
} else {
uniq = false;
vTail = vTail.next;
}
}
if (uniq) {
if (rHead == null) {
rHead = vHead;
} else {
rTail.next = vHead;
}
rTail = vHead;
}
vHead = vTail.next;
}
if (rTail != null) rTail.next = null;
return rHead;
}
} |
package org.jabref.gui.util;
import java.util.Arrays;
import java.util.Collection;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import org.jabref.gui.icon.IconTheme;
import org.controlsfx.control.decoration.Decoration;
import org.controlsfx.control.decoration.GraphicDecoration;
import org.controlsfx.validation.Severity;
import org.controlsfx.validation.ValidationMessage;
import org.controlsfx.validation.decoration.<API key>;
/**
* This class is similar to {@link <API key>} but with a different style and font-based icon.
*/
public class <API key> extends <API key> {
private final Pos position;
public <API key>() {
this(Pos.BOTTOM_LEFT);
}
public <API key>(Pos position) {
this.position = position;
}
@Override
protected Node createErrorNode() {
return IconTheme.JabRefIcons.ERROR.getGraphicNode();
}
@Override
protected Node createWarningNode() {
return IconTheme.JabRefIcons.WARNING.getGraphicNode();
}
@Override
public Node <API key>(ValidationMessage message) {
Node graphic = Severity.ERROR == message.getSeverity() ? createErrorNode() : createWarningNode();
graphic.getStyleClass().add(Severity.ERROR == message.getSeverity() ? "error-icon" : "warning-icon");
Label label = new Label();
label.setGraphic(graphic);
label.setTooltip(createTooltip(message));
label.setAlignment(position);
return label;
}
@Override
protected Tooltip createTooltip(ValidationMessage message) {
Tooltip tooltip = new Tooltip(message.getText());
tooltip.getStyleClass().add(Severity.ERROR == message.getSeverity() ? "tooltip-error" : "tooltip-warning");
return tooltip;
}
@Override
protected Collection<Decoration> <API key>(ValidationMessage message) {
return Arrays.asList(new GraphicDecoration(<API key>(message), position));
}
} |
package seedu.address.model;
import java.util.Comparator;
import java.util.Optional;
import seedu.address.commons.exceptions.<API key>;
import seedu.address.model.ModelManager.<API key>;
import seedu.address.model.filter.TaskPredicate;
import seedu.address.model.task.DeadlineTask;
import seedu.address.model.task.EventTask;
import seedu.address.model.task.FloatingTask;
import seedu.address.model.task.TaskSelect;
/**
* The API of the Model component.
*/
public interface Model extends ReadOnlyModel {
/ Config
/** Sets configured task book file path */
void setTaskBookFilePath(String taskBookFilePath);
/ Task Book
/** Clears existing backing task book and replaces with the provided new task book data. */
void resetTaskBook(ReadOnlyTaskBook newTaskBook);
/ Task Select
/** Sets the task being selected. */
void setTaskSelect(Optional<TaskSelect> taskSelect);
/ Task Filtering
/** Sets the {@link TaskPredicate} used to filter tasks. If the filter is null, no filter is applied. */
void setTaskPredicate(TaskPredicate taskPredicate);
/ Floating Tasks
/* Adds the given floating task and returns its working index. */
int addFloatingTask(FloatingTask floatingTask);
/** Removes the given Floating task and returns it. */
FloatingTask removeFloatingTask(int workingIndex) throws <API key>;
/** Removes the all Floating tasks satisfy the given predicate. */
void removeFloatingTasks(TaskPredicate taskPredicate);
/** Replaces the given Floating task with a new Floating task */
void setFloatingTask(int workingIndex, FloatingTask newFloatingTask) throws <API key>;
/** Sets the comparator used to sort the floating task list. */
void <API key>(Comparator<? super FloatingTask> comparator);
/ Deadline Tasks
/** Adds the given deadline task and returns its working index. */
int addDeadlineTask(DeadlineTask deadlineTask);
/** Removes the given deadline task and returns it. */
DeadlineTask removeDeadlineTask(int workingIndex) throws <API key>;
/** Removes the all Deadline tasks satisfy the given predicate. */
void removeDeadlineTasks(TaskPredicate taskPredicate);
/** Replaces the given deadline task with a new deadline task */
void setDeadlineTask(int workingIndex, DeadlineTask newDeadlineTask) throws <API key>;
/** Sets the comparator used to sort the deadline task list. */
void <API key>(Comparator<? super DeadlineTask> comparator);
/ Event Tasks
/** Adds the given event task and returns its working index */
int addEventTask(EventTask eventTask);
/** Removes the given event task and returns it. */
EventTask removeEventTask(int workingIndex) throws <API key>;
/** Removes the all Event tasks satisfy the given predicate. */
void removeEventTasks(TaskPredicate taskPredicate);
/** Replaces the given event task with a new event task */
void setEventTask(int workingIndex, EventTask newEventTask) throws <API key>;
/** Sets the comparator used to sort the event task list. */
void <API key>(Comparator<? super EventTask> comparator);
/ undo/redo
/**
* Saves the state of the model as a commit.
* @param name The name of the commit.
* @return The new commit.
*/
Commit recordState(String name);
/**
* Redoes the most recently undone commit.
* @return The commit that was redone.
* @throws <API key> if there are no more commits to redo.
*/
Commit redo() throws <API key>;
/**
* Undoes the most recent commit.
* @return the commit that was undone.
* @throws <API key>
*/
Commit undo() throws <API key>;
public interface Commit {
/** The name of the commit */
String getName();
}
} |
require 'spec_helper'
module RSpec
module Given
DESCRIBE_LINE = __LINE__
describe FileCache do
Given(:file_name) { __FILE__ }
Given(:cache) { FileCache.new }
When(:result) { cache.get(file_name) }
context "when reading the file" do
Then { result[DESCRIBE_LINE].should =~ /describe FileCache do/ }
Then { result.size.should == MAX_LINE }
end
context "when getting the same file twice" do
Given { cache.should_receive(:read_lines).once.and_return(["A"]) }
When(:result2) { cache.get(file_name) }
Then { result.should == ["A"] }
Then { result2.should == ["A"] }
end
end
end
end
MAX_LINE = __LINE__ |
using System;
using System.Collections;
using uScoober.Extensions;
namespace uScoober.TestFramework.Assert
{
public static class ShouldExtensions
{
private const string ActualOutOfElements = "Actual Out Of Elements";
private const string <API key> = "Expected Out Of Elements";
public static void ShouldBeEmpty(this IEnumerable values) {
if (values == null) {
throw new <API key>("values");
}
if (values.GetEnumerator()
.MoveNext()) {
Throw.NotEmptyException();
}
}
public static void ShouldBeFalse(this bool value) {
if (value) {
Throw.NotFalseException();
}
}
public static void ShouldBeNull(this object value) {
if (value != null) {
Throw.NotNullException();
}
}
public static void ShouldBeOfType(this object actual, Type expectedClassType) {
if (!expectedClassType.IsClass) {
throw new Exception("ShouldBeOfType() requires a class, not an interface. Use ShouldHaveInterface() instead.");
}
Type actualType = actual.GetType();
if (actualType != expectedClassType) {
Throw.NotEqualException(actualType, expectedClassType);
}
}
public static void ShouldBeTrue(this bool value) {
if (!value) {
Throw.NotTrueException();
}
}
public static void <API key>(this byte[] actual, params byte[] expected) {
int i = 0;
for (; i < actual.Length && i < expected.Length; i++) {
if (actual[i] != expected[i]) {
Throw.NotEqualAtException(actual[i], expected[i], i);
}
}
if (i != actual.Length) {
Throw.NotEqualAtException(actual[i], <API key>, i);
}
if (i != expected.Length) {
Throw.NotEqualAtException(ActualOutOfElements, expected[i], i);
}
}
public static void <API key>(this IEnumerable actual, params object[] expected) {
<API key>(actual, (IEnumerable)expected);
}
public static void <API key>(this IEnumerable actual, IEnumerable expected) {
int counter = 0;
IEnumerator actualEnumerator = actual.GetEnumerator();
IEnumerator expectedEnumerator = expected.GetEnumerator();
bool hasActual = actualEnumerator.MoveNext();
bool hasExpected = expectedEnumerator.MoveNext();
while (hasActual && hasExpected) {
if (!actualEnumerator.Current.Equals(expectedEnumerator.Current)) {
Throw.NotEqualAtException(actualEnumerator.Current, expectedEnumerator.Current, counter);
}
counter++;
hasActual = actualEnumerator.MoveNext();
hasExpected = expectedEnumerator.MoveNext();
}
if (hasActual) {
Throw.NotEqualAtException(actualEnumerator.Current, <API key>, counter);
}
if (hasExpected) {
Throw.NotEqualAtException(ActualOutOfElements, expectedEnumerator.Current, counter);
}
}
public static void ShouldEqual(this object actual, object expected) {
if (!actual.Equals(expected)) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldEqual(this byte actual, byte expected) {
if (actual != expected) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldEqual(this ushort actual, ushort expected) {
if (actual != expected) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldEqual(this char actual, char expected) {
if (actual != expected) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldEqual(this int actual, int expected) {
if (actual != expected) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldEqual(this string actual, string expected) {
if (actual != expected) {
Throw.NotEqualException(actual, expected);
}
}
public static void ShouldHaveInterface(this object actual, Type @interface) {
Type actualType = actual.GetType();
Type[] allInterfaces = actualType.GetInterfaces();
if (!allInterfaces.Contains(@interface)) {
Throw.<API key>(actualType, @interface);
}
}
public static void ShouldNotBeEmpty(this IEnumerable values) {
if (values == null) {
throw new <API key>("values");
}
if (!values.GetEnumerator()
.MoveNext()) {
Throw.EmptyException();
}
}
public static void ShouldNotBeNull(this object value) {
if (value == null) {
Throw.NullException();
}
}
public static void ShouldReference(this object actual, object expected) {
if (!ReferenceEquals(actual, expected)) {
Throw.<API key>();
}
}
}
} |
layout: post
title: LeetCode | Trapping Rain Water in Python
categories: LeetCode
tags: Python
<!-- import js for mathjax -->
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<pre>
'''
Question:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Algorithm:
the amount of water trapped at bar i is affected by the highest bars on the left and right
denote them as "height_i", "high_left", "high_right"
the amount of water can be hold at bar i is min(high_left, high_right) - height_i
'''
class Solution:
# @param A, a list of integers
# @return an integer
def trap(self, A):
# corner case:
# 1. len(A) <= 2
# 2. same heights for all bars
max_from_left = [0 for itr in xrange(len(A))]
max_left = 0
for i in xrange(len(A)-1, -1, -1):
if A[i] > max_left:
max_left = A[i]
max_from_left[i] = max_left
max_from_right = [0 for itr in xrange(len(A))]
max_right = 0
for i in xrange(len(A)):
if A[i] > max_right:
max_right = A[i]
max_from_right[i] = max_right
return sum(map(lambda x: min(x[0], x[1]) - x[2], zip(max_from_left, max_from_right, A)))
</pre> |
var extensionLinker = require('./services/extensionLinker');
function BootstrapServices(){
}
module.exports = BootstrapServices; |
package com.lasarobotics.library.util;
/**
* 3D Vector : Immutable
*/
public class Vector3<T> {
public final T x;
public final T y;
public final T z;
public static class Builder<T> {
private T x, y, z;
public Builder<T> x(T n) {
this.x = n;
return this;
}
public Builder<T> y(T n) {
this.y = n;
return this;
}
public Builder<T> z(T n) {
this.z = n;
return this;
}
public Vector3<T> build() {
return new Vector3<T>(x, y, z);
}
}
public Vector3(T x, T y, T z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
} |
#include <QApplication>
#include "paymentserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"
#include <QByteArray>
#include <QDataStream>
#include <QDebug>
#include <QFileOpenEvent>
#include <QHash>
#include <QLocalServer>
#include <QLocalSocket>
#include <QStringList>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
using namespace boost;
const int <API key> = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("emarket:");
// Create a name that is unique for:
// testnet / non-testnet
// data directory
static QString ipcServerName()
{
QString name("BitcoinQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(GetDataDir(true).string().c_str());
name.append(QString::number(qHash(ddir)));
return name;
}
// This stores payment requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QStringList <API key>;
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
const QStringList& args = qApp->arguments();
for (int i = 1; i < args.size(); i++)
{
if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive))
continue;
<API key>.append(args[i]);
}
foreach (const QString& arg, <API key>)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(<API key>))
return false;
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << arg;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(<API key>);
socket-><API key>();
delete socket;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true)
{
// Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
uriServer = new QLocalServer(this);
if (!uriServer->listen(name))
qDebug() << tr("Cannot start emarket: click-to-pay handler");
else
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
}
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
// clicking on bitcoin: URLs creates FileOpen events on the Mac:
if (event->type() == QEvent::FileOpen)
{
QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->url().isEmpty())
{
if (saveURIs) // Before main window is ready:
<API key>.append(fileEvent->url().toString());
else
emit receivedURI(fileEvent->url().toString());
return true;
}
}
return false;
}
void PaymentServer::uiReady()
{
saveURIs = false;
foreach (const QString& s, <API key>)
emit receivedURI(s);
<API key>.clear();
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer-><API key>();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString message;
in >> message;
if (saveURIs)
<API key>.append(message);
else
emit receivedURI(message);
} |
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="file-fire-behavior.html">
<dom-module id="file-fire">
<template>
<style>
:host {
display: block;
}
</style>
<template is="dom-if" if="{{showInputs}}">
<template is="dom-if" if="{{onlyImages}}">
/**
* An element that allows simple upload of an image to Firebase storage
* Example:
* ```
* <firebase-app
* name="demo"
* api-key="API_KEY"
* auth-domain="AUTH_DOMAIN"
* database-url="DATABASE_URL"
* storage-bucket="convoofire.appspot.com">
* </firebase-app>
* <!-- A file-fire element allowing image upload to firebase storage -->
* <file-fire
* path="/u/test"
* over-write
* max-size="500"
* progress="{{progress}}"
* ></file-fire>
* ```
*
*
* @demo demo/file-fire.html
*/
Polymer({
is: 'file-fire',
behaviors: [FileFireBehavior],
properties: {
srcUrl:{
type: String,
}
},
ready: function(){
if (this.srcUrl){this.showInputs = false} else {this.showInputs = true}
},
});
</script>
</dom-module> |
# <API key>: true
module KubernetesHelpers
include Gitlab::Kubernetes
NODE_NAME = "<API key>"
def kube_response(body)
{ body: body.to_json }
end
def kube_pods_response
kube_response(kube_pods_body)
end
def nodes_response
kube_response(nodes_body)
end
def <API key>
kube_response(nodes_metrics_body)
end
def kube_pod_response
kube_response(kube_pod)
end
def kube_logs_response
{ body: kube_logs_body }
end
def <API key>
kube_response(<API key>)
end
def <API key>(api_url)
WebMock.stub_request(:get, api_url + '/api/v1').to_return(kube_response(<API key>))
WebMock
.stub_request(:get, api_url + '/apis/extensions/v1beta1')
.to_return(kube_response(<API key>))
WebMock
.stub_request(:get, api_url + '/apis/apps/v1')
.to_return(kube_response(<API key>))
WebMock
.stub_request(:get, api_url + '/apis/rbac.authorization.k8s.io/v1')
.to_return(kube_response(kube_v1_rbac_<API key>))
WebMock
.stub_request(:get, api_url + '/apis/metrics.k8s.io/v1beta1')
.to_return(kube_response(<API key>))
end
def <API key>(api_url)
<API key>(api_url)
WebMock
.stub_request(:get, api_url + '/apis/networking.istio.io/v1alpha3')
.to_return(kube_response(<API key>))
end
def <API key>(api_url)
<API key>(api_url)
WebMock
.stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1')
.to_return(kube_response(<API key>))
end
def <API key>(api_url)
<API key>(api_url)
WebMock
.stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1')
.to_return(status: [404, "Resource Not Found"])
end
def <API key>(api_url)
WebMock
.stub_request(:get, api_url + '/apis/serving.knative.dev/v1alpha1')
.to_return(kube_response(<API key>))
end
def <API key>(response = nil, options = {})
<API key>(service.api_url)
namespace_path = options[:namespace].present? ? "namespaces/#{options[:namespace]}/" : ""
pods_url = service.api_url + "/api/v1/#{namespace_path}pods"
WebMock.stub_request(:get, pods_url).to_return(response || kube_pods_response)
end
def <API key>(api_url)
<API key>(api_url)
nodes_url = api_url + "/api/v1/nodes"
WebMock.stub_request(:get, nodes_url).to_return(nodes_response)
end
def <API key>(api_url)
<API key>(api_url)
nodes_url = api_url + "/apis/metrics.k8s.io/v1beta1/nodes"
WebMock.stub_request(:get, nodes_url).to_return(<API key>)
end
def <API key>(namespace, status: nil)
<API key>(service.api_url)
pods_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods"
response = { status: status } if status
WebMock.stub_request(:get, pods_url).to_return(response || kube_pods_response)
end
def <API key>(pod, namespace, status: nil)
<API key>(service.api_url)
pod_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods/#{pod}"
response = { status: status } if status
WebMock.stub_request(:get, pod_url).to_return(response || kube_pod_response)
end
def <API key>(pod_name, namespace, container: nil, status: nil, message: nil)
<API key>(service.api_url)
if container
<API key> = "container=#{container}&"
end
logs_url = service.api_url + "/api/v1/namespaces/#{namespace}/pods/#{pod_name}" \
"/log?#{<API key>}tailLines=#{::PodLogs::KubernetesService::LOGS_LIMIT}×tamps=true"
if status
response = { status: status }
response[:body] = { message: message }.to_json if message
end
WebMock.stub_request(:get, logs_url).to_return(response || kube_logs_response)
end
def <API key>(namespace, status: nil)
<API key>(service.api_url)
deployments_url = service.api_url + "/apis/extensions/v1beta1/namespaces/#{namespace}/deployments"
response = { status: status } if status
WebMock.stub_request(:get, deployments_url).to_return(response || <API key>)
end
def <API key>(options = {})
namespace_path = options[:namespace].present? ? "namespaces/#{options[:namespace]}/" : ""
options[:name] ||= "kubetest"
options[:domain] ||= "example.com"
options[:response] ||= kube_response(<API key>(options))
<API key>(service.api_url)
knative_url = service.api_url + "/apis/serving.knative.dev/v1alpha1/#{namespace_path}services"
WebMock.stub_request(:get, knative_url).to_return(options[:response])
end
def <API key>(api_url, **options)
options[:metadata_name] ||= "default-token-1"
options[:namespace] ||= "default"
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
.to_return(kube_response(kube_v1_secret_body(options)))
end
def <API key>(api_url, name, namespace: 'default', status: 404)
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}")
.to_return(status: [status, "Internal Server Error"])
end
def <API key><API key>(api_url, **options)
options[:metadata_name] ||= "default-token-1"
options[:namespace] ||= "default"
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
.to_return(status: [404, "Not Found"])
.then
.to_return(kube_response(kube_v1_secret_body(options)))
end
def <API key><API key>(api_url, **options)
options[:metadata_name] ||= "default-token-1"
options[:namespace] ||= "default"
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{options[:namespace]}/secrets/#{options[:metadata_name]}")
.to_return(kube_response(kube_v1_secret_body(options.merge(token: nil))))
.then
.to_return(kube_response(kube_v1_secret_body(options)))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url, name, namespace: 'default', status: 404)
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
.to_return(status: [status, "Internal Server Error"])
end
def <API key>(api_url, namespace: 'default')
WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts")
.to_return(kube_response({}))
end
def <API key>(api_url, namespace: 'default')
WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts")
.to_return(status: [500, "Internal Server Error"])
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/serviceaccounts/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url, namespace: 'default')
WebMock.stub_request(:post, api_url + "/api/v1/namespaces/#{namespace}/secrets")
.to_return(kube_response({}))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:put, api_url + "/api/v1/namespaces/#{namespace}/secrets/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url, name)
WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/clusterrolebindings/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/rolebindings/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url)
WebMock.stub_request(:post, api_url + "/api/v1/namespaces")
.to_return(kube_response({}))
end
def <API key>(api_url, namespace: 'default')
WebMock.stub_request(:get, api_url + "/api/v1/namespaces/#{namespace}")
.to_return(kube_response({}))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:put, api_url + "/apis/rbac.authorization.k8s.io/v1/namespaces/#{namespace}/roles/#{name}")
.to_return(kube_response({}))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:get, api_url + "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}")
.to_return(kube_response(<API key>(name, namespace)))
end
def <API key>(api_url, name, namespace: 'default')
WebMock.stub_request(:put, api_url + "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}")
.to_return(kube_response({}))
end
def kube_v1_secret_body(**options)
{
"kind" => "SecretList",
"apiVersion": "v1",
"metadata": {
"name": options.fetch(:metadata_name, "default-token-1"),
"namespace": "kube-system"
},
"data": {
"token": options.fetch(:token, Base64.encode64('token-sample-123'))
}
}
end
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "nodes", "namespaced" => false, "kind" => "Node" },
{ "name" => "pods", "namespaced" => true, "kind" => "Pod" },
{ "name" => "deployments", "namespaced" => true, "kind" => "Deployment" },
{ "name" => "secrets", "namespaced" => true, "kind" => "Secret" },
{ "name" => "serviceaccounts", "namespaced" => true, "kind" => "ServiceAccount" },
{ "name" => "services", "namespaced" => true, "kind" => "Service" },
{ "name" => "namespaces", "namespaced" => true, "kind" => "Namespace" }
]
}
end
# From Kubernetes 1.16+ Deployments are no longer served from apis/extensions
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "ingresses", "namespaced" => true, "kind" => "Deployment" }
]
}
end
def <API key>
{
"kind" => "APIResourceList",
"resources" => []
}
end
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "deployments", "namespaced" => true, "kind" => "Deployment" },
{ "name" => "ingresses", "namespaced" => true, "kind" => "Ingress" }
]
}
end
# Yes, deployments are defined in both apis/extensions/v1beta1 and apis/v1
# (for Kubernetes < 1.16). This matches what Kubenetes API server returns.
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "deployments", "namespaced" => true, "kind" => "Deployment" }
]
}
end
def kube_v1_rbac_<API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "clusterrolebindings", "namespaced" => false, "kind" => "ClusterRoleBinding" },
{ "name" => "clusterroles", "namespaced" => false, "kind" => "ClusterRole" },
{ "name" => "rolebindings", "namespaced" => true, "kind" => "RoleBinding" },
{ "name" => "roles", "namespaced" => true, "kind" => "Role" }
]
}
end
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "nodes", "namespaced" => false, "kind" => "NodeMetrics" },
{ "name" => "pods", "namespaced" => true, "kind" => "PodMetrics" }
]
}
end
def <API key>
{
"kind" => "APIResourceList",
"apiVersion" => "v1",
"groupVersion" => "networking.istio.io/v1alpha3",
"resources" => [
{
"name" => "gateways",
"singularName" => "gateway",
"namespaced" => true,
"kind" => "Gateway",
"verbs" => %w[delete deletecollection get list patch create update watch],
"shortNames" => %w[gw],
"categories" => %w[istio-io networking-istio-io]
},
{
"name" => "serviceentries",
"singularName" => "serviceentry",
"namespaced" => true,
"kind" => "ServiceEntry",
"verbs" => %w[delete deletecollection get list patch create update watch],
"shortNames" => %w[se],
"categories" => %w[istio-io networking-istio-io]
},
{
"name" => "destinationrules",
"singularName" => "destinationrule",
"namespaced" => true,
"kind" => "DestinationRule",
"verbs" => %w[delete deletecollection get list patch create update watch],
"shortNames" => %w[dr],
"categories" => %w[istio-io networking-istio-io]
},
{
"name" => "envoyfilters",
"singularName" => "envoyfilter",
"namespaced" => true,
"kind" => "EnvoyFilter",
"verbs" => %w[delete deletecollection get list patch create update watch],
"categories" => %w[istio-io networking-istio-io]
},
{
"name" => "sidecars",
"singularName" => "sidecar",
"namespaced" => true,
"kind" => "Sidecar",
"verbs" => %w[delete deletecollection get list patch create update watch],
"categories" => %w[istio-io networking-istio-io]
},
{
"name" => "virtualservices",
"singularName" => "virtualservice",
"namespaced" => true,
"kind" => "VirtualService",
"verbs" => %w[delete deletecollection get list patch create update watch],
"shortNames" => %w[vs],
"categories" => %w[istio-io networking-istio-io]
}
]
}
end
def <API key>(name, namespace)
{
"apiVersion" => "networking.istio.io/v1alpha3",
"kind" => "Gateway",
"metadata" => {
"generation" => 1,
"labels" => {
"networking.knative.dev/ingress-provider" => "istio",
"serving.knative.dev/release" => "v0.7.0"
},
"name" => name,
"namespace" => namespace,
"selfLink" => "/apis/networking.istio.io/v1alpha3/namespaces/#{namespace}/gateways/#{name}"
},
"spec" => {
"selector" => {
"istio" => "ingressgateway"
},
"servers" => [
{
"hosts" => [
"*"
],
"port" => {
"name" => "http",
"number" => 80,
"protocol" => "HTTP"
}
},
{
"hosts" => [
"*"
],
"port" => {
"name" => "https",
"number" => 443,
"protocol" => "HTTPS"
},
"tls" => {
"mode" => "PASSTHROUGH"
}
}
]
}
}
end
def <API key>
{
"kind" => "APIResourceList",
"resources" => [
{ "name" => "revisions", "namespaced" => true, "kind" => "Revision" },
{ "name" => "services", "namespaced" => true, "kind" => "Service" },
{ "name" => "configurations", "namespaced" => true, "kind" => "Configuration" },
{ "name" => "routes", "namespaced" => true, "kind" => "Route" }
]
}
end
def kube_pods_body
{
"kind" => "PodList",
"items" => [kube_pod]
}
end
def nodes_body
{
"kind" => "NodeList",
"items" => [kube_node]
}
end
def nodes_metrics_body
{
"kind" => "List",
"items" => [kube_node_metrics]
}
end
def kube_logs_body
"2019-12-13T14:04:22.123456Z Log 1\n2019-12-13T14:04:23.123456Z Log 2\n2019-12-13T14:04:24.123456Z Log 3"
end
def <API key>
{
"kind" => "DeploymentList",
"items" => [kube_deployment]
}
end
def <API key>(name, namespace)
{
"kind" => "PodList",
"items" => [kube_knative_pod(name: name, namespace: namespace)]
}
end
def <API key>(**options)
{
"kind" => "List",
"items" => [knative_09_service(options)]
}
end
# This is a partial response, it will have many more elements in reality but
# these are the ones we care about at the moment
def kube_pod(name: "kube-pod", container_name: "container-0", environment_slug: "production", namespace: "project-namespace", project_slug: "project-path-slug", status: "Running", track: nil)
{
"metadata" => {
"name" => name,
"namespace" => namespace,
"generateName" => "<API key>",
"creationTimestamp" => "2016-11-25T19:55:19Z",
"annotations" => {
"app.gitlab.com/env" => environment_slug,
"app.gitlab.com/app" => project_slug
},
"labels" => {
"track" => track
}.compact
},
"spec" => {
"containers" => [
{ "name" => "#{container_name}" },
{ "name" => "#{container_name}-1" }
]
},
"status" => { "phase" => status }
}
end
# This is a partial response, it will have many more elements in reality but
# these are the ones we care about at the moment
def kube_node
{
"metadata" => {
"name" => NODE_NAME
},
"status" => {
"capacity" => {
"cpu" => "2",
"memory" => "7657228Ki"
},
"allocatable" => {
"cpu" => "1930m",
"memory" => "5777164Ki"
}
}
}
end
# This is a partial response, it will have many more elements in reality but
# these are the ones we care about at the moment
def kube_node_metrics
{
"metadata" => {
"name" => NODE_NAME
},
"usage" => {
"cpu" => "144208668n",
"memory" => "1789048Ki"
}
}
end
# Similar to a kube_pod, but should contain a running service
def kube_knative_pod(name: "kube-pod", namespace: "default", status: "Running")
{
"metadata" => {
"name" => name,
"namespace" => namespace,
"generateName" => "<API key>",
"creationTimestamp" => "2016-11-25T19:55:19Z",
"labels" => {
"serving.knative.dev/service" => name
}
},
"spec" => {
"containers" => [
{ "name" => "container-0" },
{ "name" => "container-1" }
]
},
"status" => { "phase" => status }
}
end
def kube_deployment(name: "kube-deployment", environment_slug: "production", project_slug: "project-path-slug", track: nil)
{
"metadata" => {
"name" => name,
"generation" => 4,
"annotations" => {
"app.gitlab.com/env" => environment_slug,
"app.gitlab.com/app" => project_slug
},
"labels" => {
"track" => track
}.compact
},
"spec" => { "replicas" => 3 },
"status" => {
"observedGeneration" => 4
}
}
end
# noinspection <API key>
def knative_06_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production', cluster_id: 9)
{ "apiVersion" => "serving.knative.dev/v1alpha1",
"kind" => "Service",
"metadata" =>
{ "annotations" =>
{ "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
"serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
"creationTimestamp" => "2019-10-22T21:19:20Z",
"generation" => 1,
"labels" => { "service" => name },
"name" => name,
"namespace" => namespace,
"resourceVersion" => "6042",
"selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
"uid" => "<API key>" },
"spec" => {
"runLatest" => {
"configuration" => {
"revisionTemplate" => {
"metadata" => {
"annotations" => { "Description" => description },
"creationTimestamp" => "2019-10-22T21:19:20Z",
"labels" => { "service" => name }
},
"spec" => {
"container" => {
"env" => [{ "name" => "timestamp", "value" => "2019-10-22 21:19:20" }],
"image" => "image_name",
"name" => "",
"resources" => {}
},
"timeoutSeconds" => 300
}
}
}
}
},
"status" => {
"address" => {
"hostname" => "#{name}.#{namespace}.svc.cluster.local",
"url" => "http://#{name}.#{namespace}.svc.cluster.local"
},
"conditions" =>
[{ "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "ConfigurationsReady" },
{ "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "Ready" },
{ "lastTransitionTime" => "2019-10-22T21:20:25Z", "status" => "True", "type" => "RoutesReady" }],
"domain" => "#{name}.#{namespace}.#{domain}",
"domainInternal" => "#{name}.#{namespace}.svc.cluster.local",
"<API key>" => "#{name}-bskx6",
"<API key>" => "#{name}-bskx6",
"observedGeneration" => 1,
"traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-bskx6" }],
"url" => "http://#{name}.#{namespace}.#{domain}"
},
"environment_scope" => environment,
"cluster_id" => cluster_id,
"podcount" => 0 }
end
# noinspection <API key>
def knative_07_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production', cluster_id: 5)
{ "apiVersion" => "serving.knative.dev/v1alpha1",
"kind" => "Service",
"metadata" =>
{ "annotations" =>
{ "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
"serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
"creationTimestamp" => "2019-10-22T21:19:13Z",
"generation" => 1,
"labels" => { "service" => name },
"name" => name,
"namespace" => namespace,
"resourceVersion" => "289726",
"selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
"uid" => "<API key>" },
"spec" => {
"template" => {
"metadata" => {
"annotations" => { "Description" => description },
"creationTimestamp" => "2019-10-22T21:19:12Z",
"labels" => { "service" => name }
},
"spec" => {
"containers" => [{
"env" =>
[{ "name" => "timestamp", "value" => "2019-10-22 21:19:12" }],
"image" => "image_name",
"name" => "user-container",
"resources" => {}
}],
"timeoutSeconds" => 300
}
},
"traffic" => [{ "latestRevision" => true, "percent" => 100 }]
},
"status" =>
{ "address" => { "url" => "http://#{name}.#{namespace}.svc.cluster.local" },
"conditions" =>
[{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "ConfigurationsReady" },
{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "Ready" },
{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "RoutesReady" }],
"<API key>" => "#{name}-92tsj",
"<API key>" => "#{name}-92tsj",
"observedGeneration" => 1,
"traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-92tsj" }],
"url" => "http://#{name}.#{namespace}.#{domain}" },
"environment_scope" => environment,
"cluster_id" => cluster_id,
"podcount" => 0 }
end
# noinspection <API key>
def knative_09_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production', cluster_id: 5)
{ "apiVersion" => "serving.knative.dev/v1alpha1",
"kind" => "Service",
"metadata" =>
{ "annotations" =>
{ "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
"serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
"creationTimestamp" => "2019-10-22T21:19:13Z",
"generation" => 1,
"labels" => { "service" => name },
"name" => name,
"namespace" => namespace,
"resourceVersion" => "289726",
"selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
"uid" => "<API key>" },
"spec" => {
"template" => {
"metadata" => {
"annotations" => { "Description" => description },
"creationTimestamp" => "2019-10-22T21:19:12Z",
"labels" => { "service" => name }
},
"spec" => {
"containers" => [{
"env" =>
[{ "name" => "timestamp", "value" => "2019-10-22 21:19:12" }],
"image" => "image_name",
"name" => "user-container",
"resources" => {}
}],
"timeoutSeconds" => 300
}
},
"traffic" => [{ "latestRevision" => true, "percent" => 100 }]
},
"status" =>
{ "address" => { "url" => "http://#{name}.#{namespace}.svc.cluster.local" },
"conditions" =>
[{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "ConfigurationsReady" },
{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "Ready" },
{ "lastTransitionTime" => "2019-10-22T21:20:15Z", "status" => "True", "type" => "RoutesReady" }],
"<API key>" => "#{name}-92tsj",
"<API key>" => "#{name}-92tsj",
"observedGeneration" => 1,
"traffic" => [{ "latestRevision" => true, "percent" => 100, "revisionName" => "#{name}-92tsj" }],
"url" => "http://#{name}.#{namespace}.#{domain}" },
"environment_scope" => environment,
"cluster_id" => cluster_id,
"podcount" => 0 }
end
# noinspection <API key>
def knative_05_service(name: 'kubetest', namespace: 'default', domain: 'example.com', description: 'a knative service', environment: 'production', cluster_id: 8)
{ "apiVersion" => "serving.knative.dev/v1alpha1",
"kind" => "Service",
"metadata" =>
{ "annotations" =>
{ "serving.knative.dev/creator" => "system:serviceaccount:#{namespace}:#{namespace}-service-account",
"serving.knative.dev/lastModifier" => "system:serviceaccount:#{namespace}:#{namespace}-service-account" },
"creationTimestamp" => "2019-10-22T21:19:19Z",
"generation" => 1,
"labels" => { "service" => name },
"name" => name,
"namespace" => namespace,
"resourceVersion" => "330390",
"selfLink" => "/apis/serving.knative.dev/v1alpha1/namespaces/#{namespace}/services/#{name}",
"uid" => "<API key>" },
"spec" => {
"runLatest" => {
"configuration" => {
"revisionTemplate" => {
"metadata" => {
"annotations" => { "Description" => description },
"creationTimestamp" => "2019-10-22T21:19:19Z",
"labels" => { "service" => name }
},
"spec" => {
"container" => {
"env" => [{ "name" => "timestamp", "value" => "2019-10-22 21:19:19" }],
"image" => "image_name",
"name" => "",
"resources" => { "requests" => { "cpu" => "400m" } }
},
"timeoutSeconds" => 300
}
}
}
}
},
"status" =>
{ "address" => { "hostname" => "#{name}.#{namespace}.svc.cluster.local" },
"conditions" =>
[{ "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "ConfigurationsReady" },
{ "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "Ready" },
{ "lastTransitionTime" => "2019-10-22T21:20:24Z", "status" => "True", "type" => "RoutesReady" }],
"domain" => "#{name}.#{namespace}.#{domain}",
"domainInternal" => "#{name}.#{namespace}.svc.cluster.local",
"<API key>" => "#{name}-58qgr",
"<API key>" => "#{name}-58qgr",
"observedGeneration" => 1,
"traffic" => [{ "percent" => 100, "revisionName" => "#{name}-58qgr" }] },
"environment_scope" => environment,
"cluster_id" => cluster_id,
"podcount" => 0 }
end
def kube_terminals(service, pod)
pod_name = pod['metadata']['name']
pod_namespace = pod['metadata']['namespace']
containers = pod['spec']['containers']
containers.map do |container|
terminal = {
selectors: { pod: pod_name, container: container['name'] },
url: container_exec_url(service.api_url, pod_namespace, pod_name, container['name']),
subprotocols: ['channel.k8s.io'],
headers: { 'Authorization' => ["Bearer #{service.token}"] },
created_at: DateTime.parse(pod['metadata']['creationTimestamp']),
max_session_time: 0
}
terminal[:ca_pem] = service.ca_pem if service.ca_pem.present?
terminal
end
end
def <API key>
::Gitlab::Kubernetes::RolloutStatus.from_deployments(kube_deployment)
end
def <API key>
::Gitlab::Kubernetes::RolloutStatus.from_deployments
end
end |
# This file is part of Indico.
# Indico is free software; you can redistribute it and/or
from marshmallow import fields
from indico.core.marshmallow import mm
from indico.modules.events.sessions.models.blocks import SessionBlock
from indico.modules.events.sessions.models.sessions import Session
class SessionBlockSchema(mm.<API key>):
room_name_verbose = fields.Function(lambda obj: obj.get_room_name(full=False, verbose=True))
class Meta:
model = SessionBlock
fields = ('id', 'title', 'code', 'start_dt', 'end_dt', 'duration', 'room_name', 'room_name_verbose')
class BasicSessionSchema(mm.<API key>):
blocks = fields.Nested(SessionBlockSchema, many=True)
class Meta:
model = Session
fields = ('id', 'title', 'friendly_id', 'blocks') |
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$email = ($this->session->userdata['logged_in']['email']);
$tipouser = 'Administrador';
$id_user = ($this->session->userdata['logged_in']['id']);
} else {
redirect(base_url());
}
?>
<?php
if ($tipouser == 'Administrador') {
} else {
redirect(base_url());
}
?>
<script type="text/javascript" src="jquery.qrcode.min.js"></script>
<div class="wrapper">
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper" style="min-height: 1156px;">
<br/>
<br/>
<br/>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Registrar Pago
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-home"></i> Inicio</a></li>
<li class="active">Registrar Pago</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-4">
<div class="box box-primary">
<div class="box-header with-border col-md-12">
<input class='validar' id='paypal' type="checkbox" />
<h3 class="box-title" style="font-weight:bold;">Banco</h3>
</div><!-- /.box-header -->
<div class="panel-body">
<div class="col-md-12">
<div class="form-group">
<label style="font-weight:bold">Cuenta</label><br>
<select id="cuenta_id" class="form-control select2" >
<option value=0>SELECCIONE</option>
<?php foreach ($listar_cuentas as $cuentas) { ?>
<option value="<?php echo $cuentas->codigo?>">
<?php foreach ($listar_t_cuentas as $t_cuenta) { ?>
<?php if ($t_cuenta->codigo == $cuentas->tipo_cuenta_id): ?>
CTA. <?php echo $t_cuenta->descripcion?>
<?php endif; ?>
<?php }?>
<?php foreach ($listar_bancos as $bancos) { ?>
<?php if ($bancos->codigo == $cuentas->banco_id): ?>
<?php echo $bancos->descripcion?>
<?php endif; ?>
<?php }?>
<?php echo $cuentas->descripcion?>
</option>
<?php }?>
</select>
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<div class="col-md-6">
<div class="form-group">
<label style="font-weight:bold">Tipo de Pago</label><br>
<select id="tipo_pago" class="form-control select2" >
<option value=0>SELECCIONE</option>
<option value=1>DEPOSITO</option>
<option value=2>TRANSFERENCIA</option>
</select>
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<div class="col-md-6">
<div class="form-group">
<label style="font-weight:bold">Nº Pago</label>
<input type="text" placeholder="Ej: 011494191" maxlength="8" id="num_pago" value="<?php echo $pago[0]->num_pago ?>" class="form-control" >
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<div class="col-md-6">
<div class="form-group">
<label style="font-weight:bold">Fecha</label>
<input type="text" placeholder="Ej: 01/10/2016" maxlength="10" id="fecha_pago" value="<?php echo $pago[0]->fecha_pago ?>" class="form-control" >
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<div class="col-md-6">
<div class="form-group">
<label style="font-weight:bold">Monto</label>
<input type="text" placeholder="Ej: 50" maxlength="10" id="monto" disabled="disabled" value="<?php echo $monto_pago->monto_pago ?>" class="form-control" >
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<div class="col-md-6">
<div class="form-group">
<label style="font-weight:bold">Estatus</label><br>
<?php if ($pago[0]->estatus == 1) {?>
<label style="font-weight:bold; color: blue">En verificación</label>
<?php }else if ($pago[0]->estatus == 2){ ?>
<label style="font-weight:bold; color: green">Aprobado</label>
<?php } ?>
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<?php if ($pago[0]->estatus == 2){ ?>
<div class="col-md-2">
<div class="form-group text-left">
<a class="btn btn-app ver" data-toggle="tab" id="recibo_pago" >
<i class="fa fa-file-pdf-o text-red "></i>
Recibo de Pago
</a>
</div><!-- /.form-group -->
</div><!-- /.form-group -->
<?php } ?>
<div class="col-md-12">
<div class="form-group text-center">
<br>
<button type="button" id="registrar_p" style="font-weight: bold;font-size: 13px" class="btn btn-info " >
<span class="glyphicon <API key>"></span> Registrar
</button>
<input id="cod_perfil" type='hidden' value="<?php echo $cod_perfil ?>" class="form-control" >
<input id="cod_pago" type='hidden' value="<?php echo $pago[0]->codigo ?>" class="form-control" >
<input id="estatus" type='hidden' value="<?php echo $pago[0]->estatus ?>" class="form-control" >
<input id="tipo_pago_id" type='hidden' value="<?php echo $pago[0]->tipo_pago ?>" class="form-control" >
<input id="cuenta_id_id" type='hidden' value="<?php echo $pago[0]->cuenta_id ?>" class="form-control" >
</div><!-- /.form-group -->
</div><!-- /.form-group -->
</div><!-- /.form-group -->
</div><!-- /.box-body -->
</div><!-- /.box-body-primary -->
<div class="col-xs-4">
<div class="box box-primary">
<div class="box-header with-border col-md-12">
<input class='validar' id='paypal' type="checkbox" />
<h3 class="box-title" style="font-weight:bold;">PayPal</h3>
</div><!-- /.box-header -->
<div class="panel-body">
<div class="col-md-12">
<div class="form-group">
<label style="font-weight:bold">Correo</label>
<input type="text" placeholder="" maxlength="8" id="correo_paypal" value="" class="form-control" >
</div><!-- /.form-group -->
</div><!-- /.form-group -->
</div>
</div><!-- /.box-body -->
</div><!-- /.box-body-primary -->
<div class="col-xs-4">
<div class="box box-primary">
<div class="box-header with-border col-md-12">
<input class='validar' id='paypal' type="checkbox" />
<h3 class="box-title" style="font-weight:bold;">Bitcoin</h3>
</div><!-- /.box-header -->
<div class="panel-body">
<div class="col-md-12">
<div class="form-group text-center">
<h4 style="font-weight:bold; "><API key></h4>
<h3 ><em>Compártela para que cualquiera pueda enviarte un pago</em></h3>
</div><!-- /.form-group -->
<div class="col-md-1" ></div>
<div id="qrcodeTable"></div>
</div><!-- /.form-group -->
</div>
</div><!-- /.box-body -->
</div><!-- /.box-body-primary -->
</div><!-- /.box-body -->
</div><!-- /.col -->
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.0
</div>
<strong>Network C. A.</strong>
</footer>
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar
<div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->
<script>
jQuery('#qrcodeTable').qrcode({
render : "table",
text : "<API key>"
});
$('#fecha_pago').numeric({allow: "/"});
$('#num_pago').numeric();
$('#monto').numeric({allow: "."});
$('input').on({
keypress: function () {
$(this).parent('div').removeClass('has-error');
}
});
$('select').on({
change: function () {
$(this).parent('div').removeClass('has-error');
}
});
$('#fecha_pago').datepicker({
format: "dd/mm/yyyy",
language: "es",
autoclose: true,
})
var tipo = $("#tipo_pago_id").val()
var cuenta = $("#cuenta_id_id").val()
$("#tipo_pago").val(tipo);
$("#cuenta_id").val(cuenta);
if ($("#estatus").val() == 99 || $("#estatus").val() == 1) {
$("#cuenta_id,#tipo_pago,#num_pago,#fecha_pago,#registrar_p").prop('disabled',false)
}else{
$("#cuenta_id,#tipo_pago,#num_pago,#fecha_pago,#registrar_p").prop('disabled',true)
}
$('#registrar_p').click(function(e){
e.preventDefault();
//Para validar campos vacios
if ($("#cuenta_id").val() == 0) {
bootbox.alert("Debe selecionar la cuenta a la cual realizo el pago", function () {
}).on('hidden.bs.modal', function (event) {
$("#cuenta_id").parent('div').addClass('has-error')
$("#cuenta_id").focus();
});
}else if ($("#tipo_pago").val() == 0) {
bootbox.alert("Debe selecionar el tipo de pago", function () {
}).on('hidden.bs.modal', function (event) {
$("#tipo_pago").parent('div').addClass('has-error')
$("#tipo_pago").focus();
});
}else if ($("#num_pago").val() == '') {
bootbox.alert("Debe colocar el número", function () {
}).on('hidden.bs.modal', function (event) {
$("#num_pago").parent('div').addClass('has-error')
$("#num_pago").focus();
});
}else if ($("#fecha_pago").val() == '') {
bootbox.alert("Debe indicar el monto", function () {
}).on('hidden.bs.modal', function (event) {
$("#fecha_pago").parent('div').addClass('has-error')
$("#fecha_pago").focus();
});
}else if ($("#monto").val() == 0) {
bootbox.alert("Debe indicar el monto", function () {
}).on('hidden.bs.modal', function (event) {
$("#monto").parent('div').addClass('has-error')
$("#monto").focus();
});
}else{
cuenta_id = $('#cuenta_id').val()
num_pago = $('#num_pago').val()
tipo_pago = $('#tipo_pago').val()
fecha_pago = $('#fecha_pago').val()
$('#monto').prop('disabled',false);
monto = $('#monto').val()
pk_perfil = $('#cod_perfil').val()
cod_pago = $('#cod_pago').val()
$.post('<?php echo base_url(); ?>index.php/referidos/CRelPagos/actualizar',
$.param({'pk_perfil': pk_perfil})+'&'+$.param({'num_pago': num_pago})+'&'+$.param({'monto': monto})+'&'+$.param({'tipo_pago': tipo_pago})+'&'+
$.param({'fecha_pago': fecha_pago})+'&'+$.param({'cuenta_id': cuenta_id})+'&'+$.param({'cod_pago': cod_pago}),
function (response){
if (response[0] == 1) {
bootbox.alert("Disculpe, este num_pago ya fue registrado con este recibo", function () {
}).on('hidden.bs.modal', function (event) {
$("#num_pago,#tipo_pago").parent('div').addClass('has-error')
$("#num_pago,#tipo_pago").focus();
});
} else {
bootbox.alert("Su Registro fue Exitoso ", function (){
window.location = '<?php echo base_url(); ?>index.php/referidos/CRelPagos/'
});
}
});
}
})
$("#recibo_pago").click(function (e) {
e.preventDefault();
// pk_perfil = $('#id').val()
// alert(pk_perfil)
URL = '<?php echo base_url(); ?>index.php/referidos/CRelPagos/pdf_recibo_pago/';
$.fancybox.open({ padding : 0, href: URL, type: 'iframe',width: 1024, height: 520});
});
$("#qrcode").qrcode({
'render': 'canvas',
'size': 250,
'fill': '#1D82AF',
'radius': 0.5,
'background': '#ffffff',
'text': 'http:
});
</script> |
def format_money(amount):
# your formatting code here
return '${:.2f}'.format(amount) |
function <API key>({ appId, apiKey }) {
sessionStorage.setItem('placesAppId', appId);
sessionStorage.setItem('placesApiKey', apiKey);
}
function <API key>() {
const appId = sessionStorage.getItem('placesAppId');
const apiKey = sessionStorage.getItem('placesApiKey');
if (appId && apiKey) {
return { appId, apiKey };
}
return null;
}
function <API key>() {
return fetch('https:
credentials: 'include',
headers: {},
referrer: 'https:
referrerPolicy: '<API key>',
body: null,
method: 'GET',
mode: 'cors',
})
.then((x) => x.json())
.then((credentials) => {
const { application_id: appId, search_api_key: apiKey } = credentials;
if (appId && appId.startsWith('pl') && apiKey) {
<API key>({ appId, apiKey });
return { appId, apiKey };
}
return null;
})
.catch(() => null);
}
function getCredentials() {
return new Promise((resolve, reject) => {
const sessionCredentials = <API key>();
if (!sessionCredentials) {
<API key>()
.then((credentials) => {
resolve(credentials || {});
})
.catch(reject);
} else {
resolve(sessionCredentials || {});
}
});
}
function updatePlaceholders({ appId, apiKey }) {
document.querySelectorAll('.rouge-code > pre > span').forEach((elt) => {
if (elt.textContent.match(/.*YOUR_PLACES_APP_ID.*/)) {
if (elt.textContent.startsWith(`'`)) {
// <API key> no-param-reassign
elt.innerHTML = `'${appId}'`;
} else {
// <API key> no-param-reassign
elt.innerHTML = `"${appId}"`;
}
}
if (elt.textContent.match(/.*YOUR_PLACES_API_KEY.*/)) {
if (elt.textContent.startsWith(`'`)) {
// <API key> no-param-reassign
elt.innerHTML = `'${apiKey}'`;
} else {
// <API key> no-param-reassign
elt.innerHTML = `"${apiKey}"`;
}
}
});
}
function noop() {}
export default function autoPullCredentials() {
return getCredentials()
.then(({ appId, apiKey }) => {
if (appId && apiKey) {
updatePlaceholders({ appId, apiKey });
}
})
.catch(noop);
} |
#ifndef LAYOUTPLANETUNITS_H
#define LAYOUTPLANETUNITS_H
#include "Gui3d/WindowLayout.h"
class LayoutPlanetUnits : public WindowLayout
{
public:
<API key>();
// Construction
LayoutPlanetUnits();
// NodeInterfaceClient interface
void onActivate();
void onDeactivate();
void onUpdate( float t );
private:
// Data
NounPlanet::wRef m_Planet;
};
#endif
//EOF |
#include "C:\Factory\Common\all.h"
#include "Define.h"
static void DoSendBit(uint bit)
{
uint evReady = eventOpen(EV_READY);
uint evBit_0 = eventOpen(EV_BIT_0);
uint evBit_1 = eventOpen(EV_BIT_1);
int result;
if(handleWaitForMillis(evReady, 5000))
{
if(bit)
eventSet(evBit_1);
else
eventSet(evBit_0);
result = 1;
}
else
result = 0;
handleClose(evReady);
handleClose(evBit_0);
handleClose(evBit_1);
errorCase_m(!result, "M^CAEgµÜµ½BóM¤ÌõªoĢܹñB");
}
static void DoSend(char *message)
{
char *p;
LOGPOS();
for(p = message; *p; p++)
{
uint bit;
for(bit = 1 << 7; bit; bit >>= 1)
{
DoSendBit((uint)*p & bit);
}
}
LOGPOS();
}
int main(int argc, char **argv)
{
if(argIs("/F"))
{
char *text = readText(nextArg());
DoSend(text);
memFree(text);
return;
}
if(hasArgs(1))
{
DoSend(nextArg());
return;
}
for(; ; )
{
char *text = readText(c_dropFile());
DoSend(text);
memFree(text);
cout("\n");
}
} |
{% extends "pbase.html" %}
{% block sidebar %} <style type="text/css"> </style> {% endblock %}
{% block content %}
<style type="text/css">
.main { margin-left: 25px; margin-top: 30px; }
.title {
font-size: 1.4em; margin-top: 20px; border-bottom: 1px solid #ccc;
padding-left: 4px;
}
.messages { margin-left: 20px; }
img { margin: 10px; padding: 5px; border: 1px solid #ccc; }
</style>
<div class="main">
<!-- Messages -->
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<a href="{{ backurl }}"><< back</a>
<!-- Image -->
<ul>
{% if image.title %}
<div class="title">{{ image.title }}</div>
{% endif %}
<ul>
<img border="0" alt="" src="{{ media_url }}{{ image.image.name }}" width="900" />
</ul>
</ul>
</div>
{% endblock %} |
package com.witchworks.common.block.natural.crop;
import com.witchworks.common.lib.LibBlockName;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.Random;
public class CropSilphium extends BlockCrop {
public CropSilphium() {
super(LibBlockName.CROP_SILPHIUM);
}
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) {
if (rand.nextBoolean() || !worldIn.getBiome(pos).canRain()) return;
if (isMaxAge(state) && state.getValue(AGE) != 7 && canSustainBush(worldIn.getBlockState(pos.down())) && worldIn.isAirBlock(pos.up())) {
if (worldIn.getBlockState(pos.down()).getBlock() == this) {
worldIn.setBlockState(pos, state.withProperty(AGE, 7), 2);
} else if (rand.nextInt(20) == 0) {
if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(worldIn, pos, state, true)) {
worldIn.setBlockState(pos.up(), getDefaultState());
net.minecraftforge.common.ForgeHooks.onCropsGrowPost(worldIn, pos, state, worldIn.getBlockState(pos));
}
}
}
}
@Override
public boolean canPlaceBlockAt(World worldIn, BlockPos pos) {
IBlockState state = worldIn.getBlockState(pos.down());
return canSustainBush(state);
}
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) {
this.checkForDrop(worldIn, pos, state);
}
private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) {
if (this.canSustainBush(worldIn.getBlockState(pos.down()))) {
return true;
} else {
this.dropBlockAsItem(worldIn, pos, state, 0);
worldIn.setBlockToAir(pos);
return false;
}
}
@Override
protected boolean canSustainBush(IBlockState state) {
return state.getBlock() == Blocks.FARMLAND || state.getBlock() == this;
}
} |
<HTML><HEAD>
<TITLE>Review for Maverick (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0110478">Maverick (1994)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Dragan+Antulov">Dragan Antulov</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>
MAVERICK (1994)
A Film Review
Copyright Dragan Antulov 2000</PRE>
<P>Last year's WILD WILD WEST is something unforgivable and
unjustifiable, but at least in the beginning it might have
looked like a good idea. Five years before, another 1950s
western TV series got itself revamped into rather successful
summer blockbuster. This film was MAVERICK, 1994 western
comedy directed by Richard Donner.</P>
<P>The protagonist of this film is Bret Maverick (played by Mel
Gibson), gambler who is both skillful with cards and guns.
He nevertheless prefers coning than shooting people, and
such abilities will be needed when he decides to join great
poker game which is held on Mississippi riverboat. But to
enter this game he must pay large entering fee, so he must
either collect all debts or find some ingenious ways to
depart people from their money. In doing so, he would cross
paths with Anabella Cranston (played by Jodie Foster),
southern belle whose beauty is not spoiled by bad Southern
accent or lack of scruples. While two of them join forces
and travel to the boat, they are pursued by lawman and
Maverick's old acquintance Zane Cooper (played by James
Garner). All that would lead to whole series of adventures
and encounters with various bizarre characters of the Old
West.</P>
<P>Scriptwriter William Goldman probably envisioned MAVERICK
and western version of STING - story which represents
complex set of intrigues, twist and characters who
constantly try to fool each other. However, his efforts
failed for one simple reason - plot aroused very little
interest in director Richard Donner, who instead envisioned
film as series of elaborate and mostly humorous action
scenes. Sometimes those scenes don't have much connection
with the rest of film, in some segments they are slow and
tendency to have as much cameo appearances as possible makes
this film too long. But film is nevertheless saved by
enthusiastic performances of Mel Gibson and Jodie Foster,
two actors who obviously enjoy playing light-hearted
characters for change. James Garner, who played Maverick in
the original series, is very good in the role of Cooper,
while Graham Greene is hillarious as Indian chief. All in
all, despite the lack of plot and excessive length, there is
enough humour for the audience to enjoy MAVERICK as
unpretencious entertainment. Western fans would be
additionally satisfied because MAVERICK with its light
spirit is rather refreshing addition to the rejuvenated
genre, represented with dark, depressive and revisionist
films of the early 1990s.</P>
<PRE>RATING: 6/10 (++)</PRE>
<PRE>Review written on October 3rd 2000</PRE>
<PRE>Dragan Antulov a.k.a. Drax
Fido: 2:381/100
E-mail: <A HREF="mailto:dragan.antulov@st.tel.hr">dragan.antulov@st.tel.hr</A>
E-mail: <A HREF="mailto:drax@purger.com">drax@purger.com</A>
E-mail: <A HREF="mailto:dragan.antulov@altbbs.fido.hr">dragan.antulov@altbbs.fido.hr</A></PRE>
<P>Filmske recenzije na hrvatskom/Movie Reviews in Croatian
<A HREF="http:
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML> |
# MyFirstGitHubTest
this is my first repository for testing
testing possibilities |
'use strict';
const validation_schema = require('removals_schema').event;
const service = require('../../../api/services/<API key>');
describe('UNIT <API key>', function () {
let <API key>;
before(() => {
<API key> = global.<API key>;
global.<API key> = {
validate: sinon.stub()
};
service.validate({centre: 'bar'});
});
after(() => global.<API key> = <API key>);
it('Should call the <API key>', () =>
expect(global.<API key>.validate).to.be.calledWith({centre: 'bar'}, validation_schema)
);
}); |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Mon Jan 16 20:13:07 PST 2017 -->
<title>ComputeTax</title>
<meta name="date" content="2017-01-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ComputeTax";
}
}
catch(err) {
}
var methods = {"i0":9,"i1":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ComputeTax.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?main/ComputeTax.html" target="_top">Frames</a></li>
<li><a href="ComputeTax.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<div class="subTitle">main</div>
<h2 title="Class ComputeTax" class="title">Class ComputeTax</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>main.ComputeTax</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">ComputeTax</span>
extends java.lang.Object</pre>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Tony Liang</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../main/ComputeTax.html#ComputeTax--">ComputeTax</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method.summary">
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static double</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../main/ComputeTax.html#<API key>-">computeTax</a></span>(int status,
double taxableIncome)</code>
<div class="block">Returns the personal income tax for 2009 with the specified filing status and taxable income.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../main/ComputeTax.html#main-java.lang.String:A-">main</a></span>(java.lang.String[] args)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
</a>
<h3>Constructor Detail</h3>
<a name="ComputeTax
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ComputeTax</h4>
<pre>public ComputeTax()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method.detail">
</a>
<h3>Method Detail</h3>
<a name="main-java.lang.String:A-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] args)</pre>
</li>
</ul>
<a name="<API key>-">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>computeTax</h4>
<pre>public static double computeTax(int status,
double taxableIncome)</pre>
<div class="block">Returns the personal income tax for 2009 with the specified filing status and taxable income.
<ul>
<li>
If the second argument is negative, the tax will be $0.00.
</li>
</ul>
<p>
The available options for filing statuses are
<ul>
<li>
0 for single filer
</li>
<li>
1 for married filing jointly
</li>
<li>
2 for married filing separately
</li>
<li>
3 for head of household
</li>
</ul></div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>status</code> - filing status</dd>
<dd><code>taxableIncome</code> - taxable income</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>personal income tax</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../main/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ComputeTax.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?main/ComputeTax.html" target="_top">Frames</a></li>
<li><a href="ComputeTax.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mount Diablo</title>
<meta name="description" content="Mt Diablo is one of the highest points in San Francisco Bay Area. On a clear day, you can even see Sierra Nevada! I drove to the summit. The view along the w...">
<script>
// Picture element HTML5 shiv
document.createElement( "picture" );
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/picturefill/3.0.1/picturefill.min.js" async></script>
<script>
(function(d) {
var config = {
kitId: 'kwf5dox',
scriptTimeout: 3000,
async: true
},
h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.<API key>("script")[0],a;h.className+=" wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s)
})(document);
</script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Libre+Baskerville:700|Sanchez" type="text/css">
<link rel="stylesheet" href="/css/screen.css">
<link rel="canonical" href="http://localhost:4000/Mt-Diablo">
<link rel="alternate" type="application/rss+xml" title="Bay Area Photos" href="http://localhost:4000/feed.xml">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "<API key>",
<API key>: true
});
</script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-143004455-1');
</script>
<meta name="propeller" content="<API key>">
<script type="text/javascript" src="//deloplen.com/apu.php?zoneid=2707463" async data-cfasync="false"></script>
<script type="text/javascript">
amzn_assoc_ad_type = "<API key>";
<API key> = "travelog008-20";
amzn_assoc_linkid = "<API key>";
<API key> = "";
<API key> = "amazon";
amzn_assoc_region = "US";
</script>
<script src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&Operation=GetScript&ID=OneJS&WS=1&MarketPlace=US"></script>
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.<API key>(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '1522303214583493');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https:
/></noscript>
<!-- End Facebook Pixel Code -->
</head>
<body class="is-offset ">
<header role="banner">
<a href="https:
<h1>Travelog</h1>
</a>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "<API key>",
<API key>: true
});
</script>
</header>
<section role="main">
<article class="post">
<header>
<a href="/Mt-Diablo">
<h1 class="post-title">Mount Diablo</h1>
</a>
<time datetime="2019-03-16T00:00:00-07:00" class="post-date">Saturday, March 16, 2019</time>
</header>
<div class="post-body">
<a href="https:
<div id="<API key>"></div>
<script async="" src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=<API key>"></script>
<div class="post-image">
<img src="img/mt_diablo/DSC02308.png" />
</div>
<div class="post-image">
<img src="img/mt_diablo/DSC02269.png" />
</div>
<div class="post-image">
<img src="img/mt_diablo/DSC02281.png" />
</div>
<div class="post-image">
<img src="img/mt_diablo/DSC02286.png" />
</div>
<div class="post-image">
<img src="img/mt_diablo/DSC02293.png" />
</div>
<div class="post-image">
<img src="img/mt_diablo/DSC02300.png" />
</div>
</div>
<footer class="post-footer">
<a href="https:
</footer>
</article>
</section>
<footer id="footer">
<p>Your Host: <strong><a href="http:
<p class="legal">It is better to travel ten thousand miles than to read ten thousand books</p>
<div id="<API key>"></div><script async src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US&adInstanceId=<API key>"></script>
</footer>
<script type="text/javascript" src="/js/galileo.js"></script>
</body>
</html> |
<?php
class Message
{
public static function sendToConversation($accessToken, $opt)
{
$response = Http::post("/message/<API key>",
array("access_token" => $accessToken),
json_encode($opt));
return $response;
}
public static function send($accessToken, $opt)
{
$response = Http::post("/message/send",
array("access_token" => $accessToken),json_encode($opt));
return $response;
}
} |
using System.IO;
namespace ExperimentalTools.Roslyn.Features.TypeDeclaration
{
internal static class NameHelper
{
public static string RemoveExtension(string documentName) => Path.<API key>(documentName);
public static string AddExtension(string documentName) => $"{documentName}.cs";
}
} |
namespace _04.WorkingWithData.Web.ViewModels
{
public class TagViewModel
{
public string Name { get; set; }
}
} |
<?php
/* @Twig/base_js.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$<API key> = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$<API key>->enter($<API key> = new <API key>($this->getTemplateName(), "template", "@Twig/base_js.html.twig"));
// line 3
echo "<script";
if ((array_key_exists("csp_script_nonce", $context) && (isset($context["csp_script_nonce"]) ? $context["csp_script_nonce"] : $this->getContext($context, "csp_script_nonce")))) {
echo " nonce=";
echo twig_escape_filter($this->env, (isset($context["csp_script_nonce"]) ? $context["csp_script_nonce"] : $this->getContext($context, "csp_script_nonce")), "html", null, true);
}
echo ">/*<![CDATA[*/
";
// line 7
echo "
Sfjs = (function() {
\"use strict\";
var <API key> = 'classList' in document.documentElement;
if (<API key>) {
var hasClass = function (el, cssClass) { return el.classList.contains(cssClass); };
var removeClass = function(el, cssClass) { el.classList.remove(cssClass); };
var addClass = function(el, cssClass) { el.classList.add(cssClass); };
var toggleClass = function(el, cssClass) { el.classList.toggle(cssClass); };
} else {
var hasClass = function (el, cssClass) { return el.className.match(new RegExp('\\\\b' + cssClass + '\\\\b')); };
var removeClass = function(el, cssClass) { el.className = el.className.replace(new RegExp('\\\\b' + cssClass + '\\\\b'), ' '); };
var addClass = function(el, cssClass) { if (!hasClass(el, cssClass)) { el.className += \" \" + cssClass; } };
var toggleClass = function(el, cssClass) { hasClass(el, cssClass) ? removeClass(el, cssClass) : addClass(el, cssClass); };
}
var noop = function() {};
var profilerStorageKey = 'sf2/profiler/';
var request = function(url, onSuccess, onError, payload, options) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
options = options || {};
options.maxTries = options.maxTries || 0;
xhr.open(options.method || 'GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(state) {
if (4 !== xhr.readyState) {
return null;
}
if (xhr.status == 404 && options.maxTries > 1) {
setTimeout(function(){
options.maxTries
request(url, onSuccess, onError, payload, options);
}, 500);
return null;
}
if (200 === xhr.status) {
(onSuccess || noop)(xhr);
} else {
(onError || noop)(xhr);
}
};
xhr.send(payload || '');
};
var getPreference = function(name) {
if (!window.localStorage) {
return null;
}
return localStorage.getItem(profilerStorageKey + name);
};
var setPreference = function(name, value) {
if (!window.localStorage) {
return null;
}
localStorage.setItem(profilerStorageKey + name, value);
};
var requestStack = [];
var extractHeaders = function(xhr, stackElement) {
/* Here we avoid to call xhr.getResponseHeader in order to */
/* prevent polluting the console with CORS security errors */
var allHeaders = xhr.<API key>();
var ret;
if (ret = allHeaders.match(/^x-debug-token:\\s+(.*)\$/im)) {
stackElement.profile = ret[1];
}
if (ret = allHeaders.match(/^x-debug-token-link:\\s+(.*)\$/im)) {
stackElement.profilerUrl = ret[1];
}
};
var successStreak = 4;
var pendingRequests = 0;
var renderAjaxRequests = function() {
var requestCounter = document.querySelector('.<API key>');
if (!requestCounter) {
return;
}
requestCounter.textContent = requestStack.length;
var infoSpan = document.querySelector(\".<API key>\");
if (infoSpan) {
infoSpan.textContent = requestStack.length + ' AJAX request' + (requestStack.length !== 1 ? 's' : '');
}
var ajaxToolbarPanel = document.querySelector('.<API key>');
if (requestStack.length) {
ajaxToolbarPanel.style.display = 'block';
} else {
ajaxToolbarPanel.style.display = 'none';
}
if (pendingRequests > 0) {
addClass(ajaxToolbarPanel, '<API key>');
} else if (successStreak < 4) {
addClass(ajaxToolbarPanel, '<API key>');
removeClass(ajaxToolbarPanel, '<API key>');
} else {
removeClass(ajaxToolbarPanel, '<API key>');
removeClass(ajaxToolbarPanel, '<API key>');
}
};
var startAjaxRequest = function(index) {
var tbody = document.querySelector('.<API key>');
if (!tbody) {
return;
}
var request = requestStack[index];
pendingRequests++;
var row = document.createElement('tr');
request.DOMNode = row;
var methodCell = document.createElement('td');
methodCell.textContent = request.method;
row.appendChild(methodCell);
var typeCell = document.createElement('td');
typeCell.textContent = request.type;
row.appendChild(typeCell);
var statusCodeCell = document.createElement('td');
var statusCode = document.createElement('span');
statusCode.textContent = 'n/a';
statusCodeCell.appendChild(statusCode);
row.appendChild(statusCodeCell);
var pathCell = document.createElement('td');
pathCell.className = 'sf-ajax-request-url';
if ('GET' === request.method) {
var pathLink = document.createElement('a');
pathLink.setAttribute('href', request.url);
pathLink.textContent = request.url;
pathCell.appendChild(pathLink);
} else {
pathCell.textContent = request.url;
}
pathCell.setAttribute('title', request.url);
row.appendChild(pathCell);
var durationCell = document.createElement('td');
durationCell.className = '<API key>';
durationCell.textContent = 'n/a';
row.appendChild(durationCell);
var profilerCell = document.createElement('td');
profilerCell.textContent = 'n/a';
row.appendChild(profilerCell);
row.className = 'sf-ajax-request <API key>';
tbody.insertBefore(row, tbody.firstChild);
renderAjaxRequests();
};
var finishAjaxRequest = function(index) {
var request = requestStack[index];
if (!request.DOMNode) {
return;
}
pendingRequests
var row = request.DOMNode;
/* Unpack the children from the row */
var methodCell = row.children[0];
var statusCodeCell = row.children[2];
var statusCodeElem = statusCodeCell.children[0];
var durationCell = row.children[4];
var profilerCell = row.children[5];
if (request.error) {
row.className = 'sf-ajax-request <API key>';
methodCell.className = '<API key>';
successStreak = 0;
} else {
row.className = 'sf-ajax-request sf-ajax-request-ok';
successStreak++;
}
if (request.statusCode) {
if (request.statusCode < 300) {
statusCodeElem.setAttribute('class', 'sf-toolbar-status');
} else if (request.statusCode < 400) {
statusCodeElem.setAttribute('class', 'sf-toolbar-status <API key>');
} else {
statusCodeElem.setAttribute('class', 'sf-toolbar-status <API key>');
}
statusCodeElem.textContent = request.statusCode;
} else {
statusCodeElem.setAttribute('class', 'sf-toolbar-status <API key>');
}
if (request.duration) {
durationCell.textContent = request.duration + 'ms';
}
if (request.profilerUrl) {
profilerCell.textContent = '';
var profilerLink = document.createElement('a');
profilerLink.setAttribute('href', request.profilerUrl);
profilerLink.textContent = request.profile;
profilerCell.appendChild(profilerLink);
}
renderAjaxRequests();
};
var addEventListener;
var el = document.createElement('div');
if (!('addEventListener' in el)) {
addEventListener = function (element, eventName, callback) {
element.attachEvent('on' + eventName, callback);
};
} else {
addEventListener = function (element, eventName, callback) {
element.addEventListener(eventName, callback, false);
};
}
";
// line 238
if (array_key_exists("excluded_ajax_paths", $context)) {
// line 239
echo " if (window.fetch && window.fetch.polyfill === undefined) {
var oldFetch = window.fetch;
window.fetch = function () {
var promise = oldFetch.apply(this, arguments);
var url = arguments[0];
var params = arguments[1];
var paramType = Object.prototype.toString.call(arguments[0]);
if (paramType === '[object Request]') {
url = arguments[0].url;
params = {
method: arguments[0].method,
credentials: arguments[0].credentials,
headers: arguments[0].headers,
mode: arguments[0].mode,
redirect: arguments[0].redirect
};
}
if (!url.match(new RegExp(";
// line 256
echo <API key>((isset($context["excluded_ajax_paths"]) ? $context["excluded_ajax_paths"] : $this->getContext($context, "excluded_ajax_paths")));
echo "))) {
var method = 'GET';
if (params && params.method !== undefined) {
method = params.method;
}
var stackElement = {
error: false,
url: url,
method: method,
type: 'fetch',
start: new Date()
};
var idx = requestStack.push(stackElement) - 1;
promise.then(function (r) {
stackElement.duration = new Date() - stackElement.start;
stackElement.error = r.status < 200 || r.status >= 400;
stackElement.statusCode = r.status;
stackElement.profile = r.headers.get('x-debug-token');
stackElement.profilerUrl = r.headers.get('x-debug-token-link');
finishAjaxRequest(idx);
}, function (e){
stackElement.error = true;
finishAjaxRequest(idx);
});
startAjaxRequest(idx);
}
return promise;
};
}
if (window.XMLHttpRequest && XMLHttpRequest.prototype.addEventListener) {
var proxied = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
var self = this;
/* prevent logging AJAX calls to static and inline files, like templates */
var path = url;
if (url.substr(0, 1) === '/') {
if (0 === url.indexOf('";
// line 297
echo twig_escape_filter($this->env, twig_escape_filter($this->env, $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array()), "js"), "html", null, true);
echo "')) {
path = url.substr(";
// line 298
echo twig_escape_filter($this->env, twig_length_filter($this->env, $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array())), "html", null, true);
echo ");
}
}
else if (0 === url.indexOf('";
// line 301
echo twig_escape_filter($this->env, twig_escape_filter($this->env, ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "schemeAndHttpHost", array()) . $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array())), "js"), "html", null, true);
echo "')) {
path = url.substr(";
// line 302
echo twig_escape_filter($this->env, twig_length_filter($this->env, ($this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "schemeAndHttpHost", array()) . $this->getAttribute((isset($context["request"]) ? $context["request"] : $this->getContext($context, "request")), "basePath", array()))), "html", null, true);
echo ");
}
if (!path.match(new RegExp(";
// line 305
echo <API key>((isset($context["excluded_ajax_paths"]) ? $context["excluded_ajax_paths"] : $this->getContext($context, "excluded_ajax_paths")));
echo "))) {
var stackElement = {
error: false,
url: url,
method: method,
type: 'xhr',
start: new Date()
};
var idx = requestStack.push(stackElement) - 1;
this.addEventListener('readystatechange', function() {
if (self.readyState == 4) {
stackElement.duration = new Date() - stackElement.start;
stackElement.error = self.status < 200 || self.status >= 400;
stackElement.statusCode = self.status;
extractHeaders(self, stackElement);
finishAjaxRequest(idx);
}
}, false);
startAjaxRequest(idx);
}
proxied.apply(this, Array.prototype.slice.call(arguments));
};
}
";
}
// line 334
echo "
return {
hasClass: hasClass,
removeClass: removeClass,
addClass: addClass,
toggleClass: toggleClass,
getPreference: getPreference,
setPreference: setPreference,
addEventListener: addEventListener,
request: request,
renderAjaxRequests: renderAjaxRequests,
load: function(selector, url, onSuccess, onError, options) {
var el = document.getElementById(selector);
if (el && el.getAttribute('data-sfurl') !== url) {
request(
url,
function(xhr) {
el.innerHTML = xhr.responseText;
el.setAttribute('data-sfurl', url);
removeClass(el, 'loading');
for (var i = 0; i < requestStack.length; i++) {
startAjaxRequest(i);
if (requestStack[i].duration) {
finishAjaxRequest(i);
}
}
(onSuccess || noop)(xhr, el);
},
function(xhr) { (onError || noop)(xhr, el); },
'',
options
);
}
return this;
},
toggle: function(selector, elOn, elOff) {
var tmp = elOn.style.display,
el = document.getElementById(selector);
elOn.style.display = elOff.style.display;
elOff.style.display = tmp;
if (el) {
el.style.display = 'none' === tmp ? 'none' : 'block';
}
return this;
},
createTabs: function() {
var tabGroups = document.querySelectorAll('.sf-tabs');
/* create the tab navigation for each group of tabs */
for (var i = 0; i < tabGroups.length; i++) {
var tabs = tabGroups[i].querySelectorAll('.tab');
var tabNavigation = document.createElement('ul');
tabNavigation.className = 'tab-navigation';
for (var j = 0; j < tabs.length; j++) {
var tabId = 'tab-' + i + '-' + j;
var tabTitle = tabs[j].querySelector('.tab-title').innerHTML;
var tabNavigationItem = document.createElement('li');
tabNavigationItem.setAttribute('data-tab-id', tabId);
if (j == 0) { addClass(tabNavigationItem, 'active'); }
if (hasClass(tabs[j], 'disabled')) { addClass(tabNavigationItem, 'disabled'); }
tabNavigationItem.innerHTML = tabTitle;
tabNavigation.appendChild(tabNavigationItem);
var tabContent = tabs[j].querySelector('.tab-content');
tabContent.parentElement.setAttribute('id', tabId);
}
tabGroups[i].insertBefore(tabNavigation, tabGroups[i].firstChild);
}
/* display the active tab and add the 'click' event listeners */
for (i = 0; i < tabGroups.length; i++) {
tabNavigation = tabGroups[i].querySelectorAll('.tab-navigation li');
for (j = 0; j < tabNavigation.length; j++) {
tabId = tabNavigation[j].getAttribute('data-tab-id');
document.getElementById(tabId).querySelector('.tab-title').className = 'hidden';
if (hasClass(tabNavigation[j], 'active')) {
document.getElementById(tabId).className = 'block';
} else {
document.getElementById(tabId).className = 'hidden';
}
tabNavigation[j].addEventListener('click', function(e) {
var activeTab = e.target || e.srcElement;
/* needed because when the tab contains HTML contents, user can click */
/* on any of those elements instead of their parent '<li>' element */
while (activeTab.tagName.toLowerCase() !== 'li') {
activeTab = activeTab.parentNode;
}
/* get the full list of tabs through the parent of the active tab element */
var tabNavigation = activeTab.parentNode.children;
for (var k = 0; k < tabNavigation.length; k++) {
var tabId = tabNavigation[k].getAttribute('data-tab-id');
document.getElementById(tabId).className = 'hidden';
removeClass(tabNavigation[k], 'active');
}
addClass(activeTab, 'active');
var activeTabId = activeTab.getAttribute('data-tab-id');
document.getElementById(activeTabId).className = 'block';
});
}
}
},
createToggles: function() {
var toggles = document.querySelectorAll('.sf-toggle');
for (var i = 0; i < toggles.length; i++) {
var elementSelector = toggles[i].getAttribute('<API key>');
var element = document.querySelector(elementSelector);
addClass(element, 'sf-toggle-content');
if (toggles[i].hasAttribute('data-toggle-initial') && toggles[i].getAttribute('data-toggle-initial') == 'display') {
addClass(toggles[i], 'sf-toggle-on');
addClass(element, 'sf-toggle-visible');
} else {
addClass(toggles[i], 'sf-toggle-off');
addClass(element, 'sf-toggle-hidden');
}
addEventListener(toggles[i], 'click', function(e) {
e.preventDefault();
if ('' !== window.getSelection().toString()) {
/* Don't do anything on text selection */
return;
}
var toggle = e.target || e.srcElement;
/* needed because when the toggle contains HTML contents, user can click */
/* on any of those elements instead of their parent '.sf-toggle' element */
while (!hasClass(toggle, 'sf-toggle')) {
toggle = toggle.parentNode;
}
var element = document.querySelector(toggle.getAttribute('<API key>'));
toggleClass(toggle, 'sf-toggle-on');
toggleClass(toggle, 'sf-toggle-off');
toggleClass(element, 'sf-toggle-hidden');
toggleClass(element, 'sf-toggle-visible');
/* the toggle doesn't change its contents when clicking on it */
if (!toggle.hasAttribute('<API key>')) {
return;
}
if (!toggle.hasAttribute('<API key>')) {
toggle.setAttribute('<API key>', toggle.innerHTML);
}
var currentContent = toggle.innerHTML;
var originalContent = toggle.getAttribute('<API key>');
var altContent = toggle.getAttribute('<API key>');
toggle.innerHTML = currentContent !== altContent ? altContent : originalContent;
});
/* Prevents from disallowing clicks on links inside toggles */
var toggleLinks = document.querySelectorAll('.sf-toggle a');
for (var i = 0; i < toggleLinks.length; i++) {
addEventListener(toggleLinks[i], 'click', function(e) {
e.stopPropagation();
});
}
}
}
};
})();
Sfjs.addEventListener(window, 'load', function() {
Sfjs.createTabs();
Sfjs.createToggles();
});
</script>
";
$<API key>->leave($<API key>);
}
public function getTemplateName()
{
return "@Twig/base_js.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 380 => 334, 348 => 305, 342 => 302, 338 => 301, 332 => 298, 328 => 297, 284 => 256, 265 => 239, 263 => 238, 30 => 7, 22 => 3,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{# This file is duplicated in WebProfilerBundle/Resources/views/Profiler/base_js.html.twig.
If you make any change in this file, do the same change in the other file.
<script{% if csp_script_nonce is defined and csp_script_nonce %} nonce={{ csp_script_nonce }}{% endif %}>/*<![CDATA[*/
{# Caution: the contents of this file are processed by Twig before loading
/* Here we avoid to call xhr.getResponseHeader in order to */
/* prevent polluting the console with CORS security errors */
/* Unpack the children from the row */
/* prevent logging AJAX calls to static and inline files, like templates */
/* create the tab navigation for each group of tabs */
/* display the active tab and add the 'click' event listeners */
/* needed because when the tab contains HTML contents, user can click */
/* on any of those elements instead of their parent '<li>' element */
/* get the full list of tabs through the parent of the active tab element */
/* Don't do anything on text selection */
/* needed because when the toggle contains HTML contents, user can click */
/* on any of those elements instead of their parent '.sf-toggle' element */
/* the toggle doesn't change its contents when clicking on it */
/* Prevents from disallowing clicks on links inside toggles */
</script> |
package tie.hackathon.travelguide;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Displays emergency contact numbers
*/
public class EmergencyFragment extends Fragment implements View.OnClickListener {
@BindView(R.id.police) Button police;
@BindView(R.id.fire) Button fire;
@BindView(R.id.ambulance) Button ambulance;
@BindView(R.id.blood_bank) Button blood_bank;
@BindView(R.id.bomb) Button bomb;
@BindView(R.id.railways) Button railways;
private Activity activity;
public EmergencyFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_emergency, container, false);
ButterKnife.bind(this,view);
police.setOnClickListener(this);
fire.setOnClickListener(this);
ambulance.setOnClickListener(this);
blood_bank.setOnClickListener(this);
bomb.setOnClickListener(this);
railways.setOnClickListener(this);
return view;
}
@Override
public void onAttach(Context activity) {
super.onAttach(activity);
this.activity = (Activity) activity;
}
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
switch (v.getId()) {
case R.id.police:
intent.setData(Uri.parse("tel:100"));
break;
case R.id.fire:
intent.setData(Uri.parse("tel:101"));
break;
case R.id.ambulance:
intent.setData(Uri.parse("tel:102"));
break;
case R.id.blood_bank:
intent.setData(Uri.parse("tel:25752924"));
break;
case R.id.bomb:
intent.setData(Uri.parse("tel:22512201"));
break;
case R.id.railways:
intent.setData(Uri.parse("tel:23366177"));
}
startActivity(intent);
}
} |
<h1>
{{title}}
</h1>
<nav>
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet> |
import React, {Component} from 'react';
import DataActions from '../actions/dataActions';
import DataStore from '../stores/dataStore';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
import '../css/categoryPage.css';
export default class ValueSeriesItems extends Component {
constructor() {
super();
this.state = {
valueSerie: { name:'none', items: [] }
};
//this.AddNewItem = this.AddNewItem.bind(this);
// this.RemoveItem = this.RemoveItem.bind(this);
this.onChange = this.onChange.bind(this);
}
componentWillMount() {
DataStore.addChangeListener(this.onChange);
}
componentDidMount() {
const id = this.props.params.id;
let vs = DataStore.getValueSeries(id);
this.setState({ valueSerie: vs });
}
<API key>() {
DataStore.<API key>(this.onChange);
}
onChange() {
this.setState({ <API key>: DataStore.series });
}
/* RemoveItem(searchTerm) {
DataActions.deleteValueSeries(searchTerm);
}*/
render() {
const <API key> = (ValueSeriesItem) => {
return (
<TableRow>
<TableRowColumn>
{ValueSeriesItem.name}
</TableRowColumn>
<TableRowColumn>
{ValueSeriesItem.date}
</TableRowColumn>
<TableRowColumn>
{ValueSeriesItem.col1}
</TableRowColumn>
<TableRowColumn>
{ValueSeriesItem.col2}
</TableRowColumn>
<TableRowColumn>
{ValueSeriesItem.col3}
</TableRowColumn>
</TableRow>
);
}
return (
<div>
<Table>
<TableHeader>
<TableRow>
<TableRowColumn>
Value Series:{this.state.valueSerie.name}
</TableRowColumn>
</TableRow>
<TableRow>
<TableRowColumn>
Items
</TableRowColumn>
</TableRow>
</TableHeader>
</Table>
</div>
);
}
} |
// Ver.2.0.0
enum <API key> : int {
<API key> = 0,
<API key>,
};
#ifdef __OBJC__
#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>
@interface EposEasySelectInfo : NSObject
@property (assign, nonatomic, readonly) int deviceType;
@property (strong, nonatomic, readonly) NSString *printerName;
@property (strong, nonatomic, readonly) NSString *macAddress;
@property (strong, nonatomic, readonly) NSString *target;
@end
@interface EposEasySelect : NSObject
- (EposEasySelectInfo *)parseQR:(NSString *)data;
- (EposEasySelectInfo *)parseBeacon:(CLBeacon *)beacon;
- (NSString *)createQR:(NSString *)printerName DeviceType:(int)deviceType MacAddress:(NSString*)macAddress;
@end
#endif /*__OBJC__*/ |
using System;
using System.Linq;
using System.Threading.Tasks;
using GitNStats.Core;
using LibGit2Sharp;
namespace GitNStats
{
public enum Result
{
Success = 0,
Failure = 1
}
public class Controller
{
private readonly View _view;
private readonly FileSystem _fileSystem;
private readonly Func<string, IRepository> RepositoryFactory;
private readonly Func<IRepository, AsyncVisitor> AsyncVisitorFactory;
public Controller(View view, FileSystem fileSystem, Func<string, IRepository> repositoryFactory, Func<IRepository, AsyncVisitor> asyncVisitorFactory)
{
_view = view;
_fileSystem = fileSystem;
RepositoryFactory = repositoryFactory;
AsyncVisitorFactory = asyncVisitorFactory;
}
public Task<Result> RunAnalysis(Options options)
{
_view.QuietMode = options.QuietMode;
var repoPath = RepositoryPath(options);
var filter = Filter(options.DateFilter);
return RunAnalysis(repoPath, options.BranchName, filter);
}
private async Task<Result> RunAnalysis(string repositoryPath, string? branchName, DiffFilterPredicate diffFilter)
{
try
{
using (var repo = RepositoryFactory(repositoryPath))
{
var branch = Branch(branchName, repo);
if (branch == null)
{
_view.DisplayError($"Invalid branch: {branchName}");
return Result.Failure;
}
_view.<API key>(repositoryPath, branch);
var diffs = await AsyncVisitorFactory(repo).Walk(branch.Tip);
var filteredDiffs = diffs.Where(diffFilter.Invoke);
_view.DisplayPathCounts(Analysis.CountFileChanges(filteredDiffs));
return Result.Success;
}
}
catch (<API key>)
{
_view.DisplayError($"{repositoryPath} is not a git repository.");
return Result.Failure;
}
}
private string RepositoryPath(Options options)
{
return String.IsNullOrWhiteSpace(options.RepositoryPath)
? _fileSystem.CurrentDirectory()
: options.RepositoryPath;
}
private static DiffFilterPredicate Filter(DateTime? dateFilter)
{
if (dateFilter == null)
{
return NoFilter;
}
return OnOrAfter;
static bool NoFilter(CommitDiff diffs) => true;
bool OnOrAfter(CommitDiff diffs)
{
// Datetime may come in in as "unspecified", we need to be sure it's specified
// to get accurate comparisons to a commit's DateTimeOffset
return Analysis.OnOrAfter(DateTime.SpecifyKind(dateFilter.Value, DateTimeKind.Local))(diffs);
}
}
private static Branch Branch(string? branchName, IRepository repo)
{
// returns null if branch name is specified but doesn't exist
return (branchName == null) ? repo.Head : repo.Branches[branchName];
}
}
} |
import React,{Component} from 'react'; |
var ripple = require('ripple');
var template = require('./index.html');
var Logo = ripple(template);
module.exports = new Logo(); |
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# all copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject
class GmlFill(IdentifiedObject):
"""Specifies how the area of the geometry will be filled.Specifies how the area of the geometry will be filled.
"""
def __init__(self, opacity=0.0, GmlColour=None, GmlMarks=None, GmlTextSymbols=None, GmlSvgParameters=None, GmlPolygonSymbols=None, *args, **kw_args):
"""Initialises a new 'GmlFill' instance.
@param opacity: Specifies the level of translucency to use when rendering the Fill. The value is encoded as a floating-point value between 0.0 and 1.0 with 0.0 representing completely transparent and 1.0 representing completely opaque, with a linear scale of translucency for intermediate values. The default value is 1.0
@param GmlColour:
@param GmlMarks:
@param GmlTextSymbols:
@param GmlSvgParameters:
@param GmlPolygonSymbols:
"""
#: Specifies the level of translucency to use when rendering the Fill. The value is encoded as a floating-point value between 0.0 and 1.0 with 0.0 representing completely transparent and 1.0 representing completely opaque, with a linear scale of translucency for intermediate values. The default value is 1.0
self.opacity = opacity
self._GmlColour = None
self.GmlColour = GmlColour
self._GmlMarks = []
self.GmlMarks = [] if GmlMarks is None else GmlMarks
self._GmlTextSymbols = []
self.GmlTextSymbols = [] if GmlTextSymbols is None else GmlTextSymbols
self._GmlSvgParameters = []
self.GmlSvgParameters = [] if GmlSvgParameters is None else GmlSvgParameters
self._GmlPolygonSymbols = []
self.GmlPolygonSymbols = [] if GmlPolygonSymbols is None else GmlPolygonSymbols
super(GmlFill, self).__init__(*args, **kw_args)
_attrs = ["opacity"]
_attr_types = {"opacity": float}
_defaults = {"opacity": 0.0}
_enums = {}
_refs = ["GmlColour", "GmlMarks", "GmlTextSymbols", "GmlSvgParameters", "GmlPolygonSymbols"]
_many_refs = ["GmlMarks", "GmlTextSymbols", "GmlSvgParameters", "GmlPolygonSymbols"]
def getGmlColour(self):
return self._GmlColour
def setGmlColour(self, value):
if self._GmlColour is not None:
filtered = [x for x in self.GmlColour.GmlFills if x != self]
self._GmlColour._GmlFills = filtered
self._GmlColour = value
if self._GmlColour is not None:
if self not in self._GmlColour._GmlFills:
self._GmlColour._GmlFills.append(self)
GmlColour = property(getGmlColour, setGmlColour)
def getGmlMarks(self):
return self._GmlMarks
def setGmlMarks(self, value):
for p in self._GmlMarks:
filtered = [q for q in p.GmlFIlls if q != self]
self._GmlMarks._GmlFIlls = filtered
for r in value:
if self not in r._GmlFIlls:
r._GmlFIlls.append(self)
self._GmlMarks = value
GmlMarks = property(getGmlMarks, setGmlMarks)
def addGmlMarks(self, *GmlMarks):
for obj in GmlMarks:
if self not in obj._GmlFIlls:
obj._GmlFIlls.append(self)
self._GmlMarks.append(obj)
def removeGmlMarks(self, *GmlMarks):
for obj in GmlMarks:
if self in obj._GmlFIlls:
obj._GmlFIlls.remove(self)
self._GmlMarks.remove(obj)
def getGmlTextSymbols(self):
return self._GmlTextSymbols
def setGmlTextSymbols(self, value):
for x in self._GmlTextSymbols:
x.GmlFill = None
for y in value:
y._GmlFill = self
self._GmlTextSymbols = value
GmlTextSymbols = property(getGmlTextSymbols, setGmlTextSymbols)
def addGmlTextSymbols(self, *GmlTextSymbols):
for obj in GmlTextSymbols:
obj.GmlFill = self
def <API key>(self, *GmlTextSymbols):
for obj in GmlTextSymbols:
obj.GmlFill = None
def getGmlSvgParameters(self):
return self._GmlSvgParameters
def setGmlSvgParameters(self, value):
for p in self._GmlSvgParameters:
filtered = [q for q in p.GmlFills if q != self]
self._GmlSvgParameters._GmlFills = filtered
for r in value:
if self not in r._GmlFills:
r._GmlFills.append(self)
self._GmlSvgParameters = value
GmlSvgParameters = property(getGmlSvgParameters, setGmlSvgParameters)
def addGmlSvgParameters(self, *GmlSvgParameters):
for obj in GmlSvgParameters:
if self not in obj._GmlFills:
obj._GmlFills.append(self)
self._GmlSvgParameters.append(obj)
def <API key>(self, *GmlSvgParameters):
for obj in GmlSvgParameters:
if self in obj._GmlFills:
obj._GmlFills.remove(self)
self._GmlSvgParameters.remove(obj)
def <API key>(self):
return self._GmlPolygonSymbols
def <API key>(self, value):
for x in self._GmlPolygonSymbols:
x.GmlFill = None
for y in value:
y._GmlFill = self
self._GmlPolygonSymbols = value
GmlPolygonSymbols = property(<API key>, <API key>)
def <API key>(self, *GmlPolygonSymbols):
for obj in GmlPolygonSymbols:
obj.GmlFill = self
def <API key>(self, *GmlPolygonSymbols):
for obj in GmlPolygonSymbols:
obj.GmlFill = None |
- : 1864-261-4639
- Email: ci_knight@msn.cn
- Wechat: ci_knight
- : [](https:
- //1994
- / (``````)
- : 1
- : [blog.ibeats.top](http://blog.ibeats.top)
- Github: [ciknight](https://github.com/ciknight)
- : /
- : (Web)
- : 11k~18k
- : ,,
## () (201412 ~ 20154)
__:__ ,ServerBug,H5..
> ,PythonDjango,.H5api.
uWsgi+Nginx.
> M2M,.DSL,RabbitMQ,Kafka,supervisor
() (20156 ~ )
>
> Server
> ,
- Web: Python/Go/Java
- Web: Django/Tornado/Flask/SpringMVC/SSH
- : Bootstrap/Jquery/AmazeUI
- : npm/node
- : Docker/Ansible/Supervisor/virtualenv
- : Mysql/SqlServer/Oracle/Mongo/redis/Sqlite
- : Git/Svn
- : RabbitMQ/ELK/MVN/tmux/screen/awk/vim/shell/html5/css3/javascript/uWsgi/Elasticsearch/ETCD
- Web
-
- |
C $Header$
C $Name$
C
CBOP
C !ROUTINE: RECIP_DYG_MACROS.h
C !INTERFACE:
C include RECIP_DYG_MACROS.h
C !DESCRIPTION: \bv
C *==========================================================*
C | RECIP_DYG_MACROS.h
C *==========================================================*
C | These macros are used to reduce memory requirement and/or
C | memory references when variables are fixed along a given
C | axis or axes.
C *==========================================================*
C \ev
CEOP
#ifdef RECIP_DYG_CONST
#define _recip_dyG(i,j,bi,bj) recip_dyG(1,1,1,1)
#endif
#ifdef RECIP_DYG_FX
#define _recip_dyG(i,j,bi,bj) recip_dyG(i,1,bi,1)
#endif
#ifdef RECIP_DYG_FY
#define _recip_dyG(i,j,bi,bj) recip_dyG(1,j,1,bj)
#endif
#ifndef _recip_dyG
#define _recip_dyG(i,j,bi,bj) recip_dyG(i,j,bi,bj)
#endif |
package exercise02;
public class Triangle implements Polygon
{
private Point[] vertices;
public Triangle(Point p1, Point p2, Point p3) {
vertices = new Point[] { p1, p2, p3 };
}
@Override
public Point[] allVertexes() {
return vertices;
}
@Override
public double perimeter() {
double sum = 0;
for (int i = 0; i < vertices.length; i++) {
sum += vertices[i].distance(vertices[(i+1)%3]);
}
return sum;
}
@Override
public double area() {
double product = 1;
double s = this.perimeter()/2;
for (int i = 0; i < vertices.length; i++) {
product *= s-vertices[i].distance(vertices[(i+1)%3]);
}
return Math.sqrt(s*product);
}
@Override
public void move(double dx, double dy) {
for (int i = 0; i < vertices.length; i++) {
vertices[i] = vertices[i].moved(dx, dy);
}
}
private void printPoints()
{
for (int i = 0; i < vertices.length; i++)
{
System.out.printf("Point%d: (%.2f;%.2f)\n", i, vertices[i].getX(), vertices[i].getY());
}
}
public static void main(String[] args) {
Triangle t = new Triangle(new Point(1, 2), new Point(3, 4), new Point(1,3));
t.printPoints();
System.out.printf("Umfang: %f\nFläche %f\nBewege um (2|4) ...\n", t.perimeter(), t.area());
t.move(2,4);
t.printPoints();
}
} |
# Joules
# @description: Module for providing circular motion formulas
# Circular motion module (circular_motion.rb)
module Joules
module_function
# @!group Circular Motion Methods
# Calculates the angular velocity given linear velocity and radius.
# @param linear_velocity [Int, Float]
# linear_velocity is in metres per second
# @param radius [Int, Float]
# radius > 0; radius is in metres
# @return [Float]
# return value is in radians per second
# @raise [ZeroDivisionError] if radius = 0
# @example
# Joules.angular_velocity_v1(9, 3) #=> 3.0
# @note There is one other method for calculating angular velocity.
def angular_velocity_v1(linear_velocity, radius)
if radius.zero?
raise ZeroDivisionError.new('divided by 0')
else
return linear_velocity / radius.to_f
end
end
# Calculates the angular velocity given frequency of rotation.
# @param <API key> [Int, Float]
# <API key> >= 0; <API key> is in hertz
# @return [Float]
# return value >= 0; return value is in radians per second
# @example
# Joules.angular_velocity_v2(1.5) #=> 9.42477796076938
# @note There is one other method for calculating angular velocity.
def angular_velocity_v2(<API key>)
return 2 * Math::PI * <API key>
end
# Calculates the angular acceleration given initial angular velocity, final angular velocity, and time.
# @param <API key> [Int, Float]
# <API key> is in radians per second
# @param <API key> [Int, Float]
# <API key> is in radians per second
# @param time [Int, Float]
# time > 0; time is in seconds
# @return [Float]
# return value is in radians per second squared
# @raise [ZeroDivisionError] if time = 0
# @example
# Joules.<API key>(20, 35, 2.4) #=> 6.25
def <API key>(<API key>, <API key>, time)
if time.zero?
raise ZeroDivisionError.new('divided by 0')
else
return (<API key> - <API key>) / time.to_f
end
end
# Calculates the centripetal acceleration given linear velocity and radius.
# @param linear_velocity [Int, Float]
# linear_velocity is in metres per second
# @param radius [Int, Float]
# radius > 0; radius is in metres
# @return [Float]
# return value >= 0; return value is in metres per second squared
# @raise [ZeroDivisionError] if radius = 0
# @example
# Joules.<API key>(9, 3) #=> 27.0
# @note There is one other method for calculating centripetal acceleration.
def <API key>(linear_velocity, radius)
if radius.zero?
raise ZeroDivisionError.new('divided by 0')
else
return (linear_velocity ** 2.0) / radius
end
end
# Calculates the centripetal acceleration given angular velocity and radius.
# @param angular_velocity [Int, Float]
# angular_velocity is in radians per second
# @param radius [Int, Float]
# radius >= 0; radius is in metres
# @return [Float]
# return value >= 0; return value is in metres per second squared
# @example
# Joules.<API key>(3, 3) #=> 27.0
# @note There is one other method for calculating centripetal acceleration.
def <API key>(angular_velocity, radius)
return (angular_velocity ** 2.0) * radius
end
# Calculates the centripetal force given mass, linear velocity, and radius.
# @param mass [Int, Float]
# mass >= 0; mass is in kilograms
# @param linear_velocity [Int, Float]
# linear_velocity is in metres per second
# @param radius [Int, Float]
# radius >= 0; radius is in metres
# @return [Float]
# return value >= 0; return value is in newtons
# @example
# Joules.<API key>(2000, 5.56, 2.1) #=> 29441.523809523802
# @note There is one other method for calculating centripetal force.
def <API key>(mass, linear_velocity, radius)
if radius.zero?
raise ZeroDivisionError.new('divided by 0')
else
return (mass * (linear_velocity ** 2.0)) / radius
end
end
# Calculates the centripetal force given mass, angular velocity, and radius.
# @param mass [Int, Float]
# mass >= 0; mass is in kilograms
# @param angular_velocity [Int, Float]
# angular_velocity is in radians per second
# @param radius [Int, Float]
# radius >= 0; radius is in metres
# @return [Float]
# return value >= 0; return value is in newtons
# @example
# Joules.<API key>(53.5, 3, 3) #=> 1444.5
# @note There is one other method for calculating centripetal force.
def <API key>(mass, angular_velocity, radius)
return mass * (angular_velocity ** 2.0) * radius
end
# Calculates the angular momentum given moment of inertia and angular velocity.
# @param moment_of_inertia [Int, Float]
# moment_of_inertia is in kilogram metres squared
# @param angular_velocity [Int, Float]
# angular_velocity is in radians per second
# @return [Float]
# return value is in kilogram metres squared per second
# @example
# Joules.angular_momentum(2, 2.5) #=> 5.0
def angular_momentum(moment_of_inertia, angular_velocity)
return moment_of_inertia * angular_velocity.to_f
end
# Calculates the angular kinetic energy given moment of inertia and angular velocity.
# @param moment_of_inertia [Int, Float]
# moment_of_inertia is in kilogram metres squared
# @param angular_velocity [Int, Float]
# angular_velocity is in radians per second
# @return [Float]
# return value is in joules
# @example
# Joules.<API key>(5, 2.3) #=> 13.224999999999998
def <API key>(moment_of_inertia, angular_velocity)
return 0.5 * moment_of_inertia * (angular_velocity ** 2)
end
# @!endgroup
end |
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
## [1.3.5]
- Added 'availableToServe' to BackupRecord DTO
- Added 'status' to TCPool profile DTO
- Improved the testing steps used latest `go 1.14` and `go mod`
## [1.3.4] - 2018-01-15
Changed
- Update all references to udnssdk from Ensighten to terra-farm
## [1.3.3] - 2017-12-19
Changed
- Added 'availableToServe' to SBPool and TCPool profile DTOs.
## [1.3.2] - 2017-03-03
Changed
- CheckResponse: improve fallthrough error to include full Response Status and properly format Body
- Client.NewRequest: split query to avoid encoding "?" as "%3F" into path
## [1.3.1] - 2017-03-03
Changed
- Client.NewRequest: shallow-copy BaseURL to avoid retaining modifications
## [1.3.0] - 2017-02-28
Added
- cmd/udns: add rrset query tool
- DPRDataInfo.Type: add field to support API change
## [1.2.1] - 2016-06-13
Fixed
* `omitempty` tags fixed for `ProbeInfoDTO.PoolRecord` & `ProbeInfoDTO.ID`
* Check `*http.Response` values for nil before access
## [1.2.0] - 2016-06-09
Added
* Add probe detail serialization helpers
Changed
* Flatten udnssdk.Response to mere http.Response
* Extract self-contained passwordcredentials oauth2 TokenSource
* Change ProbeTypes to constants
## [1.1.1] - 2016-05-27
Fixed
* remove terraform tag for `GeoInfo.Codes`
## [1.1.0] - 2016-05-27
Added
* Add terraform tags to structs to support mapstructure
Fixed
* `omitempty` tags fixed for `DirPoolProfile.NoResponse`, `DPRDataInfo.GeoInfo`, `DPRDataInfo.IPInfo`, `IPInfo.Ips` & `GeoInfo.Codes`
* ProbeAlertDataDTO equivalence for times with different locations
Changed
* Convert RawProfile to use mapstructure and structs instead of round-tripping through json
* CHANGELOG.md: fix link to v1.0.0 commit history
## [1.0.0] - 2016-05-11
Added
* Support for API endpoints for `RRSets`, `Accounts`, `DirectionalPools`, Traffic Controller Pool `Probes`, `Events`, `Notifications` & `Alerts`
* `Client` wraps common API access including OAuth, deferred tasks and retries
[Unreleased]: https://github.com/Ensighten/udnssdk/compare/v1.3.2...HEAD
[1.3.2]: https://github.com/Ensighten/udnssdk/compare/v1.3.1...v1.3.2
[1.3.1]: https://github.com/Ensighten/udnssdk/compare/v1.3.0...v1.3.1
[1.3.0]: https://github.com/Ensighten/udnssdk/compare/v1.2.1...v1.3.0
[1.2.1]: https://github.com/Ensighten/udnssdk/compare/v1.2.0...v1.2.1
[1.2.0]: https://github.com/Ensighten/udnssdk/compare/v1.1.1...v1.2.0
[1.1.1]: https://github.com/Ensighten/udnssdk/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/Ensighten/udnssdk/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/Ensighten/udnssdk/compare/v0.0.0...v1.0.0 |
import { bookshelfSlugPlugin } from "./../lib/plugin";
import Bookshelf from "bookshelf";
import { PluginSettings } from "./../lib/interfaces";
import chai from "chai";
import { knex } from "./database";
import faker from "faker";
let expect = chai.expect;
const createPostModel = (settings: PluginSettings = {}) => {
let bookshelf = Bookshelf(knex as any);
bookshelf.plugin(bookshelfSlugPlugin(settings));
const Post = bookshelf.model("Post", {
tableName: "post",
requireFetch: false,
slug: ["title", "description"],
});
return Post;
};
describe("bookshelf-slug settings", () => {
describe("generateId option", () => {
it("should append a custom id if slug exists", async () => {
const Post = createPostModel({
generateId() {
return "123abc123";
},
});
const title = faker.lorem.word();
const description = faker.lorem.words(3);
await new Post({
title,
description,
}).save();
const post2 = await new Post({
title,
description,
}).save();
const slug = (post2.get("slug") as string).split("-").slice(-1)[0];
expect(slug).not.null;
expect(slug).equal("123abc123");
});
});
describe("slugify settings", () => {
it("should pass settings to slugify package", async () => {
const Post = createPostModel({
lower: false,
replacement: ";",
remove: /[*+~.()'"!:@]/g,
strict: true,
});
const title = "Title++^^*!'@";
const description = "Apple Orange";
const expectedSlug = "Title;Apple;Orange";
const post = await new Post({
title,
description,
}).save();
expect(post.get("slug")).equal(expectedSlug);
});
});
}); |
layout: default
<div id="home" class="page-content wc-container">
<div class="posts">
{% for post in site.posts limit:10 %}
<div class="post">
<h3 class="post-title">
<a href="{{ post.url | prepend: site.baseurl | prepend: site.url }}">
{{ post.title }}
</a>
</h3>
<p class="post-meta">
{% if (post.categories.size > 0 %}
<span class="categories">
{{ post.categories | <API key> }}
</span> |
{% endif %}
<span class="post-date">
{{ post.date | date: "%b %-d, %Y" }}
</span>
</p>
<h5>{{ post.description}}</h5>
<p>
{{ post.excerpt }}
</p>
<p>
<a href="{{ post.url | prepend: site.baseurl | prepend: site.url }}" title="{{ post.title}}">
Read More
</a>
</p>
</div>
{% endfor %}
</div>
<div class="post-footer">
<div class="column-full"><a href="{{ '/blog' | prepend: site.baseurl | prepend: site.url }}">Blog archive</a></div>
</div>
</div> |
<?php
class Hana_Router
{
protected $project = array();
protected $module = array();
protected $settings = array();
protected $structure = array();
protected $projectSet = array();
protected $params = array();
protected $moduleSet = array();
public function __construct(){
$settings = array();
$settings['dir'] = APP.DIRECTORY_SEPARATOR.'Settings';
$this->settings = $settings;
require($settings['dir'].DIRECTORY_SEPARATOR.'Config.php');
$projects = array();
$projects['dir'] = APP.DIRECTORY_SEPARATOR.'Project';
$dir = new <API key>();
$ds = $dir->setPath($projects['dir'])->scan();
foreach($ds as $key => $names){
if($names['type'] == 'directory'){
$projects['projects'][$names['name']]['dir'] = $names['path'];
$projects['projects'][$names['name']]['parts'] = $names['path'].DIRECTORY_SEPARATOR.'Parts';
$projects['projects'][$names['name']]['layout'] = $names['path'].DIRECTORY_SEPARATOR.'Layout';
Hana_Loader::addPath($names['name'],$names['path']);
}
}
$this->project = $projects;
$module = array();
$module['dir'] = APP.DIRECTORY_SEPARATOR.'Module';
$module['modules'] = array();
$dir = new <API key>();
$ds = $dir->setPath($module['dir'])->scan();
while($ds){
$mod = array_shift($ds);
$module['modules'][$mod['name']] = $mod['path'];
Hana_Loader::addPath($mod['name'],$module['modules'][$mod['name']]);
}
$this->module = $module;
Hana_Loader::addPath('Adapter',APP.DIRECTORY_SEPARATOR.'Adapter');
// var_dump($this);
}
protected function setStructure(){
$st = new Hana_Xml_Structure();
$st->setPath($this->settings['dir'].DIRECTORY_SEPARATOR.'Structure.xml');
$st->init();
return $st;
}
public function init($request){
$structure = $this->setStructure();
$params = $structure->getParams($request->getDefaultUrls());
$projectName = $params['attributes']['project'];
$this->projectSet = $this->project['projects'][$projectName];
if(empty($params['attributes']['joint'])) $params['attributes']['joint'] = null;
if(empty($params['attributes']['direct'])) $params['attributes']['direct'] = null;
if(empty($params['target']['meta'])) $params['target']['meta'] = array('title'=>null,'description'=>null,'keyword'=>null);
$this->params = $params;
// var_dump($params);
}
public function getParams(){
return $this->params;
}
public function setParams($params){
$this->params = $params;
}
public function getMeta(){
return $this->params['target']['meta'];
}
public function getSet(){
$hooks = array();
$hs = array();
$prjSet = $this->projectSet;
$this->params['attributes']['project'];
$settingPath = $prjSet['dir'].DIRECTORY_SEPARATOR.'Setting'.DIRECTORY_SEPARATOR.'Main.php';
if(file_exists($settingPath)){
return array('name'=>'Main','path'=>$settingPath);
}else{
return array();
}
}
public function getExceptionSet(){
$params = $this->params;
return array(
'name' => $params['attributes']['exception'],
'path' => $this->projectSet['parts'].DIRECTORY_SEPARATOR.$params['attributes']['exception'].'.php'
);
}
public function getLayoutSet(){
$layout = $this->params['attributes']['layout'];
$frame = $this->params['attributes']['frame'];
return array(
'name' => $layout,
'dir' => $this->projectSet['layout'].DIRECTORY_SEPARATOR.$layout.DIRECTORY_SEPARATOR.'Frame',
'path' => $this->projectSet['layout'].DIRECTORY_SEPARATOR.$layout.DIRECTORY_SEPARATOR.'Frame'.DIRECTORY_SEPARATOR.$frame.'.php',
);
}
public function getControlSet(){
$res = array();
$params = $this->params;
$projectName = $params['attributes']['project'];
$prjSet = $this->projectSet;
$moduleData = !empty($params['attributes']['joint']) ? $params['attributes']['joint'] : $params['attributes']['direct'];
if(array_key_exists($moduleData['name'],$this->module['modules'])){
$directories = $moduleData['urls']['directories'] ? join('_',$moduleData['urls']['directories']) : 'Index';
$ds = $moduleData['urls']['directories'] ? join(DIRECTORY_SEPARATOR,$moduleData['urls']['directories']) : 'Index';
if(isset($params['target']['params'])){
$params = $params['target']['params'];
}else{
if(isset($params['path_nodes'])){
$last = end($params['path_nodes']);
$ps = $last['params'];
}else{
$ps = array();
}
}
return array(
'project' => $projectName,
'module'=>$moduleData['name'],
'name' => $directories,
'path' => $this->module['modules'][$moduleData['name']].DIRECTORY_SEPARATOR.'Controller'.DIRECTORY_SEPARATOR.$ds.'Controller.php',
'action' => $moduleData['urls']['file'],
'params' => $ps,
'data' => $moduleData['data']
);
}else{
// var_dump($params['project_root']);
if(!empty($params['project_root'])){
$directories = $params['project_root'];
if($directories[0] == $params['attributes']['project']) array_shift($directories);
}else{
$directories = $params['urls']['directories'];
}
$ds = $directories ? join('_',$directories) : 'Index';
if(!$directories) $directories[] = 'Index';
$directories = $directories ? join(DIRECTORY_SEPARATOR,$directories) : 'Index';
$pm = empty($params['target']['params']) ? array() : $params['target']['params'];
return array(
'project' => $projectName,
'name' => $ds,
'path' => $prjSet['dir'].DIRECTORY_SEPARATOR.'Controller'.DIRECTORY_SEPARATOR.$directories.'Controller.php',
'action' => $params['urls']['file'],
'params' => $pm,
'data' => array()
);
}
}
public function getViewSet(){
$params = $this->params;
$prjSet = $this->projectSet;
$moduleData = !empty($params['attributes']['joint']) ? $params['attributes']['joint'] : $params['attributes']['direct'];
if(!$moduleData){
if(!empty($params['project_root'])){
$directories = $params['project_root'];
if($directories[0] == $params['attributes']['project']) array_shift($directories);
}else{
$directories = $params['urls']['directories'];
}
$dss = $directories ? join(DIRECTORY_SEPARATOR,$directories).DIRECTORY_SEPARATOR : null;
return array(
'name' => $params['urls']['file'],
'path' => $prjSet['dir'].DIRECTORY_SEPARATOR.'View'.DIRECTORY_SEPARATOR.$dss.$params['urls']['file'].'.php',
);
}else{
if(array_key_exists($moduleData['name'],$this->module['modules'])){
$dss = $moduleData['urls']['directories'] ? join(DIRECTORY_SEPARATOR,$moduleData['urls']['directories']).DIRECTORY_SEPARATOR : null;
return array(
'name' => $moduleData['urls']['file'],
'path' => $this->module['modules'][$moduleData['name']].DIRECTORY_SEPARATOR.'View'.DIRECTORY_SEPARATOR.$dss.$moduleData['urls']['file'].'.php'
);
}else{
return array();
}
}
}
public function getThemeSet(){
$theme = $this->params['attributes']['theme'];
return array(
'name' => $theme,
'dir' => ROOT.DIRECTORY_SEPARATOR.'src'.DIRECTORY_SEPARATOR.'theme'.DIRECTORY_SEPARATOR.$theme,
'url' => BASE.'src/theme/'.$theme.'/'
);
}
public function getOutlineSet(){
$outline = $this->params['attributes']['outline'];
$layout = $this->params['attributes']['layout'];
$res = array(
'name' => $outline,
'dir' => $this->projectSet['layout'].DIRECTORY_SEPARATOR.$layout.DIRECTORY_SEPARATOR.'Outline',
'path' => $this->projectSet['layout'].DIRECTORY_SEPARATOR.$layout.DIRECTORY_SEPARATOR.'Outline'.DIRECTORY_SEPARATOR.$outline.'.xml'
);
$outlineReader = new Hana_Xml_Outline();
$outlineReader->setPath($res['path']);
$outlineReader->init();
$res['outlines'] = $outlineReader->getData();
return $res;
}
public function getPartsSet(){
return array(
'dir' => $this->projectSet['parts']
);
}
public function setModuleSet($moduleName){
$this->moduleSet['dir'] = $this->module['modules'][$moduleName];
$this->moduleSet['name'] = $moduleName;
}
public function getModuleControlSet($urls){
$moduleName = $this->moduleSet['name'];
$res = array();
$ds = $urls['directories'];
if(empty($ds)) $ds = array('Index');
return array(
'path'=>$this->moduleSet['dir'].DIRECTORY_SEPARATOR.'Controller'.DIRECTORY_SEPARATOR.join('_',$ds).'Controller.php',
'name'=>join('_',$ds),
'action'=>$urls['file']
);
}
public function getModuleViewSet($urls){
$moduleName = $this->moduleSet['name'];
$vd = empty($urls['directories']) ? null : DIRECTORY_SEPARATOR.join(DIRECTORY_SEPARATOR,$urls['directories']);
return array(
'path'=>$this->moduleSet['dir'].DIRECTORY_SEPARATOR.'View'.$vd.DIRECTORY_SEPARATOR.$urls['file'].'.php'
);
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
div {
width: 200px;
height: 200px;
background-color: #58a;
}
</style>
</head>
<body>
<div id="ad">
</div>
<script>
// 1 div
let ad = document.getElementById('ad');
/*
ad.onclick = () => {
console.log(this);
this.style.backgroundColor = 'pink';
};
*/
ad.addEventListener('click', function() {
setTimeout(() => {
console.log(this);
this.style.backgroundColor = 'pink';
}, 2000);
});
let arr = [1, 2, 3, 4, 5];
let res = arr.filter(item => item % 2 === 0);
console.log(res);
// this
</script>
</body>
</html> |
<?php
declare(strict_types=1);
namespace Windwalker\Utilities\Cache;
/**
* The RuntimeCacheTrait class.
*/
trait RuntimeCacheTrait
{
protected static array $cacheStorage = [];
protected static function cacheGet(string $id)
{
return static::$cacheStorage[$id] ?? null;
}
protected static function cacheSet(string $id, $value = null): void
{
static::$cacheStorage[$id] = $value;
}
protected static function cacheHas(string $id): bool
{
return isset(static::$cacheStorage[$id]);
}
public static function cacheRemove(string $id): static
{
unset(static::$cacheStorage[$id]);
}
public static function cacheReset(): void
{
static::$cacheStorage = [];
}
protected static function once(?string $id, callable $closure, bool $refresh = false)
{
if ($refresh) {
unset(static::$cacheStorage[$id]);
}
return static::$cacheStorage[$id] ??= $closure();
}
} |
[ of scanners and parsers doesn't belong to the actual
process of compilation.
Using macros, the generation of the scanners and parsers can be achieved via meta-programming.
Thus, the disadvantage will disappear.
Macrowave allows to define a parsing expression grammar, which gets transformed into a regular automaton for
tokenization and a table driven LALR(1)-parser.
## Building macrowave
The project macrowave is built with [SBT] 0.13.12 or later and its master branch with [Scala] 2.11.8.
To build the project:
- Install [SBT] and [Scala].
- Clone this project and `cd` into the root directory of the cloned repository.
- Run
- `sbt compile` to build the project
- `sbt test` to run the unit tests
## Using macrowave
- TODO: Nothing to use, yet!
## Trivia
The name "macrowave" is obviously a play on "macros" and "microwave".
## Authors
- [keddelzz](https://github.com/keddelzz)
- [kuchenkruste](https://github.com/kuchenkruste)
[Bison]: http://dinosaur.compilertools.net/bison/
[Flex]: http://dinosaur.compilertools.net/flex/
[Lex]: http://dinosaur.compilertools.net/lex/
[SBT]: http:
[Scala]: https:
[YACC]: http://dinosaur.compilertools.net/yacc/ |
package com.azure.spring.integration.eventhub.impl;
import com.azure.spring.cloud.context.core.util.Tuple;
import com.azure.spring.integration.core.api.PartitionSupplier;
import com.azure.spring.integration.eventhub.api.<API key>;
import com.azure.spring.integration.eventhub.api.EventHubRxOperation;
import org.springframework.messaging.Message;
import reactor.core.publisher.Mono;
import rx.Observable;
import rx.subscriptions.Subscriptions;
import java.util.concurrent.ConcurrentHashMap;
/**
* Default implementation of {@link EventHubRxOperation}.
*
* @author Warren Zhu
* @author Xiaolu Dai
*
* @deprecated {@link rx} API will be dropped in version 4.x, please migrate to reactor API in
* {@link EventHubTemplate}. From version 4.0.0, the reactor API support will be moved to
* com.azure.spring.eventhubs.core.EventHubTemplate.
*/
@Deprecated
public class EventHubRxTemplate extends <API key> implements EventHubRxOperation {
private final ConcurrentHashMap<Tuple<String, String>, Observable<Message<?>>> <API key> =
new ConcurrentHashMap<>();
public EventHubRxTemplate(<API key> clientFactory) {
super(clientFactory);
}
private static <T> Observable<T> toObservable(Mono<T> mono) {
return Observable.create(subscriber -> mono.toFuture().whenComplete((result, error) -> {
if (error != null) {
subscriber.onError(error);
} else {
subscriber.onNext(result);
subscriber.onCompleted();
}
}));
}
@Override
public <T> Observable<Void> sendRx(String destination, Message<T> message, PartitionSupplier partitionSupplier) {
return toObservable(sendAsync(destination, message, partitionSupplier));
}
@Override
public Observable<Message<?>> subscribe(String destination, String consumerGroup, Class<?> messagePayloadType) {
Tuple<String, String> <API key> = Tuple.of(destination, consumerGroup);
<API key>.computeIfAbsent(<API key>, k -> Observable.<Message<?>>create(subscriber -> {
final EventHubProcessor eventHubProcessor = new EventHubProcessor(subscriber::onNext, subscriber::onError,
messagePayloadType, getCheckpointConfig(), getMessageConverter());
this.<API key>(destination, consumerGroup, eventHubProcessor);
this.<API key>(destination, consumerGroup);
subscriber.add(Subscriptions.create(() -> this.<API key>(destination, consumerGroup)));
}).share());
return <API key>.get(<API key>);
}
} |
'use strict';
// imports
import { Component, EventEmitter, Input, Output } from '@angular/core';
import {Device} from './../util/device.class';
import {LatLng} from './../core/latlng.model';
import {LocationService} from './../locationsearch/location.service';
import {preferences} from './../app.module';
import {Stop} from './../core/stop.model';
declare let Modernizr: any; // import global so ts compiler doesn't complain
//import * as _ from 'lodash'; // works in dev but breaks the build
import {htmlTemplate} from './journey-search.component.html'; // include template in compiled bundle; external html may cause extra http request
//import htmlTemplate: string from './journey-search.component.html'; // no need for ts literal when ts compiler catches up
import {styles} from './journey-search.component.css'; // include template in compiled bundle; external html may cause extra http request
//import styles: string from './progress-indicator.component.html'; // no need for ts literal when ts compiler catches up
/**@classdesc Manages display of, and user interaction with, the search form in the Journey Planner view.
* Enables user to enter journey search terms and submit the search.
*/
@Component({
selector: 'journey-search',
template: htmlTemplate,
//templateUrl: './journeyplanner/journey-search.component.html', // ngc compiler disagrees with dev module loader about path here, so using import instead
styles: styles,
//styleUrls: ['./journeyplanner/journey-search.component.css'],
viewProviders: [],
providers: [Device, LocationService]
})
/** @classdesc Manages journey search form.
* Expects to be embedded in containing component taking care of
* search execution and presentation of search results
*/
export class <API key> {
// attributes
@Input() public date: any = null;
public datetime: string = '';
@Input() public destination: any = null;
public destinationId: string = '';
public <API key>: any = null; // [{id: '14', name:'Test Destination', x: 1, y: 2}];
@Input() public origin: any = null;
public originId: string = '';
public originSuggestions: any = null; // = [{id: '12', name:'Test Origin', x: 1, y: 2}];
public time: string;
public Modernizr: any = Modernizr; // workaround: can't figure out how to 'import' library in global scope (tried, failed!)
@Output() onFindJourney = new EventEmitter<any>(); // call parent component on submit
public valid: boolean = false;
// workaround until I out figure out how to use lodash without breaking the build
private _padStart(string: string, length: number, chars: string): string {
while (string.length < length) {string = chars + string;}
return string;
}
public constructor(
public device: Device, private _service: LocationService) {
}
// operations
/* Converts date into string format agreeable to vaading-date-picker */
private _formatDate(date: Date): string {
return date.getFullYear()
+ '-'
+ this._padStart(String(date.getMonth() + 1), 2, '0')
+ '-'
+ this._padStart(String(date.getDate()), 2, '0');
}
/* Converts date into string format agreeable to native datetime-local widgets */
private _formatDateTime(date: Date): string {
return date.getFullYear() // Native datetime-locals require an ISO 8601 string with no trailing 'Z'
+ '-'
+ this._padStart(String(date.getMonth() + 1), 2, '0')
+ '-'
+ this._padStart(String(date.getDate()), 2, '0')
+ 'T'
+ this._padStart(String(date.getHours()), 2, '0')
+ ':'
+ this._padStart(String(date.getMinutes() + 1), 2, '0');
}
/* Converts date into 24h time string */
private _formatTime(date: Date): string {
return this._padStart(String(date.getHours()), 2, '0') // 'hh:mm' (24h)
+ ':'
+ this._padStart(String(date.getMinutes() + 1), 2, '0');
}
/** Populates locations list for autocomplete in from/to (i.e. origin/destination) input fields */
public fetchLocations(query: string, target: string) {
let suggestions: any = [];
this._service.fetchLocations(query)
.then((result: Stop[]) => {
// Flatten object model into json object array required by vaadin-combo-box
if (result.forEach) { // service did not come up empty
result.forEach((stop) => {
suggestions.push(stop.toJSON());
});
}
if (target.toLowerCase() === 'origin') {
this.originSuggestions = suggestions;
}
else {
this.<API key> = suggestions;
}
})
.catch((e: Error) => {
// Maybe later collect frequently used stations for offline use;
// but for now, just show a brief error message when search fails
let toast: any = document.getElementById('<API key>');
toast.show({duration: preferences.<API key>});
console.log(e);
})
}
/** Converts any data updated by parent component to formats required by UI widgets */
public ngOnChanges(changes: any) {
void changes; // keep ngc build compiler happy; no actual need for changes object here
this.origin = this.origin && this.origin.toJSON ? this.origin.toJSON() : null;
if (this.origin) {
this.originId = this.origin._modelId;
this.originSuggestions = [this.origin];
}
this.destination = this.destination && this.destination.toJSON ? this.destination.toJSON() : null;
if (this.destination) {
this.destinationId = this.destination._modelId;
this.<API key> = [this.destination];
}
if (this.date && this.date instanceof Date) {
this.datetime = this._formatDateTime(this.date);
this.time = this._formatTime(this.date);
this.date = this._formatDate(this.date);
}
}
/** Sets date/time defaults on initial load
* - using device date and time as if they were in local API time zone
*/
public ngOnInit() {
let now: Date = new Date();
this.datetime = this._formatDateTime(now);
this.date = this._formatDate(now); // vaadin picker expects 'yyyy-mm-dd'
this.time = this._formatTime(now);
}
/** Captures user selection in vaadin-date-picker (can't get regular binding to work) */
public onDateChange(event: any): void {
if (event && event.srcElement.date && event.srcElement.date.constructor === Date) {
this.date = this._formatDate(event.srcElement.date);
}
}
/** Captures updates to component data when entries are made/deleted in from/to fields */
public onFromToChange(event: any) {
this[event.target.name] = event.detail.value;
this.valid = this.origin !== null && this.destination !== null;
}
/** Fetches from/to autocomplete suggestions in response to user entries into from/to fields */
public onFromToKeyUp(event: any) {
let query: string = event.target.value;
let target = event.target.name;
if (query.length < 4) { // clear for new entry
this[target + 'Suggestions'] = [];
}
else if (this[target + 'Suggestions'].length === 0) { // call location service, if needed
this.fetchLocations(query, target);
}
// else do nothing: repeated updates obscure suggestions from users
}
/** Executes location search */
public onSearch() {
let now: Date = new Date();
// parses entry in datepicker into ISO date format ('YYYY-MM-DD', with leading zeroes)
function _parseDate(date: string): string {
// value from vaadin date picker is already formatted correctly, so should normally pass the check
return !isNaN(Date.parse(date)) ? date : now.toISOString().split('T')[0];
}
// parses entry in time input into ISO time format ('mm:hh:ss', with leading zeroes)
function _parseTime(time: any): string {
let isPM: boolean = time.toLowerCase().indexOf('pm') > -1;
time = time.replace(/\D/g, '').split(''); // strip non-digits, get array of single characters
let hours: string = (time[time.length-4] !== undefined ? time[time.length-4] : '0' ) // tens of hours
+ (time[time.length-3] !== undefined ? time[time.length-3] : '0' ) // single hours
hours = isPM ? String(Number(hours) + 12) : hours; // adjust for pm
time = !time.length ? now.toTimeString().split(' ')[0] : // use current time if no input
String(hours) + ':' // 24h hours
+ (time[time.length-2] ? time[time.length-2] : '0' ) // tens of minutes
+ (time[time.length-1] ? time[time.length-1] : '0' ) // single minutes
+ ':00'; //seconds
return time;
}
let origin = (!this.origin) ? undefined : new Stop(
this.origin._apiId,
this.origin._name,
new LatLng(this.origin._location._lat, this.origin._location._lng)
);
let destination = (!this.destination) ? undefined : new Stop(
this.destination._apiId,
this.destination._name,
new LatLng(this.destination._location._lat, this.destination._location._lng)
);
let date: Date;
if (document.getElementById('datetime')) { // default to datetime-local value when available
date = !isNaN(Date.parse(this.datetime)) ? new Date(this.datetime) : now; // cast to Date, or default to now
}
else { // use fallback (string parsing could be unreliable, but seems to work)
this.datetime = _parseDate(this.date) + 'T' + _parseTime(this.time) + 'Z'; // parse date and time entries
date = !isNaN(Date.parse(this.datetime)) ? new Date(this.datetime) : now; // cast to UTC Date, or default to now
}
void date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); // adjust for timezone offset
this.onFindJourney.emit({origin: origin, destination: destination, date: date}); // pass entries to parent component
}
} |
package at.rags.morpheus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import at.rags.morpheus.Exceptions.<API key>;
import at.rags.morpheus.TestResources.Article;
import at.rags.morpheus.TestResources.Author;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MapperUnitTest {
private Mapper mapper;
private Mapper newMapper;
private Deserializer mockDeserializer;
private Serializer mockSerializer;
private AttributeMapper mockAttributeMapper;
@Before
public void setup() {
mapper = new Mapper();
Deserializer.<API key>(new HashMap<String, Class>());
mockDeserializer = Mockito.mock(Deserializer.class);
mockSerializer = Mockito.mock(Serializer.class);
mockAttributeMapper = Mockito.mock(AttributeMapper.class);
newMapper = new Mapper(mockDeserializer, mockSerializer, mockAttributeMapper);
}
@Test
public void testInit() throws Exception {
Mapper mapper = new Mapper();
assertNotNull(mapper);
}
@Test
public void testMapLinks() throws Exception {
JSONObject jsonObject = mock(JSONObject.class);
when(jsonObject.getString("self")).thenReturn("www.self.com");
when(jsonObject.getString("related")).thenReturn("www.related.com");
when(jsonObject.getString("first")).thenReturn("www.first.com");
when(jsonObject.getString("last")).thenReturn("www.last.com");
when(jsonObject.getString("prev")).thenReturn("www.prev.com");
when(jsonObject.getString("next")).thenReturn("www.next.com");
Links links = mapper.mapLinks(jsonObject);
assertTrue(links.getSelfLink().equals("www.self.com"));
assertTrue(links.getRelated().equals("www.related.com"));
assertTrue(links.getFirst().equals("www.first.com"));
assertTrue(links.getLast().equals("www.last.com"));
assertTrue(links.getPrev().equals("www.prev.com"));
assertTrue(links.getNext().equals("www.next.com"));
}
@Test
public void <API key>() throws Exception {
JSONObject jsonObject = mock(JSONObject.class);
when(jsonObject.getString("self")).thenThrow(new JSONException(""));
when(jsonObject.getString("related")).thenThrow(new JSONException(""));
when(jsonObject.getString("first")).thenThrow(new JSONException(""));
when(jsonObject.getString("last")).thenThrow(new JSONException(""));
when(jsonObject.getString("prev")).thenThrow(new JSONException(""));
when(jsonObject.getString("next")).thenThrow(new JSONException(""));
Links links = mapper.mapLinks(jsonObject);
assertNull(links.getSelfLink());
assertNull(links.getRelated());
assertNull(links.getFirst());
assertNull(links.getLast());
assertNull(links.getPrev());
assertNull(links.getNext());
}
@Test
public void testMapId() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer, null, null);
JSONObject jsonObject = mock(JSONObject.class);
Resource resource = new Resource();
resource.setId("123456");
when(mockDeserializer.
setIdField(Matchers.<Resource>anyObject(), anyObject()))
.thenReturn(resource);
resource = mapper.mapId(resource, jsonObject);
assertTrue(resource.getId().equals("123456"));
}
@Test(expected = <API key>.class)
public void <API key>() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer, null, null);
JSONObject jsonObject = mock(JSONObject.class);
Resource resource = new Resource();
when(mockDeserializer.
setIdField(Matchers.<Resource>anyObject(), anyObject()))
.thenThrow(new <API key>(""));
resource = mapper.mapId(resource, jsonObject);
}
@Test
public void <API key>() throws Exception {
JSONObject jsonObject = mock(JSONObject.class);
Resource resource = new Resource();
when(jsonObject.get(anyString())).thenThrow(new JSONException(""));
resource = mapper.mapId(resource, jsonObject);
assertNull(resource.getId());
}
@Test
public void <API key>() throws Exception {
JSONObject jsonObject = mock(JSONObject.class);
JSONArray jsonArray = mock(JSONArray.class);
AttributeMapper mockAttributeMapper = mock(AttributeMapper.class);
Mapper mapper = new Mapper(new Deserializer(), new Serializer(), mockAttributeMapper);
Article article = new Article();
article.setId("1");
mapper.mapAttributes(article, jsonObject);
ArgumentCaptor<Field> fieldArgumentCaptor = ArgumentCaptor.forClass(Field.class);
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), any(Field.class), eq("title"));
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), fieldArgumentCaptor.capture(), eq("public"));
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), any(Field.class), eq("tags"));
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), any(Field.class), eq("map"));
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), any(Field.class), eq("version"));
verify(mockAttributeMapper).<API key>(Matchers.<Resource>anyObject(),
any(JSONObject.class), any(Field.class), eq("price"));
assertEquals(fieldArgumentCaptor.getValue().getName(), "publicStatus");
}
@Test
public void <API key>() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer, null, null);
JSONObject jsonObject = mock(JSONObject.class);
List<Resource> mockIncluded = mock(List.class);
when(jsonObject.getJSONObject(anyString())).thenThrow(new JSONException(""));
Article article = new Article();
mapper.mapRelations(article, jsonObject, mockIncluded);
assertNull(article.getAuthor());
}
@Test
public void <API key>() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer, null, null);
Factory.setDeserializer(mockDeserializer);
Factory.setMapper(mapper);
JSONObject jsonObject = mock(JSONObject.class);
JSONObject relationObject = mock(JSONObject.class);
JSONObject authorObject = mock(JSONObject.class);
List<Resource> included = new ArrayList<>();
Author includedAuthor = new Author();
includedAuthor.setId("1");
includedAuthor.setName("James");
included.add(includedAuthor);
Author author = new Author();
author.setId("1");
when(mockDeserializer.<API key>(anyString())).thenReturn(author);
when(jsonObject.getJSONObject(eq("author"))).thenReturn(relationObject);
when(jsonObject.getJSONObject(eq("authors"))).thenThrow(new JSONException(""));
when(relationObject.getJSONObject(anyString())).thenReturn(authorObject);
when(relationObject.getJSONArray(anyString())).thenThrow(new JSONException(""));
when(authorObject.getString("type")).thenReturn("author");
when(authorObject.getJSONObject("links")).thenReturn(new JSONObject());
when(mockDeserializer.setIdField(Matchers.<Resource>anyObject(),
any(JSONObject.class))).thenReturn(author);
Article article = new Article();
Article mappedArticle = (Article)mapper.mapRelations(article, jsonObject, included);
ArgumentCaptor<Object> <API key> = ArgumentCaptor.forClass(Object.class);
verify(mockDeserializer).setField(Matchers.<Resource>anyObject(), eq("author"), <API key>.capture());
Author resultAuthor = (Author)<API key>.getValue();
assertEquals(resultAuthor.getId(), "1");
assertEquals(resultAuthor.getName(), "James");
}
@Test
public void <API key>() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer, null, null);
Factory.setDeserializer(mockDeserializer);
Factory.setMapper(mapper);
JSONObject jsonObject = mock(JSONObject.class);
JSONObject relationObject = mock(JSONObject.class);
JSONObject authorObject = mock(JSONObject.class);
Author author = new Author();
author.setId("1");
author.setName("Name");
when(mockDeserializer.<API key>(anyString())).thenReturn(author);
when(jsonObject.getJSONObject(eq("author"))).thenReturn(relationObject);
when(jsonObject.getJSONObject(eq("authors"))).thenThrow(new JSONException(""));
when(relationObject.getJSONObject(anyString())).thenReturn(authorObject);
when(relationObject.getJSONArray(anyString())).thenThrow(new JSONException(""));
when(authorObject.getString("type")).thenReturn("author");
when(authorObject.getJSONObject("links")).thenReturn(new JSONObject());
when(mockDeserializer.setIdField(Matchers.<Resource>anyObject(),
any(JSONObject.class))).thenReturn(author);
Article article = new Article();
Article mappedArticle = (Article)mapper.mapRelations(article, jsonObject, null);
ArgumentCaptor<Object> <API key> = ArgumentCaptor.forClass(Object.class);
verify(mockDeserializer).setField(Matchers.<Resource>anyObject(), eq("author"), <API key>.capture());
Author resultAuthor = (Author)<API key>.getValue();
assertEquals(resultAuthor.getId(), "1");
assertEquals(resultAuthor.getName(), "Name");
assertNotNull(mappedArticle);
}
@Test
public void <API key>() throws Exception {
Deserializer mockDeserializer = mock(Deserializer.class);
Mapper mapper = new Mapper(mockDeserializer,null, null);
Factory.setDeserializer(mockDeserializer);
Factory.setMapper(mapper);
JSONObject jsonObject = mock(JSONObject.class);
JSONObject relationObject = mock(JSONObject.class);
JSONArray authorObjects = mock(JSONArray.class);
JSONObject authorObject = mock(JSONObject.class);
List<Resource> included = new ArrayList<>();
Author includedAuthor = new Author();
includedAuthor.setId("1");
includedAuthor.setName("James");
included.add(includedAuthor);
Author author1 = new Author();
author1.setId("1");
Author author2 = new Author();
author2.setId("2");
when(mockDeserializer.<API key>(anyString())).thenReturn(author1);
when(jsonObject.getJSONObject(anyString())).thenReturn(relationObject);
when(relationObject.getJSONArray(anyString())).thenReturn(authorObjects);
when(relationObject.getJSONObject(anyString())).thenThrow(new JSONException(""));
when(authorObjects.length()).thenReturn(2);
when(authorObjects.getJSONObject(0)).thenReturn(authorObject);
when(authorObjects.getJSONObject(1)).thenReturn(authorObject);
when(authorObject.getJSONObject("links")).thenReturn(new JSONObject());
when(mockDeserializer.setIdField(Matchers.<Resource>anyObject(),
any(JSONObject.class))).thenReturn(author1);
Article article = new Article();
Article mappedArticle = (Article)mapper.mapRelations(article, jsonObject, included);
ArgumentCaptor<List> <API key> = ArgumentCaptor.forClass(List.class);
verify(mockDeserializer).setField(Matchers.<Resource>anyObject(), eq("authors"), <API key>.capture());
Author resultAuthor = (Author)<API key>.getValue().get(0);
assertEquals(resultAuthor.getId(), "1");
assertEquals(resultAuthor.getName(), "James");
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Author author = new Author();
author.setId("id");
author.setName("name");
ArrayList<Author> authors = new ArrayList<>();
authors.add(author);
authors.add(author);
HashMap<String, Object> authorMap = new HashMap<>();
authorMap.put("id","id");
authorMap.put("type", "authors");
authorMap.put("attributes", mapper.getSerializer().<API key>(author));
ArrayList<HashMap<String, Object>> dataArray = new ArrayList<>();
dataArray.add(authorMap);
dataArray.add(authorMap);
ArrayList<HashMap<String, Object>> output = mapper
.createData((List)authors, true);
assertNotNull(output);
assertEquals(output.toString(), dataArray.toString());
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Author author = new Author();
author.setId("id");
author.setName("name");
HashMap<String, Object> authorMap = new HashMap<>();
authorMap.put("id","id");
authorMap.put("type", "authors");
authorMap.put("attributes", mapper.getSerializer().<API key>(author));
HashMap<String, Object> output = mapper
.createData(author, true);
assertNotNull(output);
assertEquals(3, output.size());
assertEquals(output.toString(), authorMap.toString());
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Author author = new Author();
author.setId("id");
author.setName("name");
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
article.setPrice(1.0);
article.setPublicStatus(true);
article.setMap(null);
article.setVersion(10);
article.setTags(null);
article.setAuthor(author);
HashMap<String, Object> relationDataMap = new HashMap<>();
relationDataMap.put("data", mapper.createData(author, false));
HashMap<String, Object> relationMap = new HashMap<>();
relationMap.put("author", relationDataMap);
HashMap<String, Object> articleMap = new HashMap<>();
articleMap.put("id","articleId");
articleMap.put("type", "articles");
articleMap.put("attributes", mapper.getSerializer().<API key>(article));
articleMap.put("relationships", relationMap);
HashMap<String, Object> output = mapper
.createData(article, true);
assertNotNull(output);
assertEquals(output.toString(), articleMap.toString());
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Author author = new Author();
author.setId("id");
Links links = new Links();
links.setSelfLink("self.com");
links.setRelated("related.com");
author.setLinks(links);
HashMap<String, Object> linkMap = new HashMap<>();
linkMap.put("self", "self.com");
linkMap.put("related", "related.com");
HashMap<String, Object> authorMap = new HashMap<>();
authorMap.put("id","id");
authorMap.put("type", "authors");
authorMap.put("links", linkMap);
HashMap<String, Object> output = mapper
.createData(author, true);
assertNotNull(output);
assertEquals(authorMap.toString(), output.toString());
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Author author = new Author();
author.setId("authorId");
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
article.setAuthor(author);
HashMap<String, Object> authorMap = new HashMap<>();
HashMap<String, Object> relationDataMap = new HashMap<>();
relationDataMap.put("data", mapper.createData(author, false));
authorMap.put("author", relationDataMap);
HashMap<String, Object> output = mapper.createRelationships(article);
assertNotNull(output);
assertEquals(authorMap.toString(), output.toString());
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
HashMap<String, Object> output = mapper.createRelationships(article);
assertEquals(null, output);
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Author author = new Author();
author.setId("authorId");
author.setName("Hans");
ArrayList<Author> authors = new ArrayList<>();
authors.add(author);
authors.add(author);
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
article.setAuthor(author);
article.setAuthors(authors);
ArrayList<Resource> articles = new ArrayList<>();
articles.add(article);
articles.add(article);
HashMap<String, Object> relationships = new HashMap<>();
relationships.put("author", author);
Mockito.stub(mockSerializer.<API key>(eq(author))).toReturn(null);
Mockito.stub(mockSerializer.getRelationships(eq(article))).toReturn(relationships);
ArrayList<HashMap<String, Object>> data = newMapper.createData(articles, false);
HashMap<String, Object> relationshipsMap =
(HashMap<String, Object>) data.get(0).get("relationships");
HashMap<String, Object> authorMap = (HashMap<String, Object>) relationshipsMap.get("author");
HashMap<String, Object> authorData =
(HashMap<String, Object>) authorMap.get("data");
assertNotNull(data);
assertNotNull(data.get(0).get("relationships"));
assertNotNull(relationshipsMap.get("author"));
assertNotNull(authorMap);
assertNotNull(authorData);
assertEquals(2, authorData.size());
assertEquals("authors", authorData.get("type"));
assertEquals("authorId", authorData.get("id"));
}
@Test
public void <API key>() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Author author = new Author();
author.setId("authorId");
author.setName("Hans");
ArrayList<Author> authors = new ArrayList<>();
authors.add(author);
authors.add(author);
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
article.setAuthor(author);
article.setAuthors(authors);
ArrayList<Resource> articles = new ArrayList<>();
articles.add(article);
articles.add(article);
HashMap<String, Object> relationships = new HashMap<>();
relationships.put("author", author);
relationships.put("authors", authors);
article.<API key>("author");
article.<API key>("authors");
Mockito.stub(mockSerializer.<API key>(eq(author))).toReturn(null);
Mockito.stub(mockSerializer.getRelationships(eq(article))).toReturn(relationships);
ArrayList<HashMap<String, Object>> data = newMapper.createData(articles, false);
HashMap<String, Object> relationshipsMap =
(HashMap<String, Object>) data.get(0).get("relationships");
assertNotNull(data);
assertNotNull(data.get(0).get("relationships"));
HashMap<String, Object> authorData = (HashMap<String, Object>) relationshipsMap.get("author");
assertNull(authorData.get("data"));
HashMap<String, Object> relationAuthors = (HashMap<String, Object>) relationshipsMap.get("authors");
ArrayList<Object> relationData = (ArrayList<Object>) relationAuthors.get("data");
assertEquals(0, relationData.size());
}
@Test
public void <API key>() {
HashMap<String, Object> checkLinks = new HashMap<>();
checkLinks.put("self", "selflink.com");
checkLinks.put("related", "related.com");
checkLinks.put("first", "first.com");
checkLinks.put("last", "last.com");
checkLinks.put("prev", "prev.com");
checkLinks.put("next", "next.com");
checkLinks.put("about", "about.com");
Resource resource = new Resource();
Links links = new Links();
links.setSelfLink("selflink.com");
links.setRelated("related.com");
links.setFirst("first.com");
links.setLast("last.com");
links.setPrev("prev.com");
links.setNext("next.com");
links.setAbout("about.com");
resource.setLinks(links);
HashMap<String, Object> linksFromResource =
mapper.createLinks(resource);
assertEquals(linksFromResource, checkLinks);
}
@Test
public void testCreateIncluded() {
Deserializer.<API key>("authors", Author.class);
Deserializer.<API key>("articles", Article.class);
Author author = new Author();
author.setId("authorId");
author.setName("Hans");
ArrayList<Author> authors = new ArrayList<>();
authors.add(author);
authors.add(author);
Article article = new Article();
article.setId("articleId");
article.setTitle("Some title");
article.setAuthor(author);
article.setAuthors(authors);
HashMap<String, Object> relations = new HashMap<>();
relations.put("author", author);
relations.put("authors", authors);
ArrayList<HashMap<String, Object>> checkIncluded = new ArrayList<>();
HashMap<String, Object> authorData = new HashMap<>();
authorData.put("name", "Hans");
checkIncluded.add(authorData);
Mockito.stub(mockSerializer.getRelationships(eq(article))).toReturn(relations);
Mockito.stub(mockSerializer.<API key>(eq(author))).toReturn(authorData);
ArrayList<HashMap<String, Object>> included = newMapper.createIncluded(article);
assertNotNull(included);
assertEquals(3, included.size());
assertEquals("authors", included.get(0).get("type"));
assertEquals("authorId", included.get(0).get("id"));
assertEquals(authorData, included.get(0).get("attributes"));
}
} |
'use strict';
const immutable = require('immutable');
module.exports = immutable.fromJS({
renderer: {
backgroundColor: 0x061639,
autoResize: true,
width: 640,
height: 480
}
}); |
function problem1() {
var answer,
inputInteger,
odd,
outputField;
inputInteger = document.getElementById('problem-1').value;
console.log('Problem 1');
answer = (inputInteger & 1) === 1 ? 'odd' : 'even';
console.log(inputInteger + ' is: ' + answer);
console.log('\n');
outputField = document.getElementById('problem-1-output');
outputField.innerHTML = 'The number is ' + answer;
} |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using Microsoft.Extensions.Configuration;
using NBitcoin;
namespace BTCPayServer.Configuration
{
public static class <API key>
{
public static T GetOrDefault<T>(this IConfiguration configuration, string key, T defaultValue)
{
var str = configuration[key] ?? configuration[key.Replace(".", string.Empty, StringComparison.InvariantCulture)];
if (str == null)
return defaultValue;
if (typeof(T) == typeof(bool))
{
var trueValues = new[] { "1", "true" };
var falseValues = new[] { "0", "false" };
if (trueValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)true;
if (falseValues.Contains(str, StringComparer.OrdinalIgnoreCase))
return (T)(object)false;
throw new FormatException();
}
else if (typeof(T) == typeof(Uri))
if (string.IsNullOrEmpty(str))
{
return defaultValue;
}
else
{
return (T)(object)new Uri(str, UriKind.Absolute);
}
else if (typeof(T) == typeof(string))
return (T)(object)str;
else if (typeof(T) == typeof(IPAddress))
return (T)(object)IPAddress.Parse(str);
else if (typeof(T) == typeof(IPEndPoint))
{
var separator = str.LastIndexOf(":", StringComparison.InvariantCulture);
if (separator == -1)
throw new FormatException();
var ip = str.Substring(0, separator);
var port = str.Substring(separator + 1);
return (T)(object)new IPEndPoint(IPAddress.Parse(ip), int.Parse(port, CultureInfo.InvariantCulture));
}
else if (typeof(T) == typeof(int))
{
return (T)(object)int.Parse(str, CultureInfo.InvariantCulture);
}
else
{
throw new <API key>("Configuration value does not support time " + typeof(T).Name);
}
}
}
} |
layout: post
published: true
title: How OmniFocus controls my life
At this point it's pretty fair to say that [OmniFocus][of] rules my life. I've
started to really take GTD seriously about 2 years ago. I had tried a lot of
different task managers before of course. I loved [Things][things] when it
originally came out as a beta and of course I had started to write [my own
todo tracker][gtdcouch] like everybody else. But I had never actually read
[the book][gtd-allen] before because I thought I didn't need such a
sophisticated todo tracker. That changed when I started a new job and moved to
a different country. Suddenly there were so much more things to keep track of
and do. So I read the book, pulled out Things again and tried to implement my
version of GTD. However it became apparent to me very quickly that the way I
want to use it (collect everything and have a lot of different ways to
retrieve/view data) wouldn't work with Things. So I shelled out a lot of money
and bought OmniFocus. And I have tried a couple of times to use a different
tool again but nothing worked for me as good as OF does. Mainly because I have
arrived at a setup that is very well integrated with my daily workflow.
The Basics
I have OmniFocus running on my personal and work laptop as well as on the
iPhone and iPad (although I hardly ever use it on there). They are all synced
through webdav and owncloud on my personal servers. I mainly use it on the
laptop and the iPhone client serves mostly for quickly inputting data or
pulling up a list when I'm on the go.
Collecting all the things
As every GTD guide ever will tell you, the system only works if it is your one
and only system that contains everything. And thus you have to add all your
todos and ideas in there. I try to heavily follow this approach as I found it
to be very true for me that I lose confidence in the tool as soon as it
doesn't contain my whole world. Paramount to this is the ability to enter new
items from basically everywhere and support every way that could generate
things for you to do. Luckily for me this means only a handful of things:
- Random things that I come up with
- Email
- GitHub issues
- Jira
This basically covers all variations of how I have new things landing on my
plate. And thus I have made sure all those things find an easy way into my
inbox.
# Random things
I use [Alfred 2][alfred] heavily on the desktop to quickly switch to or open
apps, convert units, lookup people, and a myriad of other things. Naturally
that means this is also the place where I should be inputting all new todos as
they come to mind. For that I'm using an [awesome workflow][alfred-workflow]
that I found somewhere on the internet. It allows me to fire up the Alfred
prompt and simply enter `todo do awesome thing @context` and on hitting enter
the new item is in my inbox with the correct context. This allows me literally
add new things in a matter of seconds and bother later with filtering,
remembering and doing them.
# Email
Email is a little bit trickier. There are awesome plugins for Mail.app to work
with Omnifocus and I hear they make it a breeze to get things done. However my
email client of choice is [mutt][mutt]. Which means there is a bit more
hacking to do (as usual). However I found a great [Python script][mutt-of]
that parses emails and adds them to Omnifocus. I also added this keybinding to
my mutt configuration:
macro index,pager \Ca "<enter-command>unset
wait_key<enter><pipe-message>mutt-to-omnifocus.py
<enter><save-message>=gtd-needs-reply/<enter><sync-mailbox>"
Now all I have to do when reading an Email or browsing through the list is hit
`Ctrl-a` and mutt automatically creates a task in my Omnifocus inbox and moves
the email out of my inbox into a folder I creatively called *gtd-needs-reply*
(I also have one called *gtd-to-read* which I use for emails that I still have
to read). This keeps my Email inbox clean and has the benefit since it adds an
Omnifocus entry with the context "Email" that I can easily find all the emails
I have to write with a custom perspective (more on that later).
# GitHub Issues
A decent amount of things to do for me are also generated via GitHub Issues.
This can either be issues on one of the public GitHub projects I maintain or
more often a code review [at work][etsy]. We use Pull Requests on GitHub
Enterprise for code reviews at Etsy and if someone wants you to review code,
they assign the pull request to you. Since there is no need for me to go
through my Email for notifications about code I have to review, I wrote a
simple script that runs every 10 minutes and checks whether I have issues
assigned that are not yet in my Omnifcous. [This script][ghfocus] reads a
configuration file which can have an arbitrary number of GitHub (Enterprise)
instances and asks for all issues assigned to a user owning the OAuth token.
It then generates a ticket title based on the repo URL and issue number and
adds a configurable context (Github or EtsyGithub for me) to it. It then
creates an Omnifocus inbox tasks based on that data, again easily findable by
context in Omnifocus.
# Jira
We use Jira at Etsy to manage tickets and workload and thus the majority of my
work is captured in there. Since I don't want to have two places to look for
things, I'm also pulling all my Jira tickets into Omnifocus. This is done with
basically the same script as the GitHub sync but uses [jira4r][jira4r] as the
input source. It then drops a todo item with the Jira project key and ticket
number into my inbox with the context *Etsy:Jira*. This makes it super easy to
organize all the work I am assigned in Omnifocus. The only downside to that is
that it's not a 2-way sync. Right now I clean up and close tasks in Omnifocus
(and Jira) when I actually finish them or during the weekly review. I also
only create tickets for myself in Jira and don't add tickets from Omnifocus
when I create new todos with the *Etsy:Jira* context. This wouldn't be very
hard to do but I haven't found it to be super painful to do it manually.
Basic Structure
So now that I have an easy way to enter all the incoming work into Omnifcous,
the next step is organizing all the things. For that I use folders heavily for
the basic structure and something close to the Areas of Responsibility in the
[GTD book][gtd-allen]. I have top level folders for *Etsy*, *Personal*,
*Talks* and *Open Source*. And under those another layer of folders which
reflect finer grained areas of responsibility. You see the structure here:

Within those areas a have the actual projects I work on and usually a single
action list project for miscellaneous things. I organize active and someday
projects in there by putting someday projects in *On Hold* status. This makes
it easy to find projects I'm working on by filtering for active ones in a
perspective. The project view is the most important one for finding and
organizing my work. I never fully got into using contexts for things other
than automated tools that pull in data. I rarely find myself in actually
different contexts where it makes sense to pull up a specific list and all my
tries to get that working ended in confusion for me (ymmv).
Perspectives all the way down
Based on that structure I have created a handful of custom perspectives to
quickly find things I need. You can see the overview of my perspectives in the
screenshot below.

The most important one is the *Today* perspective. It holds all items that are
due, overdue or flagged. This is my daily todo list with things I wanna get
done today. The next ones are Etsy active projects, next actions and weekly
summary. Those I pull up for planning daily tasks and writing my weekly
summary. I also have a perspective for Personal active projects which I don't
use that much but still pull up often enough to be valuable. The only crux
with those perspectives is that they are mostly project and not context based.
That means most of the perspectives don't sync to the iPhone. For now that is
ok for me because I mostly use the iPhone to add stuff to the inbox and to
check my daily todo list which I made a context based perspective. And [I've
also heard][kcase-tweet] that project based perspectives will be syncing to
the iPhone in the future. So that will help a lot.
Review, Review, Review
As every person that is trying to do their version of GTD will tell you,
consistent reviews are the heart of a working system. And that is no different
for me. I try to really be disciplined about my weekly reviews and try to do
daily reviews but often only end up actually doing them 3 times a week or so.
Which is not too bad as long as the weekly review is consistent.
# Daily
My daily review routine is pretty straight forward. I pull up the today list
and mark everything as done I completed but haven't checked off yet. Then I
pull up my active perspectives and flag stuff I wanna work on today. That's
it, simple and easy.
# Weekly
My weekly review is a bit more complex. I actually have a recurring project
that becomes available every Friday and is due on Sunday and looks like this:

This is my checklist to do my weekly review. So every weekend I will clear out
and archive all email and filter unprocessed email into *gtd-to-read* or
*gtd-needs-reply*. This is mostly mailing list stuff since I try to stay on
Inbox Zero during the week. I then put every thing I can think of that has to
be done into the inbox. I check my calendar from last week if there is
anything left to be done from meetings and check next weeks calendar for stuff
I have to prepare. I then hit the *Review* button in Omnifocus and start
reviewing all my projects. That usually starts with sorting all the inbox
items into the folder structure and then going through all the other projects
to mark things as completed and add new actions. This usually takes a bit
longer for active projects, whereas on hold projects I can go over quickly
because they don't usually have a lot of activity. I have set my default
review cycle to 5 days in general. That means projects become available for
review again after 5 days, so when I don't get to it on the Weekend and do my
review on Monday morning, I still have the projects ready for review on
Friday.
Verdict
For now I think I have found a good balance of using a lot of features of
Omnifocus while still keeping it somewhat simple and not going overboard with
the setup. Automating a lot of things - especially for inputting data - has
made a big difference in trusting the system to be my only source of truth for
work that needs to be done. My biggest problems are still making sure to take
enough time for the reviews, keep adding todos and paying attention to my
daily list even if I'm stressed and some days also ... you know ... actually
getting things done.
[of]: http:
[things]: https://culturedcode.com/things/
[gtdcouch]: https://github.com/mrtazz/gtd-couch
[alfred]: http:
[alfred-workflow]: http:
[mutt]: http:
[mutt-of]: https://github.com/mrtazz/bin/blob/master/mutt-to-omnifocus.py
[ghfocus]: https://github.com/mrtazz/bin/blob/master/ghfocus.rb
[jira4r]: https://github.com/codehaus/jira4r
[etsy]: https:
[gtd-allen]: http:
[kcase-tweet]: https://twitter.com/kcase/status/465904405141671938 |
@media (--viewport-max-s) {
body {
font-size: 1rem;
}
} |
// Regex.h
// Outlander
#import <Foundation/Foundation.h>
@interface Regex : NSObject
+(NSArray<<API key> *> *) matchesForString:(NSString *)value with:(NSString *)pattern;
@end |
<?
# file name: header.php
# purpose: header for each .php page
# created: June 2011
# authors: Don Franke
# Josh Stevens
# Peter Babcock
?>
<table width="100%" class="header">
<tr>
<td align="left" valign="middle"><a href=index.php><img
src="images/scantronitor.png" alt="Scantronitor" border="0"
vspace="5"></a></td>
<td align="right">
</td>
</table>
<table id="linkbox" cellspacing="0">
<tr>
<td class="flank"> </td>
<td width="200" class="highlight">Home</td>
<td width="200" class="link"><a href="past">Past</a></td>
<td width="200" class="link"><a href="present">Present</a></td>
<td width="200" class="link"><a href="future">Future</a></td>
<td class="flank"> </td>
</tr>
</table> |
# Tests for the preprocessor.
require 'test_helper'
# publicize the private methods so we can test them easily
class C::Preprocessor
public :full_command
end
class PreprocessorTest < Minitest::Test
attr_accessor :cpp
def setup
@cpp = C::Preprocessor.new(quiet: true)
@cpp.include_path << 'dir1' << 'dir 2'
@cpp.macros['V'] = nil
@cpp.macros['I'] = 5
@cpp.macros['S'] = '"blah"'
@cpp.macros['SWAP(a,b)'] = 'a ^= b ^= a ^= b'
FileUtils.rm_rf(TEST_DIR)
FileUtils.mkdir_p(TEST_DIR)
end
def teardown
FileUtils.rm_rf(TEST_DIR)
end
def test_full_command
original_command = C::Preprocessor.command
C::Preprocessor.command = 'COMMAND'
assert_equal([
'COMMAND',
'-Idir1', '-Idir 2',
'-DI=5', '-DS="blah"', '-DSWAP(a,b)=a ^= b ^= a ^= b', '-DV',
'a file.c',
], cpp.full_command('a file.c').shellsplit)
ensure
C::Preprocessor.command = original_command
end
def test_preprocess
output = cpp.preprocess("I S SWAP(x, y)")
assert_match(/5/, output)
assert_match(/"blah"/, output)
assert_match(/x \^= y \^= x \^= y/, output)
end
def <API key>
one_h = "#{TEST_DIR}/one.h"
two_h = "#{TEST_DIR}/foo/two.h"
File.open(one_h, 'w'){|f| f.puts "int one = 1;"}
FileUtils.mkdir(File.dirname(two_h))
File.open(two_h, 'w'){|f| f.puts "int two = 2;"}
output = nil
FileUtils.cd(TEST_DIR) do
output = cpp.preprocess(<<EOS)
#include "one.h"
#include "foo/two.h"
int three = 3;
EOS
end
assert_match(/int one = 1;/, output)
assert_match(/int two = 2;/, output)
assert_match(/int three = 3;/, output)
end
def <API key>
one_h = "#{TEST_DIR}/one.h"
two_h = "#{TEST_DIR}/foo/two.h"
main_c = "#{TEST_DIR}/main.c"
File.open(one_h, 'w'){|f| f.puts "int one = 1;"}
FileUtils.mkdir(File.dirname(two_h))
File.open(two_h, 'w'){|f| f.puts "int two = 2;"}
File.open(main_c, 'w'){|f| f.puts <<EOS}
#include "one.h"
#include "foo/two.h"
int three = 3;
EOS
output = cpp.preprocess_file(main_c)
assert_match(/int one = 1;/, output)
assert_match(/int two = 2;/, output)
assert_match(/int three = 3;/, output)
end
def <API key>
output = cpp.preprocess("#warning warning!")
refute_match /warning!/, output
end
end |
// <auto-generated>
// This code was generated from a template.
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
namespace U413.Domain.Entities
{
using System;
using System.Collections.Generic;
public partial class TopicFollow
{
public string Username { get; set; }
public long TopicID { get; set; }
public bool Saved { get; set; }
public virtual Topic Topic { get; set; }
public virtual User User { get; set; }
}
} |
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="layoutclass_pic"><div class="<API key>"><table class="ztable"><tr><th class="ztd1"><b> </b></th><td class="ztd2"></td></tr>
<tr><th class="ztd1"><b> </b></th><td class="ztd2"><sup class="subfont">ˇ</sup><sup class="subfont">ˊ</sup><sup class="subfont">ˋ</sup></td></tr>
<tr><th class="ztd1"><b> </b></th><td class="ztd2"><font class="english_word">liǎng dé yì zhāng</font></td></tr>
<tr><th class="ztd1"><b> </b></th><td class="ztd2"> <a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000001334%22.%26v%3D-1" class="clink" target=_blank></a><a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000001334%22.%26v%3D-1" class="clink" target=_blank></a></font></td></tr>
<tr><th class="ztd1"><b><style>.tableoutfmt2 .std1{width:3%;}</style></b></th><td class="ztd2"><table class="fmt16_table"><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b></b></td><td width=150 style="text-align:left;" class="fmt16_td2" ><a href="/cgi-bin/cydic/gsweb.cgi?o=dcydic&schfmt=text&gourl=%3De0%26sec%3Dsec1%26op%3Dsid%3D%22CW0000001334%22.%26v%3D-1" class="clink" target=_blank></a></td></tr><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b></b></td><td width=150 style="text-align:left;" class="fmt16_td2" ><sup class="subfont">ˊ</sup><sup class="subfont">ˋ</sup></td></tr><tr><td width=150 style="text-align:left;" class="fmt16_td1" ><b></b></td><td width=150 style="text-align:left;" class="fmt16_td2" ><font class="english_word">xiāng dé yì zhāng</font></td></tr></table><br><br></td></tr>
</td></tr></table></div> <!-- <API key> --><div class="<API key>"></div> <!-- <API key> --></div> <!-- layoutclass_pic --></td></tr></table> |
import { TestBed, inject, async } from '@angular/core/testing';
import RestClient from 'another-rest-client';
import { RestApiService } from '../../rest-api/rest-api.service';
import { <API key> } from './<API key>.service';
class RestClientMock {
public res: any;
public panel: any;
public common: any;
}
class RestApiServiceMock {
public getApi() {}
}
describe('<API key>', () => {
let restClientMock: RestClientMock;
let restApiServiceMock: RestApiServiceMock;
let res;
const PAGE_NUMBER = 2;
const BLOCK = {
accountId: 1,
apiKeyId: 2
};
const UNBLOCK = {
accountId: 3,
apiKeyId: 4
};
const <TwitterConsumerkey> = {
apiKeys: {},
pager: {}
};
const <API key> = {
apiKeys: {},
pager: {}
};
const BLOCK_RESULT = {
successful: true
};
const UNBLOCK_RESULT = {
successful: true
};
const <TwitterConsumerkey> = {};
const <API key> = {};
beforeEach(() => {
restClientMock = new RestClientMock();
restApiServiceMock = new RestApiServiceMock();
spyOn(restApiServiceMock, 'getApi').and.returnValue(restClientMock);
res = jasmine.createSpy('res').and.callFake(() => {
return { res };
});
restClientMock.res = res;
TestBed.<API key>({
providers: [
{
provide: <API key>,
useClass: <API key>
},
{
provide: RestApiService,
useValue: restApiServiceMock
}
]
});
});
it('is created', inject([<API key>], (<API key>: <API key>) => {
expect(<API key>).toBeTruthy();
expect(res.calls.count()).toBe(14);
expect(res.calls.argsFor(0)).toEqual(['common']);
expect(res.calls.argsFor(1)).toEqual(['panel']);
expect(res.calls.argsFor(2)).toEqual(['admin']);
expect(res.calls.argsFor(3)).toEqual(['apiKeys']);
expect(res.calls.argsFor(4)).toEqual(['block']);
expect(res.calls.argsFor(5)).toEqual(['common']);
expect(res.calls.argsFor(6)).toEqual(['panel']);
expect(res.calls.argsFor(7)).toEqual(['admin']);
expect(res.calls.argsFor(8)).toEqual(['apiKeys']);
expect(res.calls.argsFor(9)).toEqual(['unblock']);
expect(res.calls.argsFor(10)).toEqual(['common']);
expect(res.calls.argsFor(11)).toEqual(['panel']);
expect(res.calls.argsFor(12)).toEqual(['admin']);
expect(res.calls.argsFor(13)).toEqual(['accounts']);
}));
describe('after initialization', () => {
beforeEach(() => {
restClientMock.common = {
panel: {
admin: {
apiKeys: {
post: (searchCriteria: any) => {
expect(searchCriteria).toBe(<TwitterConsumerkey>);
return Promise.resolve(<TwitterConsumerkey>);
},
block: {
post: (block: any) => {
expect(block).toBe(BLOCK);
return Promise.resolve(BLOCK_RESULT);
}
},
unblock: {
post: (unblock: any) => {
expect(unblock).toBe(UNBLOCK);
return Promise.resolve(UNBLOCK_RESULT);
}
}
},
accounts: {
post: (searchCriteria: any) => {
expect(searchCriteria).toBe(<API key>);
return Promise.resolve(<API key>);
},
}
}
}
};
});
it('searches for API keys', inject([<API key>], (<API key>: <API key>) => {
<API key>.searchApiKeys(<TwitterConsumerkey>).then((response) => {
expect(response).toBe(<TwitterConsumerkey>);
});
}));
it('block API key', inject([<API key>], (<API key>: <API key>) => {
<API key>.blockApiKey(BLOCK).then((response) => {
expect(response).toBe(BLOCK_RESULT);
});
}));
it('unblock API key', inject([<API key>], (<API key>: <API key>) => {
<API key>.unblockApiKey(UNBLOCK).then((response) => {
expect(response).toBe(UNBLOCK_RESULT);
});
}));
it('searches for API keys', inject([<API key>], (<API key>: <API key>) => {
<API key>.searchAccounts(<API key>).then((response) => {
expect(response).toBe(<API key>);
});
}));
});
}); |
import {
Component,
OnInit,
ViewEncapsulation,
Input,
Output,
EventEmitter
} from '@angular/core';
@Component({
selector: 'app-header',
encapsulation: ViewEncapsulation.None,
//styleUrls: ['/header.scss'],
templateUrl: './header.html'
})
export class HeaderComponent {
@Input() logoTitle: string = 'Logo';
@Output() logoClick: EventEmitter<string> = new EventEmitter();
onLogoClick(): void {
console.log('HELLO WORLD');
this.logoClick.emit('HEADER CLICK');
}
} |
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "net.h"
#include "key.h"
#include "script.h"
#include "db.h"
#include <list>
class CBlock;
class CBlockIndex;
class CWalletTx;
class CWallet;
class CKeyItem;
class CReserveKey;
class CWalletDB;
class CAddress;
class CInv;
class CRequestTracker;
class CNode;
class CBlockIndex;
static const unsigned int MAX_BLOCK_SIZE = 1000000;
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
static const int64 COIN = 100000000;
static const int64 CENT = 1000000;
static const int64 MIN_TX_FEE = 50000;
static const int64 MIN_RELAY_TX_FEE = 10000;
static const int64 MAX_MONEY = 2100 * COIN;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
static const int COINBASE_MATURITY = 100;
// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern CBigNum bnBestChainWork;
extern CBigNum bnBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int <API key>;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection <API key>;
extern std::set<CWallet*> <API key>;
// Settings
extern int fGenerateBitcoins;
extern int64 nTransactionFee;
extern int fLimitProcessors;
extern int nLimitProcessors;
extern int fMinimizeToTray;
extern int fMinimizeOnClose;
extern int fUseUPnP;
class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CReserveKey& reservekey);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
int <API key>();
int GetNumBlocksOfPeers();
bool <API key>();
std::string GetWarnings(std::string strFor);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
template<typename T>
bool WriteSetting(const std::string& strKey, const T& value)
{
bool fOk = false;
BOOST_FOREACH(CWallet* pwallet, <API key>)
{
std::string strWalletFile;
if (!GetWalletFile(pwallet, strWalletFile))
continue;
fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
}
return fOk;
}
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return strprintf("null");
else
return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
}
void print() const
{
printf("%s", ToString().c_str());
}
};
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = -1; }
bool IsNull() const { return (ptx == NULL && n == -1); }
};
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = -1; }
bool IsNull() const { return (hash == 0 && n == -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
// An input of a transaction. It contains the location of the previous
// transaction's output that it claims and a signature that matches the
// output's public key.
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = UINT_MAX;
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == UINT_MAX);
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTxIn(");
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != UINT_MAX)
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
// An output of a transaction. It contains the public key that the next input
// must be able to sign with to claim it.
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull()
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToString() const
{
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
// The basic transaction that is broadcasted on the network and contained in
// blocks. A transaction can contain multiple inputs and outputs.
class CTransaction
{
public:
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = 1;
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = UINT_MAX;
for (int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
int GetSigOpCount() const
{
int n = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
n += txin.scriptSig.GetSigOpCount();
BOOST_FOREACH(const CTxOut& txout, vout)
n += txout.scriptPubKey.GetSigOpCount();
return n;
}
bool IsStandard() const
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.scriptSig.IsPushOnly())
return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey))
return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
return true;
}
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 144 / 250;
}
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 10K are free
// (about 4500bc if made of 50bc inputs)
if (nBytes < 10000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
filein >> *this;
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
bool ClientConnectInputs();
bool CheckTransaction() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
protected:
bool <API key>();
public:
bool <API key>();
};
// A transaction with a merkle branch linking it to the block chain
class CMerkleTx : public CTransaction
{
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable char fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
int GetDepthInMainChain(int& nHeightRet) const;
int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptToMemoryPool();
};
// A txdb record that contains the disk location of a transaction and the
// locations of transactions that spend its outputs. vSpent is really only
// used as a flag, but having the location is very helpful for debugging.
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
// Nodes collect new transactions into a block, hash them into a hash tree,
// and scan through nonce values to make the block's hash satisfy proof-of-work
// requirements. When they solve the proof-of-work, they broadcast the block
// to everyone and the block is added to the block chain. The first transaction
// in the block is a special one that creates a new coin owned by the creator
// of the block.
// Blocks are appended to blk0001.dat files on disk. Their location on disk
// is indexed by CBlockIndex objects in memory.
class CBlock
{
public:
// header
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx being last so it can calculate offset
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
READWRITE(vtx);
else if (fRead)
const_cast<CBlock*>(this)->vtx.clear();
)
void SetNull()
{
nVersion = 1;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
int GetSigOpCount() const
{
int n = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
n += tx.GetSigOpCount();
return n;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = AppendBlockFile(nFileRet);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
nBlockPosRet = ftell(fileout);
if (nBlockPosRet == -1)
return error("CBlock::WriteToDisk() : ftell failed");
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!<API key>() || (nBestHeight+1) % 500 == 0)
{
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
filein >> *this;
// Check the header
if (!CheckProofOfWork(GetHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
GetHash().ToString().substr(0,20).c_str(),
nVersion,
hashPrevBlock.ToString().substr(0,20).c_str(),
hashMerkleRoot.ToString().substr(0,10).c_str(),
nTime, nBits, nNonce,
vtx.size());
for (int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
printf("\n");
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
bool CheckBlock() const;
bool AcceptBlock();
};
// The block chain is a tree shaped structure starting with the
// genesis block at the root, with each block potentially having multiple
// candidates to be the next block. pprev and pnext link a path through the
// main/longest chain. A blockindex may have multiple pprev pointing back
// to it, but pnext will only point forward to the longest branch, or will
// be null if the block is not part of the longest chain.
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
int nHeight;
CBigNum bnChainWork;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
bnChainWork = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
bnChainWork = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return CheckProofOfWork(GetBlockHash(), nBits);
}
bool EraseBlockFromDisk()
{
// Open history file
CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
if (!fileout)
return false;
// Overwrite with empty null block
CBlock block;
block.SetNull();
fileout << block;
return true;
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
hashMerkleRoot.ToString().substr(0,10).c_str(),
GetBlockHash().ToString().substr(0,20).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
// Used to marshal pointers into hashes for db storage.
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().substr(0,20).c_str(),
hashNext.ToString().substr(0,20).c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
// Describes a place in the block chain to another node such that if the
// other node doesn't have the same branch, it can find a recent common trunk.
// The further back it is, the further before the fork it may be.
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
// Alerts are for notifying old versions if they become too obsolete and
// need to upgrade. The message is displayed in the status bar.
// Alert messages are broadcast as a vector of signed data. Unserializing may
// not read the entire buffer if the alert is for a newer version, but older
// versions can still relay the original data.
class CUnsignedAlert
{
public:
int nVersion;
int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
int64 nExpiration;
int nID;
int nCancel;
std::set<int> setCancel;
int nMinVer; // lowest version inclusive
int nMaxVer; // highest version inclusive
std::set<std::string> setSubVer; // empty matches all
int nPriority;
// Actions
std::string strComment;
std::string strStatusBar;
std::string strReserved;
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nRelayUntil);
READWRITE(nExpiration);
READWRITE(nID);
READWRITE(nCancel);
READWRITE(setCancel);
READWRITE(nMinVer);
READWRITE(nMaxVer);
READWRITE(setSubVer);
READWRITE(nPriority);
READWRITE(strComment);
READWRITE(strStatusBar);
READWRITE(strReserved);
)
void SetNull()
{
nVersion = 1;
nRelayUntil = 0;
nExpiration = 0;
nID = 0;
nCancel = 0;
setCancel.clear();
nMinVer = 0;
nMaxVer = 0;
setSubVer.clear();
nPriority = 0;
strComment.clear();
strStatusBar.clear();
strReserved.clear();
}
std::string ToString() const
{
std::string strSetCancel;
BOOST_FOREACH(int n, setCancel)
strSetCancel += strprintf("%d ", n);
std::string strSetSubVer;
BOOST_FOREACH(std::string str, setSubVer)
strSetSubVer += "\"" + str + "\" ";
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %"PRI64d"\n"
" nExpiration = %"PRI64d"\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"
" nMinVer = %d\n"
" nMaxVer = %d\n"
" setSubVer = %s\n"
" nPriority = %d\n"
" strComment = \"%s\"\n"
" strStatusBar = \"%s\"\n"
")\n",
nVersion,
nRelayUntil,
nExpiration,
nID,
nCancel,
strSetCancel.c_str(),
nMinVer,
nMaxVer,
strSetSubVer.c_str(),
nPriority,
strComment.c_str(),
strStatusBar.c_str());
}
void print() const
{
printf("%s", ToString().c_str());
}
};
class CAlert : public CUnsignedAlert
{
public:
std::vector<unsigned char> vchMsg;
std::vector<unsigned char> vchSig;
CAlert()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(vchMsg);
READWRITE(vchSig);
)
void SetNull()
{
CUnsignedAlert::SetNull();
vchMsg.clear();
vchSig.clear();
}
bool IsNull() const
{
return (nExpiration == 0);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsInEffect() const
{
return (GetAdjustedTime() < nExpiration);
}
bool Cancels(const CAlert& alert) const
{
if (!IsInEffect())
return false; // this was a no-op before 31403
return (alert.nID <= nCancel || setCancel.count(alert.nID));
}
bool AppliesTo(int nVersion, std::string strSubVerIn) const
{
return (IsInEffect() &&
nMinVer <= nVersion && nVersion <= nMaxVer &&
(setSubVer.empty() || setSubVer.count(strSubVerIn)));
}
bool AppliesToMe() const
{
return AppliesTo(VERSION, ::pszSubVer);
}
bool RelayTo(CNode* pnode) const
{
if (!IsInEffect())
return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second)
{
if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
AppliesToMe() ||
GetAdjustedTime() < nRelayUntil)
{
pnode->PushMessage("alert", *this);
return true;
}
}
return false;
}
bool CheckSignature()
{
CKey key;
if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
return error("CAlert::CheckSignature() : SetPubKey failed");
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("CAlert::CheckSignature() : verify signature failed");
// Now unserialize the data
CDataStream sMsg(vchMsg);
sMsg >> *(CUnsignedAlert*)this;
return true;
}
bool ProcessAlert();
};
#endif |
<?php
include_once('../src/SVGCreator/Element.php');
include_once('../src/SVGCreator/SVGException.php');
include_once('../src/SVGCreator/Elements/Rect.php');
include_once('../src/SVGCreator/Elements/Group.php');
include_once('../src/SVGCreator/Elements/Svg.php');
include_once('../src/SVGCreator/Elements/Circle.php');
include_once('../src/SVGCreator/Elements/Marker.php');
include_once('../src/SVGCreator/Elements/Defs.php');
include_once('../src/SVGCreator/Elements/Line.php');
include_once('../src/SVGCreator/Elements/Path.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Circle Example</title>
</head>
<body>
<section>
<?php
$attributesSvg = array(
'width' => 1000,
'height' => 1000
);
$svg = new \SVGCreator\Elements\Svg($attributesSvg);
$svg->append(\SVGCreator\Element::CIRCLE)
->attr('cx', 100)
->attr('cy', 100)
->attr('fill', '#ff0000')
->attr('r', 50)
->attr('stroke', '#000000')
->attr('stroke-width', '5px');
$svg->append(\SVGCreator\Element::CIRCLE)
->attr('cx', 250)
->attr('cy', 140)
->attr('fill', 'green')
->attr('r', 20)
->attr('stroke', 'cyan')
->attr('stroke-width', '5px');
$svg->append($circle);
echo $svg->getString();
?>
</section>
</body>
</html> |
/*!
** @file EInt1.c
** @version 01.02
** @brief
** This component, "ExtInt_LDD", provide a low level API
** for unified access of external interrupts handling
** across various device designs.
** The component uses one pin which generates interrupt on
** selected edge.
*/
/*!
** @addtogroup EInt1_module EInt1 module documentation
** @{
*/
/* MODULE EInt1. */
#include "Events.h"
#include "EInt1.h"
/* {Default RTOS Adapter} No RTOS includes */
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
LDD_TUserData *UserData; /* RTOS device data structure */
} EInt1_TDeviceData, *<API key>; /* Device data structure type */
/* {Default RTOS Adapter} Static object used for simulation of dynamic driver memory allocation */
static EInt1_TDeviceData <API key>;
/* {Default RTOS Adapter} Global variable used for passing a parameter into ISR */
static EInt1_TDeviceData * <API key>;
/*!
** @brief
** This method initializes the associated peripheral(s) and the
** component internal variables. The method is called
** automatically as a part of the application initialization
** code.
** @param
** UserDataPtr - Pointer to the RTOS device
** structure. This pointer will be passed to
** all events as parameter.
** @return
** - Pointer to the dynamically allocated private
** structure or NULL if there was an error.
*/
LDD_TDeviceData* EInt1_Init(LDD_TUserData *UserDataPtr)
{
/* Allocate LDD device structure */
EInt1_TDeviceData *DeviceDataPrv;
/* {Default RTOS Adapter} Driver memory allocation: Dynamic allocation is simulated by a pointer to the static object */
DeviceDataPrv = &<API key>;
/* Store the UserData pointer */
DeviceDataPrv->UserData = UserDataPtr;
/* Interrupt vector(s) allocation */
/* {Default RTOS Adapter} Set interrupt vector: IVT is static, ISR parameter is passed by the global variable */
<API key> = DeviceDataPrv;
/* Initialization of Port Control registers */
/* PORTA_PCR10: ISF=0,MUX=1 */
PORTA_PCR10 = (uint32_t)((PORTA_PCR10 & (uint32_t)~(uint32_t)(
PORT_PCR_ISF_MASK |
PORT_PCR_MUX(0x06)
)) | (uint32_t)(
PORT_PCR_MUX(0x01)
));
/* PORTA_PCR10: ISF=1,IRQC=9 */
PORTA_PCR10 = (uint32_t)((PORTA_PCR10 & (uint32_t)~(uint32_t)(
PORT_PCR_IRQC(0x06)
)) | (uint32_t)(
PORT_PCR_ISF_MASK |
PORT_PCR_IRQC(0x09)
));
/* NVIC_IPR7: PRI_30=0x80 */
NVIC_IPR7 = (uint32_t)((NVIC_IPR7 & (uint32_t)~(uint32_t)(
NVIC_IP_PRI_30(0x7F)
)) | (uint32_t)(
NVIC_IP_PRI_30(0x80)
));
/* NVIC_ISER: SETENA|=0x40000000 */
NVIC_ISER |= NVIC_ISER_SETENA(0x40000000);
/* Registration of the device structure */
<API key>(<API key>,DeviceDataPrv);
return ((LDD_TDeviceData *)DeviceDataPrv);
}
void EInt1_Interrupt(void)
{
/* {Default RTOS Adapter} ISR parameter is passed through the global variable */
<API key> DeviceDataPrv = <API key>;
/* Check the pin interrupt flag of the shared interrupt */
if (<API key>(PORTA_BASE_PTR, EInt1_PIN_INDEX)) {
/* Clear the interrupt flag */
<API key>(PORTA_BASE_PTR, EInt1_PIN_INDEX);
/* Call OnInterrupt event */
EInt1_OnInterrupt(DeviceDataPrv->UserData);
}
}
/* END EInt1. */
#ifdef __cplusplus
} /* extern "C" */
#endif |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-23 04:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '<API key>'),
]
operations = [
migrations.AddField(
model_name='entry',
name='featured',
field=models.BooleanField(default=False),
),
] |
angular.module('noTeRayesCoApp', [])
.controller('mainCtrl', ['$scope', '$http', '$interval', function ($scope, $http, $interval) {
// True if Pilars have started
$scope.pilares = false;
$scope.days = 000;
$scope.hours = 00;
$scope.minutes = 00;
$scope.seconds = 00;
$http.get("getVisits").then(function (response) {
$scope.nVisits = response.data;
});
// Audio path variable
$scope.audio = new Audio('audio/audioFile-' + Math.floor(Math.random() * 5) + '.mp3');
$scope.playMyAudio = function() {
$scope.audio.currentTime = 0;
$scope.audio.play();
};
// Set the date we're counting down to
$scope.countDownDate = new Date("Oct 7, 2020 21:00:00 GMT+2").getTime();
// Update the count down every 1 second
var updateCounter = function () {
// Get todays date and time
$scope.now = new Date().getTime();
// Find the distance between now an the count down date
$scope.distance = $scope.countDownDate - $scope.now;
// Time calculations for days, hours, minutes and seconds
$scope.days = Math.floor($scope.distance / (1000 * 60 * 60 * 24));
$scope.hours = Math.floor(($scope.distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$scope.minutes = Math.floor(($scope.distance % (1000 * 60 * 60)) / (1000 * 60));
$scope.seconds = Math.floor(($scope.distance % (1000 * 60)) / 1000);
if ($scope.distance <= 0) {
$scope.pilares = true;
// If the count down is over, the interval is stopped
$interval.cancel($scope.countDownFunction);
}
}
$scope.countDownFunction = $interval(updateCounter, 1000);
updateCounter();
// Once everything is loaded, make it all appear!
var hiddenElems = document.getElementsByName("init-hidden");
var elem;
for (elem = 0; elem < hiddenElems.length; elem++){
hiddenElems[elem].style.visibility = 'visible';
}
}]); |
<?php
namespace CandyCMS\Core\Models;
use CandyCMS\Core\Helpers\AdvancedException;
use CandyCMS\Core\Helpers\Helper;
use CandyCMS\Core\Helpers\Pagination;
use PDO;
class Sessions extends Main {
/**
* Fetch all user data of active session.
*
* @static
* @access public
* @return array $aResult user data
* @see vendor/candyCMS/core/controllers/Index.controller.php
*
*/
public static function getUserBySession() {
if (empty(parent::$_oDbStatic))
parent::connectToDatabase();
try {
$oQuery = parent::$_oDbStatic->prepare("SELECT
u.*
FROM
" . SQL_PREFIX . "users AS u
LEFT JOIN
" . SQL_PREFIX . "sessions AS s
ON
u.id = s.user_id
WHERE
s.session = :session_id
AND
s.ip = :ip
LIMIT
1");
$oQuery->bindParam('session_id', session_id(), PDO::PARAM_STR);
$oQuery->bindParam('ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$bReturn = $oQuery->execute();
if ($bReturn == false)
self::destroy();
$mData = $oQuery->fetch(PDO::FETCH_ASSOC);
return $mData ? parent::<API key>($mData) : $mData;
}
catch (\PDOException $p) {
AdvancedException::reportBoth('0072 - ' . $p->getMessage());
exit('SQL error.');
}
}
/**
* Create a user session.
*
* @access public
* @param array $aUser optional user data.
* @return boolean status of login
*
*/
public function create($aUser = '') {
if (empty($aUser)) {
$sModel = $this->__autoload('Users', true);
$oModel = & new $sModel($this->_aRequest, $this->_aSession);
$aUser = $oModel->getLoginData();
}
# User did verify and has id, so log in!
if (isset($aUser['id']) && !empty($aUser['id']) && empty($aUser['verification_code'])) {
try {
$oQuery = $this->_oDb->prepare("INSERT INTO
" . SQL_PREFIX . "sessions
( user_id,
session,
ip,
date)
VALUES
( :user_id,
:session,
:ip,
:date)");
$oQuery->bindParam('user_id', $aUser['id'], PDO::PARAM_INT);
$oQuery->bindParam('session', session_id(), PDO::PARAM_STR);
$oQuery->bindParam('ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
$oQuery->bindParam('date', time(), PDO::PARAM_INT);
return $oQuery->execute();
}
catch (\PDOException $p) {
try {
$this->_oDb->rollBack();
}
catch (\Exception $e) {
AdvancedException::reportBoth('0073 - ' . $e->getMessage());
}
AdvancedException::reportBoth('0074 - ' . $p->getMessage());
exit('SQL error.');
}
}
else
return false;
}
/**
* Resend password.
*
* @access public
* @param string $sPassword new password if we want to resend it
* @return boolean status of query
*
*/
public function resendPassword($sPassword = '') {
$sModel = $this->__autoload('Users');
return $sModel::setPassword($this->_aRequest['email'], $sPassword);
}
/**
* Resend verification.
*
* @access public
* @return boolean|array status of query or user array
*
*/
public function resendVerification() {
$sModel = $this->__autoload('Users');
$aData = $sModel::getVerificationData($this->_aRequest['email']);
return empty($aData['verification_code']) ? false : $aData;
}
/**
* Destroy a user session and logout.
*
* @access public
* @param integer $sSessionId the session id
* @return boolean status of query
*
*/
public function destroy($sSessionId) {
if (empty(parent::$_oDbStatic))
parent::connectToDatabase();
try {
$oQuery = parent::$_oDbStatic->prepare("UPDATE
" . SQL_PREFIX . "sessions
SET
session = NULL
WHERE
session = :session_id");
$oQuery->bindParam('session_id', $sSessionId, PDO::PARAM_STR);
return $oQuery->execute();
}
catch (\PDOException $p) {
try {
parent::$_oDbStatic->rollBack();
}
catch (\Exception $e) {
AdvancedException::reportBoth('0075 - ' . $e->getMessage());
}
AdvancedException::reportBoth('0076 - ' . $p->getMessage());
exit('SQL error.');
}
}
} |
<?php
use ByJG\Util\Psr7\StreamBase;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . "/StreamBaseTest.php";
class FileStreamTest extends StreamBaseTest
{
const FILENAME = "/tmp/filestream-test.txt";
/**
* @param $data
* @return StreamBase
*/
public function getResource($data)
{
if (file_exists(self::FILENAME)) {
unlink(self::FILENAME);
}
file_put_contents(self::FILENAME, $data);
return new \ByJG\Util\Psr7\FileStream(self::FILENAME, "rw+");
}
public function tearDownResource()
{
$this->stream->close();
$this->stream = null;
unlink(self::FILENAME);
}
public function isWriteable()
{
return true;
}
public function canOverwrite()
{
return true;
}
} |
export { default as a, b, c as d } from 'e';
export * from 'f'; |
/*
* Webpack development server configuration
*
* This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if
* the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload.
*/
'use strict';
var webpack = require('webpack');
module.exports = {
output: {
filename: 'main.js',
publicPath: '/assets/'
},
cache: true,
debug: true,
devtool: false,
entry: [
'./src/scripts/main.js'
],
stats: {
colors: true,
reasons: true
},
resolve: {
extensions: ['', '.js'],
},
module: {
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}],
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.sass/,
loader: 'style-loader!css-loader!sass-loader?outputStyle=expanded'
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}, {
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
}]
},
plugins: [
new webpack.NoErrorsPlugin()
]
}; |
package jmb.jcortex.trainers;
import jmb.jcortex.data.SynMatrix;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class <API key> {
@Test
public void <API key>() {
List<SynMatrix> nodeValues = Arrays.asList(
new SynMatrix(new double[][]{
{-0.1, 0.1},
{0.15, -0.15}
}),
new SynMatrix(new double[][]{
{0.2, -0.2},
{-0.3, 0.3}
})
);
List<SynMatrix> deltas = Arrays.asList(
new SynMatrix(new double[][]{
{-0.2, 0.2, 0.1},
{0.3, -0.2, -0.15}
}),
new SynMatrix(new double[][]{
{-0.15, -0.2, 0.3},
{0.15, 0.3, -0.1}
})
);
List<SynMatrix> expectedGradients = Arrays.asList(
new SynMatrix(new double[][]{
{0.05, 0.0, -0.025},
{0.0325, -0.025, -0.01625},
{-0.0325, 0.025, 0.01625}
}),
new SynMatrix(new double[][]{
{0.0, 0.05, 0.1},
{-0.0375, -0.065, 0.045},
{0.0375, 0.065, -0.045}
})
);
List<SynMatrix> actualGradients = new GradientCalculator().calcGradients(deltas, nodeValues);
assertThat(actualGradients).isEqualTo(expectedGradients);
}
} |
from datetime import timedelta
import time
from pypi_portal.core.email import send_email, send_exception
from pypi_portal.extensions import mail, redis
def raise_and_send():
with mail.record_messages() as outbox:
try:
raise ValueError('Fake error.')
except ValueError:
send_exception('Test Email10')
return outbox
def test_send_email():
with mail.record_messages() as outbox:
send_email('Test Email', 'Message body.')
assert 1 == len(outbox)
assert 'Test Email' == outbox[0].subject
with mail.record_messages() as outbox:
send_email('Test Email2', 'Message body.', throttle=1)
send_email('Test Email2', 'Message body.', throttle=timedelta(seconds=1))
send_email('Test Email9', 'Message body.', throttle=1)
time.sleep(1.1)
send_email('Test Email2', 'Message body.', throttle=1)
assert 3 == len(outbox)
assert ['Test Email2', 'Test Email9', 'Test Email2'] == [o.subject for o in outbox]
def test_send_exception():
redis.flushdb()
outbox = raise_and_send()
assert 1 == len(outbox)
assert 'Application Error: Test Email10' == outbox[0].subject
assert '<blockquote ' in outbox[0].html
assert 'Fake error.' in outbox[0].html
outbox = raise_and_send()
assert 0 == len(outbox) |
Expect the practicioner to be alert,motivated and capable of judgement
Galactic modeling language
there is a difference between wandering at random and real exploring
without direction or purpose... you'll be lost
Chapter 1
recognize a risk and turn that into a question to be answered
we always find the most serious bugs when we go off script
we still found surprises when we deviated from the scripts
checking that software meets expectations and exploring for risk
exploratory testing requires that your brain be fully engaged at all times
me: automating is an act of exploration
state diagram?
me: plan out charter as series of notebook scenarios like a guided tour
expedition party members - guide, notetaker/academic, technical resources (captain)
you notice what kinds of conditions the software does not handle well and use that knowlege to push even harder
me: jon bach talk about sessions integrated with automation. microsessions?
expedition -> experiment. learnings from session distilled into fruitful repetitive experiments. Building a guidebook for future testing / Demonstrable Debrief
Brainstorm a list of questions. Consider how the current test strategy answers each question.
me: automated tests answer some question, what you do with the results is more important than the act of executing them. Automate enough to inform decisions, they are a diagnostic tool. The tool doesn't replace the doctor
chapter 2
Different charters, different types of exploration
me: different charters different diagnostic tools. What about cross cutting concerns, base charter characteristics
me: charters for person/scenario explore X persona with Y team dynamics to discover possible positive contributions
a good charter is a prompt it suggests sources of inspiration without dictating precise actions or outcomes
exploring can reveal opportunities to add new requirements as well as risks or problems
when you recognize an implicit expectation that deserves exploration, capture it as a charter.
you don't want to spend a lot of time discovering information that no one will take action on
chapter 9
trust boundaries - a place where your software connects to other software that it cannot assume will always play by the rules, such as a nother system, one th
[me] we carve these areas out of automation when possible not because there is not value but because they are difficult and/or challenging
inclusive automation- engages the tester while they are testing. offering assistance or enabling greater focus on the testing at hand |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Server.RDungeons {
public class DungeonArrayRoom {
public int Opened { get; set; }
public int StartX { get; set; }
public int StartY { get; set; }
public int EndX { get; set; }
public int EndY { get; set; }
public DungeonArrayRoom() {
StartX = -1;
StartY = -1;
EndX = -1;
EndY = -1;
}
}
} |
import { stateTypes } from '../util';
export default function() {
return {
types: ['transition'],
exit: function(node) {
var data = node.data;
data.onTransition = (data.onTransition || []).concat(node.children);
node.children = [];
return node;
}
};
}; |
package fr.bmartel.pcapdecoder.structure.types.inter;
public interface IPacketBlock {
int getInterfaceId();
int getDropsCount();
Long getMillis();
int getCaptureLength();
int getPacketLength();
byte[] getPacketData();
byte[] getOptionsData();
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace SimpleUwp
{
<summary>
</summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
//button1Click
private void button1_Click(object sender, RoutedEventArgs e)
{
int a = 2; //a 2
int b = 5; //b 5
int sum = a + b; //sumab
string sum_str = sum.ToString(); //(string)
textBox1.Text = sum_str; //Text
}
}
} |
[World Wide Web Consortium][0][World Wide Web Consortium][0][Hammerdown][1]
[0]: http:
[1]: http://hammerdown.com./ |
# zscroller
dom scroller based on [zynga scroller](https://zynga.github.io/scroller/)
[![NPM version][npm-image]][npm-url]
[![gemnasium deps][gemnasium-image]][gemnasium-url]
[![node version][node-image]][node-url]
[![npm download][download-image]][download-url]
[npm-image]: http://img.shields.io/npm/v/zscroller.svg?style=flat-square
[npm-url]: http://npmjs.org/package/zscroller
[travis-image]: https://img.shields.io/travis/yiminghe/zscroller.svg?style=flat-square
[travis-url]: https://travis-ci.org/yiminghe/zscroller
[coveralls-image]: https://img.shields.io/coveralls/yiminghe/zscroller.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/yiminghe/zscroller?branch=master
[gemnasium-image]: http://img.shields.io/gemnasium/yiminghe/zscroller.svg?style=flat-square
[gemnasium-url]: https://gemnasium.com/yiminghe/zscroller
[node-image]: https://img.shields.io/badge/node.js-%3E=_0.10-green.svg?style=flat-square
[node-url]: http://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/zscroller.svg?style=flat-square
[download-url]: https://npmjs.org/package/zscroller
## Usage
import DOMScroller from 'zscroller/lib/DOMScroller';
var domScroller = new DOMScroller(contentNode, options);
## Example
http://localhost:8000/examples/
online example: http://yiminghe.github.io/zscroller/
## install
[, extra:
| name | description | type | default |
|
|scrollbars |whether show scrollbars | bool | false |
|onScroll | onScroll callback | () => void | null |
method
## Test Case
npm test
npm run chrome-test
## Coverage
npm run coverage
open coverage/ dir
zscroller is released under the MIT license. |
using BinDeps
using Compat
using Compat.Sys: iswindows, isapple, isunix
@BinDeps.setup
version = "3370"
baseurl = "ftp://heasarc.gsfc.nasa.gov/software/fitsio/c/"
if isunix()
archivename = "cfitsio$(version).tar.gz"
elseif iswindows()
archivename = "cfitsio_MSVC_$(Sys.WORD_SIZE)bit_DLL_$(version).zip"
end
libcfitsio = library_dependency("libcfitsio", aliases=["cfitsio"])
downloadsdir = BinDeps.downloadsdir(libcfitsio)
libdir = BinDeps.libdir(libcfitsio)
srcdir = BinDeps.srcdir(libcfitsio)
if isapple()
libfilename = "libcfitsio.dylib"
elseif isunix()
libfilename = "libcfitsio.so"
elseif iswindows()
libfilename = "cfitsio.dll"
end
# Unix
prefix = joinpath(BinDeps.depsdir(libcfitsio), "usr")
provides(Sources, URI(baseurl*archivename), libcfitsio, unpacked_dir="cfitsio")
provides(BuildProcess,
(@build_steps begin
GetSources(libcfitsio)
@build_steps begin
ChangeDirectory(joinpath(srcdir, "cfitsio"))
FileRule(joinpath(libdir, libfilename),
@build_steps begin
`./configure --prefix=$prefix --enable-reentrant`
`make shared install`
end)
end
end), libcfitsio, os = :Unix)
# Windows
provides(BuildProcess,
(@build_steps begin
FileDownloader(baseurl*archivename,
joinpath(downloadsdir, archivename))
CreateDirectory(srcdir, true)
FileUnpacker(joinpath(downloadsdir, archivename), srcdir,
joinpath(srcdir, libfilename))
CreateDirectory(libdir, true)
@build_steps begin
ChangeDirectory(srcdir)
FileRule(joinpath(libdir, libfilename), @build_steps begin
`powershell -Command "cp $(libfilename) $(joinpath(libdir, libfilename))"`
end)
end
end), libcfitsio, os = :Windows)
if iswindows()
push!(BinDeps.defaults, BuildProcess)
end
# OSX
if isapple()
using Homebrew
provides(Homebrew.HB, "cfitsio", libcfitsio, os=:Darwin)
end
@BinDeps.install Dict(:libcfitsio => :libcfitsio)
if iswindows()
pop!(BinDeps.defaults)
end |
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'test/unit'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'sc2parse'
class Test::Unit::TestCase
end |
layout: post
title: CentOS5.4LAN
categories:
- Cent OS
- Lavie M
tags:
- AirStation
- WPA
- "LAN"
status: publish
type: post
published: true
meta:
_edit_last: '2'
_wp_old_slug: a
author:
login: yokoshima
email: k.yokoshima@gmail.com
display_name: yokoshima
first_name: ''
last_name: ''
<p><a href="lavie-m%E3%81%ABcentos%E3%82%92%E5%85%A5%E3%82%8C%E3%81%A6%E4%BD%BF%E3%81%A3%E3%81%A6%E3%81%BF%E3%82%8B/">Lavie MCentOS</a></p>
<p>CentOS5.4Lavie MLAN<br />
</p>
<p><a href="http:
</p>
<p><br />
CentOS5.43.9)<br />
NEC Lavie M LM700/7<br />
LAN Bufferlo AirStation WHR-G</p>
<p>LANGUI
<p>OS</p>
<pre lang="bash">
# lspci
</pre>
<p></p>
<pre lang="bash">
02:09.0 Ethernet controller: Atheros Communications Inc. Atheros AR5001X+ Wireless Network Adapter (rev 01)
</pre>
<p>Atheros AR5001X+LAN</p>
<p><br />
</p>
<pre lang="bash">
# ls /lib/modules/2.6.18-164.el5/kernel/drivers/net/wireless
</pre>
<p>ath5k<br />
Atheros AR5001X+<br />
5k→5000<br />
ath<br />
</p>
<p></p>
<pre lang="bash">
# lsmod
</pre>
<p>ath5k<br />
</p>
<h4></h4>
<p>iwconfig</p>
<p>LANGUI
<pre>
Error for wireless request "Set Mode" (8B06):
Set failed on deice wlan0: invalid argument
Error for wireless request "Set requency"(8B04):
invalid argument "".
</pre>
<p><br />
/etc/sysconfig/networks-scripts/ifcfg-wlan0</p>
<pre lang="ini">
CHANNEL=
</pre>
<p>GUI<br />
<br />
</p>
<pre>
Error for wireless request "Set requency"(8B04):
invalid argument "".
</pre>
<p>SetModeMODE=Auto<br />
</p>
<p>GUI<br />
ifcfg-wlan0<br />
</p>
<pre lang="bash">
# iwlist wlan0 scanning
Cell 02 - Address: (MAC)
ESSID: SSID
</pre>
<p>iwconfig<br />
</p>
<pre>
Error for wireless request "Set requency"(8B04):
invalid argument "".
</pre>
<p></p>
<h4></h4>
<p><br />
AOSS(AirStation One-Touch Secure System)<br />
WPA-PSK-AES<br />
WPA-PSK-TKIP<br />
WEP128<br />
WEP64</p>
<p>WPA-PSK-AES<br />
WPAWEP</p>
<p><a href="http://e-words.jp/w/WPA.html">WPA Wi-Fi Protected Access - /// IT</a></p>
<p>WPALinuxLANiwconfig<br />
wpa_supplicant</p>
<p><br />
<a href="http://space.geocities.jp/wireless_defence/html/30wpa_supplicant.htm">wpa_supplicant</a><br />
<a href="http:
<a href="http://goegoe-linux.blogspot.com/2008/06/<API key>.html"> Linux : CentOS+INSPIRON 700m (WPA-PSK)</a></p>
<p>wpa_supplicantyum</p>
<pre lang="bash">
# yum install wpa_supplicant
</pre>
<p>wpa_supplicant<br />
wpa_supplicant<br />
</p>
<pre lang="bash">
# vi /etc/sysconfig/wpa_supplicant
INTERFACES="-i wlan0"
DRIVERS="-D wext"
</pre>
<p>/etc/wpa_supplicant/wpa_supplicant.conf</p>
<pre lang="bash">
# vi /etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="SSID"
proto=WPA
pairwise=CCMP
group=CCMP
psk=()
}
</pre>
<p>(SSID)AirStationSSID<br />
()<br />
wpa_passphrase<br />
SSIDAAAAAAAAAAA</p>
<pre lang="bash">
# wpa_passphrase AAA AAAAAAAA
network={
ssid="AAA"
#psk="AAAAAAAA"
psk=2f2681c2d3d2d8d1e
</pre>
<p>SSID<br />
wpa_supplicant</p> |
from azure.iot.modelsrepository import (
<API key>,
<API key>,
<API key>,
)
from azure.core.exceptions import (
<API key>,
ServiceRequestError,
<API key>,
HttpResponseError,
)
import pprint
dtmi = "dtmi:com:example:<API key>;1"
dtmi2 = "dtmi:com:example:<API key>;2"
# By default the clients in this sample will use the Azure Device Models Repository endpoint
# See <API key>.py for examples of alternate configurations
def get_model():
# This API call will return a dictionary mapping DTMI to its corresponding model from
# a DTDL document at the specified endpoint
with <API key>() as client:
model_map = client.get_models(dtmi)
pprint.pprint(model_map)
def get_models():
# This API call will return a dictionary mapping DTMIs to corresponding models for from the
# DTDL documents at the specified endpoint
with <API key>() as client:
model_map = client.get_models([dtmi, dtmi2])
pprint.pprint(model_map)
def <API key>():
# This API call will return a dictionary mapping DTMIs to corresponding models for all elements
# of an expanded DTDL document at the specified endpoint
with <API key>() as client:
model_map = client.get_models(
dtmis=[dtmi], <API key>=<API key>
)
pprint.pprint(model_map)
def <API key>():
# This API call will return a dictionary mapping the specified DTMI to its corresponding model,
# from a DTDL document at the specified endpoint, as well as the DTMIs and models for all
# dependencies on components and interfaces
with <API key>() as client:
model_map = client.get_models(dtmis=[dtmi], <API key>=<API key>)
pprint.pprint(model_map)
def <API key>():
# Various errors that can be raised when fetching models
try:
with <API key>() as client:
model_map = client.get_models(dtmi)
pprint.pprint(model_map)
except <API key> as e:
print("The model could not be found")
print("{}".format(e.message))
except ServiceRequestError as e:
print("There was an error sending the request")
print("{}".format(e.message))
except <API key> as e:
print("No response was received")
print("{}".format(e.message))
except HttpResponseError as e:
print("HTTP Error Response received")
print("{}".format(e.message)) |
using System;
using System.Collections.Generic;
using Jison;
namespace Sheet
{
public class Expression : ParserValue
{
public bool ValueSet = false;
public string Type;
public bool BoolValue;
public double DoubleValue;
public List<Expression> Children;
public Expression()
{
}
public new Expression Clone()
{
var expression = new Expression();
expression.Text = Text;
if (Loc != null)
{
expression.Loc = Loc.Clone();
}
expression.Leng = Leng;
expression.LineNo = LineNo;
expression.ValueSet = ValueSet;
expression.Type = Type;
expression.ValueSet = ValueSet;
expression.BoolValue = BoolValue;
if (Children != null)
{
expression.Children = new JList<Expression>();
foreach (var child in Children)
{
if (this != child)
{
expression.Children.Add(child.Clone());
}
}
}
expression.DoubleValue = DoubleValue;
return expression;
}
public Expression(string value)
{
Text = value;
}
public bool ToBool()
{
ValueSet = true;
BoolValue = Convert.ToBoolean (Text);
Type = "bool";
Text = BoolValue.ToString();
return BoolValue;
}
public void Set(bool value) {
BoolValue = value;
ValueSet = true;
Type = "bool";
}
public double ToDouble()
{
if (Type == "double")
{
return DoubleValue;
}
ValueSet = true;
if (!String.IsNullOrEmpty (Text) || DoubleValue != 0) {
double num;
if (double.TryParse(Text, out num)) {
DoubleValue = num;
} else {
DoubleValue = (DoubleValue != 0 ? DoubleValue : 0);
}
ValueSet = true;
} else {
DoubleValue = 0;
}
Type = "double";
return DoubleValue;
}
public bool IsNumeric()
{
if (Type == "double" || DoubleValue > 0)
{
Type = "double";
return true;
}
double num;
if (double.TryParse(Text, out num))
{
ValueSet = true;
Type = "double";
return true;
}
return false;
}
public void Add(Expression value)
{
value.ToDouble();
DoubleValue += value.DoubleValue;
Type = "double";
Text = DoubleValue.ToString();
}
public void Set(double value) {
DoubleValue = value;
Text = value.ToString();
ValueSet = true;
Type = "double";
}
public string ToString()
{
ValueSet = true;
return Text;
}
public void Set(string value) {
Text = value;
ValueSet = true;
Type = "string";
}
public void Concat(Expression value)
{
Text += value.Text;
Type = "string";
}
public void Push(Expression value)
{
if (Children == null) {
Children = new List<Expression>()
{
this
};
}
Children.Add (value);
}
}
} |
import {BotConfig} from './bot-config.model';
/**
* Tests the BotConfig model behaves as expected.
*
* @author gazbert
*/
describe('BotStatus model tests', () => {
it('should have correct initial values', () => {
const bot = new BotConfig('gdax-1', 'GDAX Bot', 'https://jakku.com/api/v1', 'rey', 'force');
expect(bot.id).toBe('gdax-1');
expect(bot.name).toBe('GDAX Bot');
expect(bot.baseUrl).toBe('https://jakku.com/api/v1');
expect(bot.username).toBe('rey');
expect(bot.password).toBe('force');
});
it('should clone itself', () => {
const bot = new BotConfig('gdax-1', 'GDAX Bot', 'https://jakku.com/api/v1', 'rey', 'force');
const clone = bot.clone();
expect(bot).toEqual(clone);
});
}); |
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline; }
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block; }
body {
line-height: 1; }
ol, ul {
list-style: none; }
blockquote, q {
quotes: none; }
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none; }
table {
border-collapse: collapse;
border-spacing: 0; }
body {
background: #fff;
font: 14px/21px "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #444;
-<API key>: antialiased; /* Fix for webkit rendering */
-<API key>: 100%;
}
h1, h2, h3, h4, h5, h6 {
color: #181818;
font-family: "Georgia", "Times New Roman", serif;
font-weight: normal; }
h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { font-weight: inherit; }
h1 { font-size: 46px; line-height: 50px; margin-bottom: 14px;}
h2 { font-size: 35px; line-height: 40px; margin-bottom: 10px; }
h3 { font-size: 28px; line-height: 34px; margin-bottom: 8px; }
h4 { font-size: 21px; line-height: 30px; margin-bottom: 4px; }
h5 { font-size: 17px; line-height: 24px; }
h6 { font-size: 14px; line-height: 21px; }
.subheader { color: #777; }
p { margin: 0 0 20px 0; }
p img { margin: 0; }
p.lead { font-size: 21px; line-height: 27px; color: #777; }
em { font-style: italic; }
strong { font-weight: bold; color: #333; }
small { font-size: 80%; }
/* Blockquotes */
blockquote, blockquote p { font-size: 17px; line-height: 24px; color: #777; font-style: italic; }
blockquote { margin: 0 0 20px; padding: 9px 20px 0 19px; border-left: 1px solid #ddd; }
blockquote cite { display: block; font-size: 12px; color: #555; }
blockquote cite:before { content: "\2014 \0020"; }
blockquote cite a, blockquote cite a:visited, blockquote cite a:visited { color: #555; }
hr { border: solid #ddd; border-width: 1px 0 0; clear: both; margin: 10px 0 30px; height: 0; }
a, a:visited { color: #333; text-decoration: underline; outline: 0; }
a:hover, a:focus { color: #000; }
p a, p a:visited { line-height: inherit; }
ul, ol { margin-bottom: 20px; }
ul { list-style: none outside; }
ol { list-style: decimal; }
ol, ul.square, ul.circle, ul.disc { margin-left: 30px; }
ul.square { list-style: square outside; }
ul.circle { list-style: circle outside; }
ul.disc { list-style: disc outside; }
ul ul, ul ol,
ol ol, ol ul { margin: 4px 0 5px 30px; font-size: 90%; }
ul ul li, ul ol li,
ol ol li, ol ul li { margin-bottom: 6px; }
li { line-height: 18px; margin-bottom: 12px; }
ul.large li { line-height: 21px; }
li p { line-height: 21px; }
img.scale-with-grid {
max-width: 100%;
height: auto; }
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
background: #eee; /* Old browsers */
background: #eee -moz-linear-gradient(top, rgba(255,255,255,.2) 0%, rgba(0,0,0,.2) 100%); /* FF3.6+ */
background: #eee -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.2)), color-stop(100%,rgba(0,0,0,.2))); /* Chrome,Safari4+ */
background: #eee -<API key>(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* Chrome10+,Safari5.1+ */
background: #eee -o-linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* Opera11.10+ */
background: #eee -ms-linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* IE10+ */
background: #eee linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* W3C */
border: 1px solid #aaa;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
-moz-border-radius: 3px;
-<API key>: 3px;
border-radius: 3px;
color: #444;
display: inline-block;
font-size: 11px;
font-weight: bold;
text-decoration: none;
text-shadow: 0 1px rgba(255, 255, 255, .75);
cursor: pointer;
margin-bottom: 20px;
line-height: normal;
padding: 8px 10px;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif; }
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover {
color: #222;
background: #ddd; /* Old browsers */
background: #ddd -moz-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(0,0,0,.3) 100%); /* FF3.6+ */
background: #ddd -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.3)), color-stop(100%,rgba(0,0,0,.3))); /* Chrome,Safari4+ */
background: #ddd -<API key>(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* Chrome10+,Safari5.1+ */
background: #ddd -o-linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* Opera11.10+ */
background: #ddd -ms-linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* IE10+ */
background: #ddd linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* W3C */
border: 1px solid #888;
border-top: 1px solid #aaa;
border-left: 1px solid #aaa; }
.button:active,
button:active,
input[type="submit"]:active,
input[type="reset"]:active,
input[type="button"]:active {
border: 1px solid #666;
background: #ccc; /* Old browsers */
background: #ccc -moz-linear-gradient(top, rgba(255,255,255,.35) 0%, rgba(10,10,10,.4) 100%); /* FF3.6+ */
background: #ccc -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.35)), color-stop(100%,rgba(10,10,10,.4))); /* Chrome,Safari4+ */
background: #ccc -<API key>(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* Chrome10+,Safari5.1+ */
background: #ccc -o-linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* Opera11.10+ */
background: #ccc -ms-linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* IE10+ */
background: #ccc linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* W3C */ }
.button.full-width,
button.full-width,
input[type="submit"].full-width,
input[type="reset"].full-width,
input[type="button"].full-width {
width: 100%;
padding-left: 0 !important;
padding-right: 0 !important;
text-align: center; }
/* Fix for odd Mozilla border & padding issues */
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
form {
margin-bottom: 20px; }
form#search {
margin-bottom: 0; }
fieldset {
margin-bottom: 20px; }
input[type="text"],
input[type="password"],
input[type="email"],
textarea,
select {
border: 1px solid #ccc;
padding: 6px 4px;
outline: none;
-moz-border-radius: 2px;
-<API key>: 2px;
border-radius: 2px;
font: 13px "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
margin: 0;
width: 210px;
max-width: 100%;
display: block;
margin-bottom: 20px;
background: #fff; }
select {
padding: 0; }
input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus,
textarea:focus {
border: 1px solid #aaa;
color: #444;
-moz-box-shadow: 0 0 3px rgba(0,0,0,.2);
-webkit-box-shadow: 0 0 3px rgba(0,0,0,.2);
box-shadow: 0 0 3px rgba(0,0,0,.2); }
textarea {
min-height: 60px; }
label,
legend {
display: block;
font-weight: bold;
font-size: 13px; }
select {
width: 220px; }
input[type="checkbox"] {
display: inline; }
label span,
legend span {
font-weight: normal;
font-size: 13px;
color: #444; }
.remove-bottom { margin-bottom: 0 !important; }
.half-bottom { margin-bottom: 10px !important; }
.add-bottom { margin-bottom: 20px !important; } |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Language" content="en">
<meta name="author" content="Sanjeev Kumar Pandit">
<meta name="description" content="My personal website">
<meta name="keywords" content="blog,developer,personal">
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="php-xdebug"/>
<meta name="<TwitterConsumerkey>" content="My personal website"/>
<meta property="og:title" content="php-xdebug" />
<meta property="og:description" content="My personal website" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://sanjeevkpandit.github.io/tags/php-xdebug/" />
<meta property="og:updated_time" content="2016-05-25T00:00:00+00:00" />
<title>Tag: php-xdebug · Sanjeev Kumar Pandit</title>
<link rel="canonical" href="http://sanjeevkpandit.github.io/tags/php-xdebug/">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700%7CMerriweather:300,700%7CSource+Code+Pro:400,700&display=swap" rel="stylesheet">
<link rel="preload" href="/fonts/forkawesome-webfont.woff2?v=1.1.7" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/coder.min.<SHA256-like>.css" integrity="sha256-9IpNqb0yzsr/kHF66FUpQR3Qh8EPwN/KnJwynHMn5eE=" crossorigin="anonymous" media="screen" />
<link rel="stylesheet" href="/css/coder-dark.min.<SHA256-like>.css" integrity="<API key>=" crossorigin="anonymous" media="screen" />
<link rel="icon" type="image/png" href="/img/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/img/favicon-16x16.png" sizes="16x16">
<link rel="apple-touch-icon" href="/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
<link rel="alternate" type="application/rss+xml" href="/tags/php-xdebug/index.xml" title="Sanjeev Kumar Pandit" />
<script defer src="https://twemoji.maxcdn.com/v/13.0.1/twemoji.min.js"
integrity="sha384-5f4X0lBluNY/<API key>" crossorigin="anonymous"></script>
<meta name="generator" content="Hugo 0.80.0" />
</head>
<body class="colorscheme-auto"
onload=" twemoji.parse(document.body); "
>
<div class="float-container">
<a id="dark-mode-toggle" class="colorscheme-toggle">
<i class="fa fa-adjust fa-fw" aria-hidden="true"></i>
</a>
</div>
<main class="wrapper">
<nav class="navigation">
<section class="container">
<a class="navigation-title" href="/">
Sanjeev Kumar Pandit
</a>
<input type="checkbox" id="menu-toggle" />
<label class="menu-button float-right" for="menu-toggle">
<i class="fa fa-bars fa-fw" aria-hidden="true"></i>
</label>
<ul class="navigation-list">
<li class="navigation-item">
<a class="navigation-link" href="/posts/">Posts</a>
</li>
<li class="navigation-item">
<a class="navigation-link" href="/about/">About</a>
</li>
</ul>
</section>
</nav>
<div class="content">
<section class="container list">
<h1 class="title">
<a class="title-link" href="http://sanjeevkpandit.github.io/tags/php-xdebug/">Tag: php-xdebug</a>
</h1>
<ul>
<li>
<span class="date">May 25, 2016</span>
<a class="title" href="/posts/<API key>/">Setup XDebug in PhpStorm</a>
</li>
<li>
<span class="date">May 24, 2016</span>
<a class="title" href="/posts/<API key>/">Setup XDebug in Ubuntu</a>
</li>
</ul>
</section>
</div>
<footer class="footer">
<section class="container">
©
2016 -
2021
Sanjeev Kumar Pandit
·
Powered by <a href="https:
</section>
</footer>
</main>
<script src="/js/dark-mode.min.<SHA256-like>.js"></script>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
(function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https:
ga('create', 'UA-78879488-1', 'auto');
ga('send', 'pageview');
}
</script>
</body>
</html> |
package se.atg.sam.ui.rest;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.junit.Assert;
import org.junit.Test;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import se.atg.sam.model.auth.User;
import se.atg.sam.ui.rest.InfoResource.Info;
import se.atg.sam.ui.rest.integrationtest.helpers.TestHelper;
public class SmokeTest {
@Inject
private WebTarget testEndpoint;
@Inject
private Client client;
@Inject @Named("basic")
private Client basicAuthClient;
@Inject @Named("anonymous")
private Client anonymousAuthClient;
@Test
public void testStartPage() {
final Response response = client.target(testEndpoint.getUriBuilder().replacePath("/"))
.request(MediaType.TEXT_HTML_TYPE)
.get();
TestHelper.assertSuccessful(response);
}
@Test
public void testDocumentation() {
final Response response = client.target(testEndpoint.getUriBuilder().replacePath("/docs/"))
.request(MediaType.TEXT_HTML_TYPE)
.get();
TestHelper.assertSuccessful(response);
}
@Test
public void testInfo() {
final Response infoResponse = testEndpoint.path("info")
.request(MediaType.<API key>)
.get();
TestHelper.assertSuccessful(infoResponse);
final Info info = infoResponse.readEntity(InfoResource.Info.class);
final Response <API key> = client.target(info.releaseNotes)
.request(MediaType.TEXT_HTML_TYPE)
.get();
TestHelper.assertSuccessful(<API key>);
}
@Test
public void <API key>() {
final Response response = anonymousAuthClient.target(testEndpoint.getUriBuilder())
.path("oauth2").path("user")
.request(MediaType.<API key>)
.get();
TestHelper.<API key>(response);
}
@Test
public void basicAuthentication() {
final Response response = basicAuthClient.target(testEndpoint.getUriBuilder())
.path("oauth2").path("user")
.request(MediaType.<API key>)
.get();
TestHelper.assertSuccessful(response);
final User user = response.readEntity(User.class);
Assert.assertEquals("integration-test", user.name);
}
@Test
public void tokenAuthentication() {
final Response response = testEndpoint
.path("oauth2").path("user")
.request(MediaType.<API key>)
.get();
TestHelper.assertSuccessful(response);
final User user = response.readEntity(User.class);
Assert.assertEquals("integration-test", user.name);
}
} |
<div class="row">
<div class="container">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<table class="table table-responsive table-hover">
<thead>
<tr>
<th colspan="4" style="text-align:center">THÔNG TINH SINH VIÊN <a herf='javascript:void(0)'><?php echo $sinhvien->Mssv; ?></a></th>
</tr>
</thead>
<tbody>
<tr>
<th>Ngày sinh:</th>
<td><?php echo $sinhvien->Ngaysinh; ?></td>
<th>Quê quán:</th>
<td><?php echo $sinhvien->Quequan; ?></td>
</tr>
<tr>
<th>Mã ngành:</th>
<td><?php echo $nganh->Tennganh; ?></td>
<th>Mã khóa học:</th>
<td><?php echo $sinhvien->Makhoahoc; ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div> |
import { getPkgReleases } from '..';
import * as httpMock from '../../../test/http-mock';
import { getName } from '../../../test/util';
import * as _hostRules from '../../util/host-rules';
import * as github from '.';
jest.mock('../../util/host-rules');
const hostRules: any = _hostRules;
const githubApiHost = 'https://api.github.com';
const <API key> = 'https://git.enterprise.com';
describe(getName(), () => {
beforeEach(() => {
jest.resetAllMocks();
hostRules.hosts = jest.fn(() => []);
hostRules.find.mockReturnValue({
token: 'some-token',
});
});
describe('getDigest', () => {
const lookupName = 'some/dep';
const tag = 'v1.2.0';
it('returns null if no token', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/commits?per_page=1`)
.reply(200, []);
const res = await github.getDigest({ lookupName }, null);
expect(res).toBeNull();
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('returns digest', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/commits?per_page=1`)
.reply(200, [{ sha: 'abcdef' }]);
const res = await github.getDigest({ lookupName }, null);
expect(res).toBe('abcdef');
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('returns commit digest', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/git/refs/tags/${tag}`)
.reply(200, { object: { type: 'commit', sha: 'ddd111' } });
const res = await github.getDigest({ lookupName }, tag);
expect(res).toBe('ddd111');
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('returns tagged commit digest', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/git/refs/tags/${tag}`)
.reply(200, {
object: { type: 'tag', url: `${githubApiHost}/some-url` },
})
.get('/some-url')
.reply(200, { object: { type: 'commit', sha: 'ddd111' } });
const res = await github.getDigest({ lookupName }, tag);
expect(res).toBe('ddd111');
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('warns if unknown ref', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/git/refs/tags/${tag}`)
.reply(200, { object: { sha: 'ddd111' } });
const res = await github.getDigest({ lookupName }, tag);
expect(res).toBeNull();
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('returns null for missed tagged digest', async () => {
httpMock
.scope(githubApiHost)
.get(`/repos/${lookupName}/git/refs/tags/${tag}`)
.reply(200, {});
const res = await github.getDigest({ lookupName: 'some/dep' }, 'v1.2.0');
expect(res).toBeNull();
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('supports ghe', async () => {
httpMock
.scope(<API key>)
.get(`/api/v3/repos/${lookupName}/git/refs/tags/${tag}`)
.reply(200, { object: { type: 'commit', sha: 'ddd111' } })
.get(`/api/v3/repos/${lookupName}/commits?per_page=1`)
.reply(200, [{ sha: 'abcdef' }]);
const sha1 = await github.getDigest(
{ lookupName, registryUrl: <API key> },
null
);
const sha2 = await github.getDigest(
{ lookupName: 'some/dep', registryUrl: <API key> },
'v1.2.0'
);
expect(httpMock.getTrace()).toMatchSnapshot();
expect(sha1).toBe('abcdef');
expect(sha2).toBe('ddd111');
});
});
describe('getReleases', () => {
beforeEach(() => {
jest.resetAllMocks();
hostRules.hosts = jest.fn(() => []);
hostRules.find.mockReturnValue({
token: 'some-token',
});
});
const depName = 'some/dep2';
it('returns tags', async () => {
const tags = [{ name: 'v1.0.0' }, { name: 'v1.1.0' }];
const releases = tags.map((item, idx) => ({
tag_name: item.name,
published_at: new Date(idx),
prerelease: !!idx,
}));
httpMock
.scope(githubApiHost)
.get(`/repos/${depName}/tags?per_page=100`)
.reply(200, tags)
.get(`/repos/${depName}/releases?per_page=100`)
.reply(200, releases);
const res = await getPkgReleases({ datasource: github.id, depName });
expect(res).toMatchSnapshot();
expect(res.releases).toHaveLength(2);
expect(httpMock.getTrace()).toMatchSnapshot();
});
it('supports ghe', async () => {
const body = [{ name: 'v1.0.0' }, { name: 'v1.1.0' }];
httpMock
.scope(<API key>)
.get(`/api/v3/repos/${depName}/tags?per_page=100`)
.reply(200, body)
.get(`/api/v3/repos/${depName}/releases?per_page=100`)
.reply(404);
const res = await github.getReleases({
registryUrl: 'https://git.enterprise.com',
lookupName: depName,
});
expect(res).toMatchSnapshot();
expect(httpMock.getTrace()).toMatchSnapshot();
});
});
}); |
if (!linz) {
var linz = {};
}
(function () {
var adminPath;
$(document).ready(function () {
// add form validation
$('form[<API key>="true"]').bootstrapValidator({});
// add delete prompt
$('[data-linz-control="delete"]').click(function () {
if ($(this).attr('data-linz-disabled')) {
// no confirmation for disabled button
return false;
}
if (confirm('Are you sure you want to delete this record?')) {
return true;
}
return false;
});
// add disabled alert
$('[data-linz-disabled="true"]').click(function () {
alert($(this).attr('<API key>'));
return false;
});
// initialize multiselect
$('.multiselect').not(function (item, el) {
return ($(el).closest('span.controlField').length === 1) ? true : false;
}).multiselect({
buttonContainer: '<div class="btn-group <API key>" />'
});
// assign ckeditor editor (classic view using iframe)
$('.ckeditor').each(function () {
var editorConfig = {
customConfig: $(this).attr('<API key>') || adminPath + '/public/js/<API key>.js',
contentsCss: $(this).attr('<API key>') ? $(this).attr('<API key>').split(',') : adminPath + '/public/css/<API key>.css'
};
// check if there are any widgets to include
var widgets = $(this).attr('<API key>') ? $(this).attr('<API key>').split(',') : [];
if (widgets.length !== 0) {
var plugins = [];
widgets.forEach(function (widget) {
// widget is provided in the format {name}:{path}
var widgetProperties = widget.split(':');
// loads external plugins
CKEDITOR.plugins.addExternal(widgetProperties[0], widgetProperties[1], '');
plugins.push(widgetProperties[0]);
});
editorConfig.extraPlugins = plugins.join(',');
}
CKEDITOR.replace( this, editorConfig);
});
// assign ckeditor inline editor
$('.ckeditor-inline').each(function () {
var editorConfig = {
customConfig: $(this).attr('<API key>') || adminPath + '/public/js/<API key>.js'
};
// check if there are any widgets to include
var widgets = $(this).attr('<API key>') ? $(this).attr('<API key>').split(',') : [];
if (widgets.length !== 0) {
var plugins = [];
widgets.forEach(function (widget) {
// widget is provided in the format {name}:{path}
var widgetProperties = widget.split(':');
// loads external plugins
CKEDITOR.plugins.addExternal(widgetProperties[0], widgetProperties[1], '');
plugins.push(widgetProperties[0]);
});
editorConfig.extraPlugins = plugins.join(',');
}
CKEDITOR.inline( this, editorConfig);
});
// We know the page has loaded at this point, so we can re-enable the modals.
$('[data-linz-modal]').removeClass('disabled');
// Add ability to open model action in a modal.
$('[data-linz-modal]').click(function (event) {
event.preventDefault();
var button = $(this);
if (button.attr('data-linz-disabled') === 'true') {
return;
}
var url = button[0].nodeName === 'BUTTON' ? button.attr('data-href') : button.attr('href');
// open modal and load URL
$('#linzModal').modal().load(url);
// remove modal shown event
$('#linzModal').off('shown.bs.modal');
// re-bind the shown event
$('#linzModal').on('shown.bs.modal', function (e) {
// add form validation
$(this).find('form[<API key>="true"]').bootstrapValidator({});
if (button.attr('<API key>')) {
// run custom function if provided after modal is shown
window[button.attr('<API key>')]();
}
});
});
// convert UTC to local datetime
$('[<API key>]').each(function () {
var dateFormat = $(this).attr('<API key>') || 'ddd DD/MM/YYYY';
var localDateTime = moment(new Date($(this).attr('data-linz-utc-date'))).format(dateFormat);
$(this).html(localDateTime);
});
loadDatepicker();
<API key>();
});
function setPath(path) {
adminPath = path;
}
function eventPreventDefault (e) {
e.preventDefault();
}
// Trigger the necessary changes for the form validation
// https://github.com/nghuuphuoc/bootstrapvalidator/blob/<SHA1-like>/src/js/bootstrapValidator.js#L49
function triggerChange (field) {
field.trigger('keyup');
field.trigger('input');
}
function loadDatepicker() {
if ($('[data-ui-datepicker]').length && !$('[name="linzTimezoneOffset"]').length) {
// Set the timezone offset in a hidden input element.
var timezoneInput = document.createElement('input');
timezoneInput.setAttribute('type', 'hidden');
timezoneInput.setAttribute('name', 'linzTimezoneOffset');
timezoneInput.setAttribute('value', moment().format('Z'));
$('[data-ui-datepicker]').parents('form').prepend(timezoneInput);
}
if ($('[data-ui-datepicker]').length) {
$('[data-ui-datepicker]').each(function () {
var field = $(this);
// Stop processing if the date picker has already been setup.
if (field.data('DateTimePicker')) {
return;
}
// Support format and useCurrent customissations via the widget.
var format = field.attr('<API key>') || 'YYYY-MM-DD';
var useCurrent = field.attr('<API key>') === 'true';
var sideBySide = field.attr('<API key>') === 'true';
// Setup the datetimepicker plugin.
field.datetimepicker({
format: format,
sideBySide: sideBySide,
useCurrent: useCurrent,
});
// Trigger the change event on load for modals.
field.change();
// Trigger the change event for the field whenever the datepicker is shown or changed.
field.on({
'dp.change': function() {
triggerChange(field);
},
'dp.show': function () {
triggerChange(field);
},
});
// Prevent manually editing the date field.
field.bind('paste', eventPreventDefault);
field.on('keydown', eventPreventDefault);
});
}
}
function <API key>() {
if ($('[data-ui-datepicker]').length) {
$('[data-ui-datepicker]').each(function () {
var field = $(this);
var dateValue = field.attr('<API key>');
// Don't default the date, only continue if there is one already.
if (!dateValue) {
return;
}
var offset = field.data('utc-offset');
var clientDateValue = offset ? moment(dateValue).utcOffset(offset) : moment(dateValue);
field.data('DateTimePicker').date(clientDateValue);
});
}
}
function isTemplateSupported() {
return 'content' in document.createElement('template');
}
function <API key> () {
$('[data-linz-control="delete"]').click(function () {
if ($(this).attr('data-linz-disabled')) {
// no confirmation for disabled button
return false;
}
if (confirm('Are you sure you want to delete this record?')) {
return true;
}
return false;
});
}
function addDisabledBtnAlert () {
$('[data-linz-disabled="true"]').click(function () {
alert($(this).attr('<API key>'));
return false;
});
}
function <API key> () {
$('[data-linz-control="config-default"]').click(function () {
if ($(this).attr('data-linz-disabled')) {
// no confirmation for disabled button
return false;
}
if (confirm('Are you sure you want to reset this config to default?')) {
return true;
}
});
}
linz.setPath = setPath;
linz.loadDatepicker = loadDatepicker;
linz.<API key> = <API key>;
linz.isTemplateSupported = isTemplateSupported;
linz.<API key> = <API key>;
linz.addDisabledBtnAlert = addDisabledBtnAlert;
linz.<API key> = <API key>;
})(); |
#!/usr/bin/env python3
# Create training sets. This short function does nothing
import csv, os, sys, random
from collections import Counter
import numpy as np
import pandas as pd
# import utils
currentdir = os.path.dirname(__file__)
libpath = os.path.join(currentdir, '../lib')
sys.path.append(libpath)
import SonicScrewdriver as utils
alreadyhave = pd.read_csv('confidentvolumes.csv', dtype = 'object', index_col = 'docid', na_filter = False)
newlytagged = pd.read_csv('taggedvolumes.csv', dtype = 'object', index_col = 'docid', na_filter = False)
both = pd.concat([alreadyhave, newlytagged])
both.to_csv('maintrainingset.csv', index_label = 'docid') |
package ch.jalu.injector.testing.extension;
import ch.jalu.injector.Injector;
import ch.jalu.injector.InjectorBuilder;
import ch.jalu.injector.handlers.Handler;
import ch.jalu.injector.handlers.postconstruct.<API key>;
import ch.jalu.injector.testing.InjectDelayed;
import ch.jalu.injector.utils.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.List;
/**
* Statement for initializing {@link ch.jalu.injector.testing.InjectDelayed} fields. These fields are
* constructed after {@link ch.jalu.injector.testing.BeforeInjecting} and before JUnit's @Before.
*/
public class RunDelayedInjects {
private Object target;
public RunDelayedInjects(Object target) {
this.target = target;
}
public void evaluate() {
Injector injector = getInjector();
for (Field field : ExtensionUtils.getAnnotatedFields(target.getClass(), InjectDelayed.class)) {
if (ReflectionUtils.getFieldValue(field, target) != null) {
throw new <API key>("Field with @InjectDelayed must be null on startup. "
+ "Field '" + field.getName() + "' is not null");
}
Object object = injector.getSingleton(field.getType());
ReflectionUtils.setField(field, target, object);
}
}
/**
* Override this method to provide your own injector in the test runner, e.g. if your application uses
* custom instantiation methods or annotation behavior.
*
* @return the injector used to set {@link ch.jalu.injector.testing.InjectDelayed} fields
*/
protected Injector getInjector() {
List<Handler> <API key> = InjectorBuilder.<API key>("");
return new InjectorBuilder()
.addHandlers(
new AnnotationResolver(target),
new <API key>(target),
new <API key>())
.addHandlers(<API key>)
.create();
}
} |
import { Component } from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import { player } from '../../models/player';
import {AngularFireDatabase, <API key>, <API key>} from 'angularfire2/database';
import {stringify} from "@angular/core/src/util";
import 'rxjs/add/operator/take';
@Component({
selector: 'page-show',
templateUrl: 'show.html'
})
export class ShowPage {
player = {} as player;
name:<API key><player>;
playerRef$: <API key><player[]>;
constructor(public navCtrl: NavController,public navPrams: NavParams, private data: AngularFireDatabase) {
this.name = this.navPrams.get('playerInfo');
this.playerRef$ = this.data.list('Players');
}
} |
var expect = require('chai').expect;
describe('data adapter', function() {
it('should throw error if data adapter does not pass interface checker', function*() {
var err = "The passed in data adapter has the following issue:"
+ "\nMissing insert method"
+ "\nMissing bulkInsert method"
+ "\nMissing update method"
+ "\nMissing remove method"
+ "\nMissing bulkRemove method"
+ "\nMissing find method"
+ "\nMissing findAll method"
+ "\nMissing startTransaction method"
+ "\nMissing commitTransaction method"
+ "\nMissing rollbackTransaction method";
expect(function() {
require('./data-access/index').create({});
}).to.throw(err);
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.