answer stringlengths 15 1.25M |
|---|
package com.github.steveice10.mc.auth.exception.property;
/**
* Thrown when an error occurs while validating a signature.
*/
public class <API key> extends PropertyException {
private static final long serialVersionUID = 1L;
public <API key>() {
}
public <API key>(String message) {
super(message);
}
public <API key>(String message, Throwable cause) {
super(message, cause);
}
public <API key>(Throwable cause) {
super(cause);
}
} |
<?php
namespace App\Observers;
use App\Models\ContactInformation;
class <API key>
{
public function saving(ContactInformation $contactInformation)
{
$checkFields = ['phone', 'email', 'facebook', 'line'];
if (!$contactInformation->isDirty($checkFields)) {
return;
}
foreach ($contactInformation->student->feedback as $feedback) {
foreach ($checkFields as $checkField) {
$feedback->$checkField = $feedback->{'include_' . $checkField}
? $contactInformation->$checkField : null;
}
// updated_at
$feedback->timestamps = false;
$feedback->save();
}
}
} |
<?php
namespace Itsup\Api\EndPoint\Campaign;
use Itsup\Api\EndPoint\<API key>;
/**
* @author Cyril LEGRAND <cyril@sctr.net>
*/
class SaleEndPoint extends <API key>
{
/**
* The model name.
*
* @var string
*/
protected $model = 'Campaign\Sale';
/**
* The API URI without the first "/".
*
* @var string
*/
protected $route = 'campaign/sale';
} |
// The LLVM Compiler Infrastructure
// This file is distributed under the University of Illinois Open Source
// This pass is used to make Pc relative loads of constants.
// For now, only Mips16 will use this.
// Loading constants inline is expensive on Mips16 and it's in general better
// to place the constant nearby in code space and then it can be loaded with a
// simple 16 bit load instruction.
// The constants can be not just numbers but addresses of functions and labels.
// This can be particularly helpful in static relocation mode for embedded
// non-linux targets.
#include "Mips.h"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "Mips16InstrInfo.h"
#include "MipsMachineFunction.h"
#include "MipsTargetMachine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_TYPE "<API key>"
STATISTIC(NumCPEs, "Number of constpool entries");
STATISTIC(NumSplit, "Number of uncond branches inserted");
STATISTIC(NumCBrFixed, "Number of cond branches fixed");
STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
// FIXME: This option should be removed once it has received sufficient testing.
static cl::opt<bool>
<API key>("<API key>", cl::Hidden, cl::init(true),
cl::desc("Align constant islands in code"));
// Rather than do make check tests with huge amounts of code, we force
// the test to use this amount.
static cl::opt<int> <API key>(
"<API key>",
cl::init(0),
cl::desc("Make small offsets be this amount for testing purposes"),
cl::Hidden);
// For testing purposes we tell it to not use relaxed load forms so that it
// will split blocks.
static cl::opt<bool> NoLoadRelaxation(
"<API key>",
cl::init(false),
cl::desc("Don't relax loads to long loads - for testing purposes"),
cl::Hidden);
static unsigned int branchTargetOperand(MachineInstr *MI) {
switch (MI->getOpcode()) {
case Mips::Bimm16:
case Mips::BimmX16:
case Mips::Bteqz16:
case Mips::BteqzX16:
case Mips::Btnez16:
case Mips::BtnezX16:
case Mips::JalB16:
return 0;
case Mips::BeqzRxImm16:
case Mips::BeqzRxImmX16:
case Mips::BnezRxImm16:
case Mips::BnezRxImmX16:
return 1;
}
llvm_unreachable("Unknown branch type");
}
static unsigned int <API key>(unsigned int Opcode) {
switch (Opcode) {
case Mips::Bimm16:
case Mips::BimmX16:
return Mips::BimmX16;
case Mips::Bteqz16:
case Mips::BteqzX16:
return Mips::BteqzX16;
case Mips::Btnez16:
case Mips::BtnezX16:
return Mips::BtnezX16;
case Mips::JalB16:
return Mips::JalB16;
case Mips::BeqzRxImm16:
case Mips::BeqzRxImmX16:
return Mips::BeqzRxImmX16;
case Mips::BnezRxImm16:
case Mips::BnezRxImmX16:
return Mips::BnezRxImmX16;
}
llvm_unreachable("Unknown branch type");
}
// FIXME: need to go through this whole constant islands port and check the math
// for branch ranges and clean this up and make some functions to calculate things
// that are done many times identically.
// Need to refactor some of the code to call this routine.
static unsigned int branchMaxOffsets(unsigned int Opcode) {
unsigned Bits, Scale;
switch (Opcode) {
case Mips::Bimm16:
Bits = 11;
Scale = 2;
break;
case Mips::BimmX16:
Bits = 16;
Scale = 2;
break;
case Mips::BeqzRxImm16:
Bits = 8;
Scale = 2;
break;
case Mips::BeqzRxImmX16:
Bits = 16;
Scale = 2;
break;
case Mips::BnezRxImm16:
Bits = 8;
Scale = 2;
break;
case Mips::BnezRxImmX16:
Bits = 16;
Scale = 2;
break;
case Mips::Bteqz16:
Bits = 8;
Scale = 2;
break;
case Mips::BteqzX16:
Bits = 16;
Scale = 2;
break;
case Mips::Btnez16:
Bits = 8;
Scale = 2;
break;
case Mips::BtnezX16:
Bits = 16;
Scale = 2;
break;
default:
llvm_unreachable("Unknown branch type");
}
unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
return MaxOffs;
}
namespace {
typedef MachineBasicBlock::iterator Iter;
typedef MachineBasicBlock::reverse_iterator ReverseIter;
MipsConstantIslands - Due to limited PC-relative displacements, Mips
requires constant pool entries to be scattered among the instructions
inside a function. To do this, it completely ignores the normal LLVM
constant pool; instead, it places constants wherever it feels like with
special instructions.
The terminology used in this pass includes:
Islands - Clumps of constants placed in the function.
Water - Potential places where an island could be formed.
CPE - A constant pool entry that has been placed somewhere, which
tracks a list of users.
class MipsConstantIslands : public MachineFunctionPass {
BasicBlockInfo - Information about the offset and size of a single
basic block.
struct BasicBlockInfo {
Offset - Distance from the beginning of the function to the beginning
of this basic block.
Offsets are computed assuming worst case padding before an aligned
block. This means that subtracting basic block offsets always gives a
conservative estimate of the real distance which may be smaller.
Because worst case padding is used, the computed offset of an aligned
block may not actually be aligned.
unsigned Offset;
Size - Size of the basic block in bytes. If the block contains
inline assembly, this is a worst case estimate.
The size does not include any alignment padding whether from the
beginning of the block, or from an aligned jump table at the end.
unsigned Size;
// FIXME: ignore LogAlign for this patch
unsigned postOffset(unsigned LogAlign = 0) const {
unsigned PO = Offset + Size;
return PO;
}
BasicBlockInfo() : Offset(0), Size(0) {}
};
std::vector<BasicBlockInfo> BBInfo;
WaterList - A sorted list of basic blocks where islands could be placed
(i.e. blocks that don't fall through to the following block, due
to a return, unreachable, or unconditional branch).
std::vector<MachineBasicBlock*> WaterList;
NewWaterList - The subset of WaterList that was created since the
previous iteration by inserting unconditional branches.
SmallSet<MachineBasicBlock*, 4> NewWaterList;
typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
CPUser - One user of a constant pool, keeping the machine instruction
pointer, the constant pool being referenced, and the max displacement
allowed from the instruction to the CP. The HighWaterMark records the
highest basic block where a new CPEntry can be placed. To ensure this
pass terminates, the CP entries are initially placed at the end of the
function and then move monotonically to lower addresses. The
exception to this rule is when the current CP entry for a particular
CPUser is out of range, but there is another CP entry for the same
constant value in range. We want to use the existing in-range CP
entry, but if it later moves out of range, the search for new water
should resume where it left off. The HighWaterMark is used to record
that point.
struct CPUser {
MachineInstr *MI;
MachineInstr *CPEMI;
MachineBasicBlock *HighWaterMark;
private:
unsigned MaxDisp;
unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
// with different displacements
unsigned LongFormOpcode;
public:
bool NegOk;
CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
bool neg,
unsigned longformmaxdisp, unsigned longformopcode)
: MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
NegOk(neg){
HighWaterMark = CPEMI->getParent();
}
getMaxDisp - Returns the maximum displacement supported by MI.
unsigned getMaxDisp() const {
unsigned xMaxDisp = <API key>?
<API key>: MaxDisp;
return xMaxDisp;
}
void setMaxDisp(unsigned val) {
MaxDisp = val;
}
unsigned getLongFormMaxDisp() const {
return LongFormMaxDisp;
}
unsigned getLongFormOpcode() const {
return LongFormOpcode;
}
};
CPUsers - Keep track of all of the machine instructions that use various
constant pools and their max displacement.
std::vector<CPUser> CPUsers;
CPEntry - One per constant pool entry, keeping the machine instruction
pointer, the constpool index, and the number of CPUser's which
reference this entry.
struct CPEntry {
MachineInstr *CPEMI;
unsigned CPI;
unsigned RefCount;
CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
: CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
};
CPEntries - Keep track of all of the constant pool entry machine
instructions. For each original constpool index (i.e. those that
existed upon entry to this pass), it keeps a vector of entries.
Original elements are cloned as we go along; the clones are
put in the vector of the original element, but have distinct CPIs.
std::vector<std::vector<CPEntry> > CPEntries;
ImmBranch - One per immediate branch, keeping the machine instruction
pointer, conditional or unconditional, the max displacement,
and (if isCond is true) the corresponding unconditional branch
opcode.
struct ImmBranch {
MachineInstr *MI;
unsigned MaxDisp : 31;
bool isCond : 1;
int UncondBr;
ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
: MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
};
ImmBranches - Keep track of all the immediate branch instructions.
std::vector<ImmBranch> ImmBranches;
HasFarJump - True if any far jump instruction has been emitted during
the branch fix up pass.
bool HasFarJump;
const MipsSubtarget *STI;
const Mips16InstrInfo *TII;
MipsFunctionInfo *MFI;
MachineFunction *MF;
MachineConstantPool *MCP;
unsigned PICLabelUId;
bool <API key>;
void initPICLabelUId(unsigned UId) {
PICLabelUId = UId;
}
unsigned createPICLabelUId() {
return PICLabelUId++;
}
public:
static char ID;
MipsConstantIslands()
: MachineFunctionPass(ID), STI(nullptr), MF(nullptr), MCP(nullptr),
<API key>(false) {}
StringRef getPassName() const override { return "Mips Constant Islands"; }
bool <API key>(MachineFunction &F) override;
<API key> <API key>() const override {
return <API key>().set(
<API key>::Property::NoVRegs);
}
void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
unsigned getCPELogAlign(const MachineInstr &CPEMI);
void <API key>(const std::vector<MachineInstr*> &CPEMIs);
unsigned getOffsetOf(MachineInstr *MI) const;
unsigned getUserOffset(CPUser&) const;
void dumpBBs();
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
unsigned Disp, bool NegativeOK);
bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
const CPUser &U);
void computeBlockSize(MachineBasicBlock *MBB);
MachineBasicBlock *<API key>(MachineInstr &MI);
void <API key>(MachineBasicBlock *NewBB);
void <API key>(MachineBasicBlock *BB);
bool <API key>(unsigned CPI, MachineInstr* CPEMI);
int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
int <API key>(CPUser& U, unsigned UserOffset);
bool findAvailableWater(CPUser&U, unsigned UserOffset,
water_iterator &WaterIter);
void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
MachineBasicBlock *&NewMBB);
bool <API key>(unsigned CPUserIndex);
void removeDeadCPEMI(MachineInstr *CPEMI);
bool <API key>();
bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
MachineInstr *CPEMI, unsigned Disp, bool NegOk,
bool DoDump = false);
bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
CPUser &U, unsigned &Growth);
bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
bool fixupImmediateBr(ImmBranch &Br);
bool fixupConditionalBr(ImmBranch &Br);
bool <API key>(ImmBranch &Br);
void prescanForConstants();
private:
};
char MipsConstantIslands::ID = 0;
} // end of anonymous namespace
bool MipsConstantIslands::isOffsetInRange
(unsigned UserOffset, unsigned TrialOffset,
const CPUser &U) {
return isOffsetInRange(UserOffset, TrialOffset,
U.getMaxDisp(), U.NegOk);
}
print block size and offset information - debugging
void MipsConstantIslands::dumpBBs() {
DEBUG({
for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
const BasicBlockInfo &BBI = BBInfo[J];
dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
<< format(" size=%#x\n", BBInfo[J].Size);
}
});
}
Returns a pass that converts branches to long branches.
FunctionPass *llvm::<API key>() {
return new MipsConstantIslands();
}
bool MipsConstantIslands::<API key>(MachineFunction &mf) {
// The intention is for this to be a mips16 only pass for now
// FIXME:
MF = &mf;
MCP = mf.getConstantPool();
STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
DEBUG(dbgs() << "constant island machine function " << "\n");
if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
return false;
}
TII = (const Mips16InstrInfo *)STI->getInstrInfo();
MFI = MF->getInfo<MipsFunctionInfo>();
DEBUG(dbgs() << "constant island processing " << "\n");
// will need to make predermination if there is any constants we need to
// put in constant islands. TBD.
if (!<API key>) prescanForConstants();
HasFarJump = false;
// This pass invalidates liveness information when it splits basic blocks.
MF->getRegInfo().invalidateLiveness();
// Renumber all of the machine basic blocks in the function, guaranteeing that
// the numbers agree with the position of the block in the function.
MF->RenumberBlocks();
bool MadeChange = false;
// Perform the initial placement of the constant pool entries. To start with,
// we put them all at the end of the function.
std::vector<MachineInstr*> CPEMIs;
if (!MCP->isEmpty())
doInitialPlacement(CPEMIs);
The next UID to take is the first unused one.
initPICLabelUId(CPEMIs.size());
// Do the initial scan of the function, building up information about the
// sizes of each block, the location of all the water, and finding all of the
// constant pool users.
<API key>(CPEMIs);
CPEMIs.clear();
DEBUG(dumpBBs());
Remove dead constant pool entries.
MadeChange |= <API key>();
// Iteratively place constant pool entries and fix up branches until there
// is no change.
unsigned NoCPIters = 0, NoBRIters = 0;
(void)NoBRIters;
while (true) {
DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
bool CPChange = false;
for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
CPChange |= <API key>(i);
if (CPChange && ++NoCPIters > 30)
report_fatal_error("Constant Island pass failed to converge!");
DEBUG(dumpBBs());
// Clear NewWaterList now. If we split a block for branches, it should
// appear as "new water" for the next iteration of constant pool placement.
NewWaterList.clear();
DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
bool BRChange = false;
for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
BRChange |= fixupImmediateBr(ImmBranches[i]);
if (BRChange && ++NoBRIters > 30)
report_fatal_error("Branch Fix Up pass failed to converge!");
DEBUG(dumpBBs());
if (!CPChange && !BRChange)
break;
MadeChange = true;
}
DEBUG(dbgs() << '\n'; dumpBBs());
BBInfo.clear();
WaterList.clear();
CPUsers.clear();
CPEntries.clear();
ImmBranches.clear();
return MadeChange;
}
doInitialPlacement - Perform the initial placement of the constant pool
entries. To start with, we put them all at the end of the function.
void
MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
// Create the basic block to hold the CPE's.
MachineBasicBlock *BB = MF-><API key>();
MF->push_back(BB);
// MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
unsigned MaxAlign = Log2_32(MCP-><API key>());
// Mark the basic block as required by the const-pool.
// If <API key> isn't set, use 4-byte alignment for everything.
BB->setAlignment(<API key> ? MaxAlign : 2);
// The function needs to be as aligned as the basic blocks. The linker may
// move functions around based on their alignment.
MF->ensureAlignment(BB->getAlignment());
// Order the entries in BB by descending alignment. That ensures correct
// alignment of all entries as long as BB is sufficiently aligned. Keep
// track of the insertion point for each alignment. We are going to bucket
// sort the entries as they are created.
SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
// Add all of the constants from the constant pool to the end block, use an
// identity mapping of CPI's to CPE's.
const std::vector<<API key>> &CPs = MCP->getConstants();
const DataLayout &TD = MF->getDataLayout();
for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
assert(Size >= 4 && "Too small constant pool entry");
unsigned Align = CPs[i].getAlignment();
assert(isPowerOf2_32(Align) && "Invalid alignment");
// Verify that all constant pool entries are a multiple of their alignment.
// If not, we would have to pad them out so that instructions stay aligned.
assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
// Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
unsigned LogAlign = Log2_32(Align);
MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
MachineInstr *CPEMI =
BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
.addImm(i).<API key>(i).addImm(Size);
CPEMIs.push_back(CPEMI);
// Ensure that future entries with higher alignment get inserted before
// CPEMI. This is bucket sort with iterators.
for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
if (InsPoint[a] == InsAt)
InsPoint[a] = CPEMI;
// Add a new CPEntry, but no corresponding CPUser yet.
CPEntries.emplace_back(1, CPEntry(CPEMI, i));
++NumCPEs;
DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
<< Size << ", align = " << Align <<'\n');
}
DEBUG(BB->dump());
}
BBHasFallthrough - Return true if the specified basic block can fallthrough
into the block immediately after it.
static bool BBHasFallthrough(MachineBasicBlock *MBB) {
// Get the next machine basic block in the function.
MachineFunction::iterator MBBI = MBB->getIterator();
// Can't fall off end of function.
if (std::next(MBBI) == MBB->getParent()->end())
return false;
MachineBasicBlock *NextBB = &*std::next(MBBI);
for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
E = MBB->succ_end(); I != E; ++I)
if (*I == NextBB)
return true;
return false;
}
findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
look up the corresponding CPEntry.
MipsConstantIslands::CPEntry
*MipsConstantIslands::findConstPoolEntry(unsigned CPI,
const MachineInstr *CPEMI) {
std::vector<CPEntry> &CPEs = CPEntries[CPI];
// Number of entries per constpool index should be small, just do a
// linear search.
for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
if (CPEs[i].CPEMI == CPEMI)
return &CPEs[i];
}
return nullptr;
}
getCPELogAlign - Returns the required alignment of the constant pool entry
represented by CPEMI. Alignment is measured in log2(bytes) units.
unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr &CPEMI) {
assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
// Everything is 4-byte aligned unless <API key> is set.
if (!<API key>)
return 2;
unsigned CPI = CPEMI.getOperand(1).getIndex();
assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
unsigned Align = MCP->getConstants()[CPI].getAlignment();
assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
return Log2_32(Align);
}
<API key> - Do the initial scan of the function, building up
information about the sizes of each block, the location of all the water,
and finding all of the constant pool users.
void MipsConstantIslands::
<API key>(const std::vector<MachineInstr*> &CPEMIs) {
BBInfo.clear();
BBInfo.resize(MF->getNumBlockIDs());
// First thing, compute the size of all basic blocks, and see if the function
// has any inline assembly in it. If so, we have to be conservative about
// alignment assumptions, as we don't know for sure the size of any
// instructions in the inline assembly.
for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
computeBlockSize(&*I);
// Compute block offsets.
<API key>(&MF->front());
// Now go back through the instructions and build up our data structures.
for (MachineBasicBlock &MBB : *MF) {
// If this block doesn't fall through into the next MBB, then this is
// 'water' that a constant pool island could be placed.
if (!BBHasFallthrough(&MBB))
WaterList.push_back(&MBB);
for (MachineInstr &MI : MBB) {
if (MI.isDebugValue())
continue;
int Opc = MI.getOpcode();
if (MI.isBranch()) {
bool isCond = false;
unsigned Bits = 0;
unsigned Scale = 1;
int UOpc = Opc;
switch (Opc) {
default:
continue; // Ignore other branches for now
case Mips::Bimm16:
Bits = 11;
Scale = 2;
isCond = false;
break;
case Mips::BimmX16:
Bits = 16;
Scale = 2;
isCond = false;
break;
case Mips::BeqzRxImm16:
UOpc=Mips::Bimm16;
Bits = 8;
Scale = 2;
isCond = true;
break;
case Mips::BeqzRxImmX16:
UOpc=Mips::Bimm16;
Bits = 16;
Scale = 2;
isCond = true;
break;
case Mips::BnezRxImm16:
UOpc=Mips::Bimm16;
Bits = 8;
Scale = 2;
isCond = true;
break;
case Mips::BnezRxImmX16:
UOpc=Mips::Bimm16;
Bits = 16;
Scale = 2;
isCond = true;
break;
case Mips::Bteqz16:
UOpc=Mips::Bimm16;
Bits = 8;
Scale = 2;
isCond = true;
break;
case Mips::BteqzX16:
UOpc=Mips::Bimm16;
Bits = 16;
Scale = 2;
isCond = true;
break;
case Mips::Btnez16:
UOpc=Mips::Bimm16;
Bits = 8;
Scale = 2;
isCond = true;
break;
case Mips::BtnezX16:
UOpc=Mips::Bimm16;
Bits = 16;
Scale = 2;
isCond = true;
break;
}
// Record this immediate branch.
unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
}
if (Opc == Mips::CONSTPOOL_ENTRY)
continue;
// Scan the instructions for constant pool operands.
for (unsigned op = 0, e = MI.getNumOperands(); op != e; ++op)
if (MI.getOperand(op).isCPI()) {
// We found one. The addressing mode tells us the max displacement
// from the PC that this instruction permits.
// Basic size info comes from the TSFlags field.
unsigned Bits = 0;
unsigned Scale = 1;
bool NegOk = false;
unsigned LongFormBits = 0;
unsigned LongFormScale = 0;
unsigned LongFormOpcode = 0;
switch (Opc) {
default:
llvm_unreachable("Unknown addressing mode for CP reference!");
case Mips::LwRxPcTcp16:
Bits = 8;
Scale = 4;
LongFormOpcode = Mips::LwRxPcTcpX16;
LongFormBits = 14;
LongFormScale = 1;
break;
case Mips::LwRxPcTcpX16:
Bits = 14;
Scale = 1;
NegOk = true;
break;
}
// Remember that this is a user of a CP entry.
unsigned CPI = MI.getOperand(op).getIndex();
MachineInstr *CPEMI = CPEMIs[CPI];
unsigned MaxOffs = ((1 << Bits)-1) * Scale;
unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
LongFormOpcode));
// Increment corresponding CPEntry reference count.
CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
assert(CPE && "Cannot find a corresponding CPEntry!");
CPE->RefCount++;
// Instructions can only use one CP entry, don't bother scanning the
// rest of the operands.
break;
}
}
}
}
computeBlockSize - Compute the size and some alignment information for MBB.
This function updates BBInfo directly.
void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
BBI.Size = 0;
for (const MachineInstr &MI : *MBB)
BBI.Size += TII->getInstSizeInBytes(MI);
}
getOffsetOf - Return the current offset of the specified machine instruction
from the start of the function. This offset changes as stuff is moved
around inside the function.
unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
MachineBasicBlock *MBB = MI->getParent();
// The offset is composed of two things: the sum of the sizes of all MBB's
// before this instruction's block, and the offset from the start of the block
// it is in.
unsigned Offset = BBInfo[MBB->getNumber()].Offset;
// Sum instructions before MI in MBB.
for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Offset += TII->getInstSizeInBytes(*I);
}
return Offset;
}
CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
ID.
static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
const MachineBasicBlock *RHS) {
return LHS->getNumber() < RHS->getNumber();
}
<API key> - When a block is newly inserted into the
machine function, it upsets all of the block numbers. Renumber the blocks
and update the arrays that parallel this numbering.
void MipsConstantIslands::<API key>
(MachineBasicBlock *NewBB) {
// Renumber the MBB's to keep them consecutive.
NewBB->getParent()->RenumberBlocks(NewBB);
// Insert an entry into BBInfo to align it properly with the (newly
// renumbered) block numbers.
BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
// Next, update WaterList. Specifically, we need to add NewMBB as having
// available water after it.
water_iterator IP =
std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
CompareMBBNumbers);
WaterList.insert(IP, NewBB);
}
unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
return getOffsetOf(U.MI);
}
Split the basic block containing MI into two blocks, which are joined by
an unconditional branch. Update data structures and renumber blocks to
account for this change and returns the newly created block.
MachineBasicBlock *
MipsConstantIslands::<API key>(MachineInstr &MI) {
MachineBasicBlock *OrigBB = MI.getParent();
// Create a new MBB for the code after the OrigBB.
MachineBasicBlock *NewBB =
MF-><API key>(OrigBB->getBasicBlock());
MachineFunction::iterator MBBI = ++OrigBB->getIterator();
MF->insert(MBBI, NewBB);
// Splice the instructions starting with MI over to NewBB.
NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
// Add an unconditional branch from OrigBB to NewBB.
// Note the new unconditional branch is not being recorded.
// There doesn't seem to be meaningful DebugInfo available; this doesn't
// correspond to anything in the source.
BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
++NumSplit;
// Update the CFG. All succs of OrigBB are now succs of NewBB.
NewBB->transferSuccessors(OrigBB);
// OrigBB branches to NewBB.
OrigBB->addSuccessor(NewBB);
// Update internal data structures to account for the newly inserted MBB.
// This is almost the same as <API key>, except that
// the Water goes after OrigBB, not NewBB.
MF->RenumberBlocks(NewBB);
// Insert an entry into BBInfo to align it properly with the (newly
// renumbered) block numbers.
BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
// Next, update WaterList. Specifically, we need to add OrigMBB as having
// available water after it (but not if it's already there, which happens
// when splitting before a conditional branch that is followed by an
// unconditional branch - in that case we want to insert NewBB).
water_iterator IP =
std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
CompareMBBNumbers);
MachineBasicBlock* WaterBB = *IP;
if (WaterBB == OrigBB)
WaterList.insert(std::next(IP), NewBB);
else
WaterList.insert(IP, OrigBB);
NewWaterList.insert(OrigBB);
// Figure out how large the OrigBB is. As the first half of the original
// block, it cannot contain a tablejump. The size includes
// the new jump we added. (It should be possible to do this without
// recounting everything, but it's very confusing, and this is rarely
// executed.)
computeBlockSize(OrigBB);
// Figure out how large the NewMBB is. As the second half of the original
// block, it may contain a tablejump.
computeBlockSize(NewBB);
// All BBOffsets following these blocks must be modified.
<API key>(OrigBB);
return NewBB;
}
isOffsetInRange - Checks whether UserOffset (the location of a constant pool
reference) is within MaxDisp of TrialOffset (a proposed location of a
constant pool entry).
bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
unsigned TrialOffset, unsigned MaxDisp,
bool NegativeOK) {
if (UserOffset <= TrialOffset) {
// User before the Trial.
if (TrialOffset - UserOffset <= MaxDisp)
return true;
} else if (NegativeOK) {
if (UserOffset - TrialOffset <= MaxDisp)
return true;
}
return false;
}
isWaterInRange - Returns true if a CPE placed after the specified
Water (a basic block) will be in range for the specific MI.
Compute how much the function will grow by inserting a CPE after Water.
bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
MachineBasicBlock* Water, CPUser &U,
unsigned &Growth) {
unsigned CPELogAlign = getCPELogAlign(*U.CPEMI);
unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
unsigned NextBlockOffset, NextBlockAlignment;
MachineFunction::const_iterator NextBlock = ++Water->getIterator();
if (NextBlock == MF->end()) {
NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
NextBlockAlignment = 0;
} else {
NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
NextBlockAlignment = NextBlock->getAlignment();
}
unsigned Size = U.CPEMI->getOperand(2).getImm();
unsigned CPEEnd = CPEOffset + Size;
// The CPE may be able to hide in the alignment padding before the next
// block. It may also cause more padding to be required if it is more aligned
// that the next block.
if (CPEEnd > NextBlockOffset) {
Growth = CPEEnd - NextBlockOffset;
// Compute the padding that would go at the end of the CPE to align the next
// block.
Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
// If the CPE is to be inserted before the instruction, that will raise
// the offset of the instruction. Also account for unknown alignment padding
// in blocks between CPE and the user.
if (CPEOffset < UserOffset)
UserOffset += Growth;
} else
// CPE fits in existing padding.
Growth = 0;
return isOffsetInRange(UserOffset, CPEOffset, U);
}
isCPEntryInRange - Returns true if the distance between specific MI and
specific ConstPool entry instruction can fit in MI's displacement field.
bool MipsConstantIslands::isCPEntryInRange
(MachineInstr *MI, unsigned UserOffset,
MachineInstr *CPEMI, unsigned MaxDisp,
bool NegOk, bool DoDump) {
unsigned CPEOffset = getOffsetOf(CPEMI);
if (DoDump) {
DEBUG({
unsigned Block = MI->getParent()->getNumber();
const BasicBlockInfo &BBI = BBInfo[Block];
dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
<< " max delta=" << MaxDisp
<< format(" insn address=%#x", UserOffset)
<< " in BB#" << Block << ": "
<< format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
<< format("CPE address=%#x offset=%+d: ", CPEOffset,
int(<API key>));
});
}
return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
}
#ifndef NDEBUG
BBIsJumpedOver - Return true of the specified basic block's only predecessor
unconditionally branches to its only successor.
static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
return false;
MachineBasicBlock *Succ = *MBB->succ_begin();
MachineBasicBlock *Pred = *MBB->pred_begin();
MachineInstr *PredMI = &Pred->back();
if (PredMI->getOpcode() == Mips::Bimm16)
return PredMI->getOperand(0).getMBB() == Succ;
return false;
}
#endif
void MipsConstantIslands::<API key>(MachineBasicBlock *BB) {
unsigned BBNum = BB->getNumber();
for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
// Get the offset and known bits at the end of the layout predecessor.
// Include the alignment of the current block.
unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
BBInfo[i].Offset = Offset;
}
}
<API key> - find the constant pool entry with index CPI
and instruction CPEMI, and decrement its refcount. If the refcount
becomes 0 remove the entry and instruction. Returns true if we removed
the entry, false if we didn't.
bool MipsConstantIslands::<API key>(unsigned CPI,
MachineInstr *CPEMI) {
// Find the old entry. Eliminate it if it is no longer used.
CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
assert(CPE && "Unexpected!");
if (--CPE->RefCount == 0) {
removeDeadCPEMI(CPEMI);
CPE->CPEMI = nullptr;
--NumCPEs;
return true;
}
return false;
}
<API key> - see if the currently referenced CPE is in range;
if not, see if an in-range clone of the CPE is in range, and if so,
change the data structures so the user references the clone. Returns:
0 = no existing entry found
1 = entry found, and there were no code insertions or deletions
2 = entry found, and there were code insertions or deletions
int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
{
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
// Check to see if the CPE is already in-range.
if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
true)) {
DEBUG(dbgs() << "In range\n");
return 1;
}
// No. Look for previously created clones of the CPE that are in range.
unsigned CPI = CPEMI->getOperand(1).getIndex();
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
// We already tried this one
if (CPEs[i].CPEMI == CPEMI)
continue;
// Removing CPEs can leave empty entries, skip
if (CPEs[i].CPEMI == nullptr)
continue;
if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
U.NegOk)) {
DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
<< CPEs[i].CPI << "\n");
// Point the CPUser node to the replacement
U.CPEMI = CPEs[i].CPEMI;
// Change the CPI in the instruction operand to refer to the clone.
for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
if (UserMI->getOperand(j).isCPI()) {
UserMI->getOperand(j).setIndex(CPEs[i].CPI);
break;
}
// Adjust the refcount of the clone...
CPEs[i].RefCount++;
// ...and the original. If we didn't remove the old entry, none of the
// addresses changed, so we don't need another pass.
return <API key>(CPI, CPEMI) ? 2 : 1;
}
}
return 0;
}
<API key> - see if the currently referenced CPE is in range;
This version checks if the longer form of the instruction can be used to
to satisfy things.
if not, see if an in-range clone of the CPE is in range, and if so,
change the data structures so the user references the clone. Returns:
0 = no existing entry found
1 = entry found, and there were no code insertions or deletions
2 = entry found, and there were code insertions or deletions
int MipsConstantIslands::<API key>
(CPUser& U, unsigned UserOffset)
{
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
// Check to see if the CPE is already in-range.
if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
U.getLongFormMaxDisp(), U.NegOk,
true)) {
DEBUG(dbgs() << "In range\n");
UserMI->setDesc(TII->get(U.getLongFormOpcode()));
U.setMaxDisp(U.getLongFormMaxDisp());
return 2; // instruction is longer length now
}
// No. Look for previously created clones of the CPE that are in range.
unsigned CPI = CPEMI->getOperand(1).getIndex();
std::vector<CPEntry> &CPEs = CPEntries[CPI];
for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
// We already tried this one
if (CPEs[i].CPEMI == CPEMI)
continue;
// Removing CPEs can leave empty entries, skip
if (CPEs[i].CPEMI == nullptr)
continue;
if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
U.getLongFormMaxDisp(), U.NegOk)) {
DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
<< CPEs[i].CPI << "\n");
// Point the CPUser node to the replacement
U.CPEMI = CPEs[i].CPEMI;
// Change the CPI in the instruction operand to refer to the clone.
for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
if (UserMI->getOperand(j).isCPI()) {
UserMI->getOperand(j).setIndex(CPEs[i].CPI);
break;
}
// Adjust the refcount of the clone...
CPEs[i].RefCount++;
// ...and the original. If we didn't remove the old entry, none of the
// addresses changed, so we don't need another pass.
return <API key>(CPI, CPEMI) ? 2 : 1;
}
}
return 0;
}
<API key> - Returns the maximum displacement that can fit in
the specific unconditional branch instruction.
static inline unsigned <API key>(int Opc) {
switch (Opc) {
case Mips::Bimm16:
return ((1<<10)-1)*2;
case Mips::BimmX16:
return ((1<<16)-1)*2;
default:
break;
}
return ((1<<16)-1)*2;
}
findAvailableWater - Look for an existing entry in the WaterList in which
we can place the CPE referenced from U so it's within range of U's MI.
Returns true if found, false if not. If it returns true, WaterIter
is set to the WaterList entry.
To ensure that this pass
terminates, the CPE location for a particular CPUser is only allowed to
move to a lower address, so search backward from the end of the list and
prefer the first water that is in range.
bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
water_iterator &WaterIter) {
if (WaterList.empty())
return false;
unsigned BestGrowth = ~0u;
for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
--IP) {
MachineBasicBlock* WaterBB = *IP;
// Check if water is in range and is either at a lower address than the
// current "high water mark" or a new water block that was created since
// the previous iteration by inserting an unconditional branch. In the
// latter case, we want to allow resetting the high water mark back to
// this new water since we haven't seen it before. Inserting branches
// should be relatively uncommon and when it does happen, we want to be
// sure to take advantage of it for all the CPEs near that block, so that
// we don't insert more branches than necessary.
unsigned Growth;
if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
(WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
// This is the least amount of required padding seen so far.
BestGrowth = Growth;
WaterIter = IP;
DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
<< " Growth=" << Growth << '\n');
// Keep looking unless it is perfect.
if (BestGrowth == 0)
return true;
}
if (IP == B)
break;
}
return BestGrowth != ~0u;
}
createNewWater - No existing WaterList entry will work for
CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
block is used if in range, and the conditional branch munged so control
flow is correct. Otherwise the block is split to create a hole with an
unconditional branch around it. In either case NewMBB is set to a
block following which the new island can be inserted (the WaterList
is not adjusted).
void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
unsigned UserOffset,
MachineBasicBlock *&NewMBB) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
unsigned CPELogAlign = getCPELogAlign(*CPEMI);
MachineBasicBlock *UserMBB = UserMI->getParent();
const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
// If the block does not end in an unconditional branch already, and if the
// end of the block is within range, make new water there.
if (BBHasFallthrough(UserMBB)) {
// Size of branch to insert.
unsigned Delta = 2;
// Compute the offset where the CPE will begin.
unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
if (isOffsetInRange(UserOffset, CPEOffset, U)) {
DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
<< format(", expected CPE offset %#x\n", CPEOffset));
NewMBB = &*++UserMBB->getIterator();
// Add an unconditional branch from UserMBB to fallthrough block. Record
// it for branch lengthening; this new branch will not get out of range,
// but if the preceding conditional branch is out of range, the targets
// will be exchanged, and the altered branch may be out of range, so the
// machinery has to know about it.
int UncondBr = Mips::Bimm16;
BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
unsigned MaxDisp = <API key>(UncondBr);
ImmBranches.push_back(ImmBranch(&UserMBB->back(),
MaxDisp, false, UncondBr));
BBInfo[UserMBB->getNumber()].Size += Delta;
<API key>(UserMBB);
return;
}
}
// What a big block. Find a place within the block to split it.
// Try to split the block so it's fully aligned. Compute the latest split
// point where we can add a 4-byte branch instruction, and then align to
// LogAlign which is the largest possible alignment in the function.
unsigned LogAlign = MF->getAlignment();
assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
DEBUG(dbgs() << format("Split in middle of big block before %
BaseInsertOffset));
// The 4 in the following is for the unconditional branch we'll be inserting
// Alignment of the island is handled
// inside isOffsetInRange.
BaseInsertOffset -= 4;
DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
<< " la=" << LogAlign << '\n');
// This could point off the end of the block if we've already got constant
// pool entries following this block; only the last one is in the water list.
// Back past any possible branches (allow for a conditional and a maximally
// long unconditional).
if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
BaseInsertOffset = UserBBI.postOffset() - 8;
DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
}
unsigned EndInsertOffset = BaseInsertOffset + 4 +
CPEMI->getOperand(2).getImm();
MachineBasicBlock::iterator MI = UserMI;
++MI;
unsigned CPUIndex = CPUserIndex+1;
unsigned NumCPUsers = CPUsers.size();
//MachineInstr *LastIT = 0;
for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
Offset < BaseInsertOffset;
Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
assert(MI != UserMBB->end() && "Fell off end of block");
if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
CPUser &U = CPUsers[CPUIndex];
if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
// Shift intertion point by one unit of alignment so it is within reach.
BaseInsertOffset -= 1u << LogAlign;
EndInsertOffset -= 1u << LogAlign;
}
// This is overly conservative, as we don't account for CPEMIs being
// reused within the block, but it doesn't matter much. Also assume CPEs
// are added in order with alignment padding. We may eventually be able
// to pack the aligned CPEs better.
EndInsertOffset += U.CPEMI->getOperand(2).getImm();
CPUIndex++;
}
}
NewMBB = <API key>(*--MI);
}
<API key> - Analyze the specified user, checking to see if it
is out-of-range. If so, pick up the constant pool value and move it some
place in-range. Return true if we changed any addresses (thus must run
another pass of branch lengthening), false otherwise.
bool MipsConstantIslands::<API key>(unsigned CPUserIndex) {
CPUser &U = CPUsers[CPUserIndex];
MachineInstr *UserMI = U.MI;
MachineInstr *CPEMI = U.CPEMI;
unsigned CPI = CPEMI->getOperand(1).getIndex();
unsigned Size = CPEMI->getOperand(2).getImm();
// Compute this only once, it's expensive.
unsigned UserOffset = getUserOffset(U);
// See if the current entry is within range, or there is a clone of it
// in range.
int result = findInRangeCPEntry(U, UserOffset);
if (result==1) return false;
else if (result==2) return true;
// Look for water where we can place this CPE.
MachineBasicBlock *NewIsland = MF-><API key>();
MachineBasicBlock *NewMBB;
water_iterator IP;
if (findAvailableWater(U, UserOffset, IP)) {
DEBUG(dbgs() << "Found water in range\n");
MachineBasicBlock *WaterBB = *IP;
// If the original WaterList entry was "new water" on this iteration,
// propagate that to the new island. This is just keeping NewWaterList
// updated to match the WaterList, which will be updated below.
if (NewWaterList.erase(WaterBB))
NewWaterList.insert(NewIsland);
// The new CPE goes before the following block (NewMBB).
NewMBB = &*++WaterBB->getIterator();
} else {
// No water found.
// we first see if a longer form of the instrucion could have reached
// the constant. in that case we won't bother to split
if (!NoLoadRelaxation) {
result = <API key>(U, UserOffset);
if (result != 0) return true;
}
DEBUG(dbgs() << "No water found\n");
createNewWater(CPUserIndex, UserOffset, NewMBB);
// <API key> adds to WaterList, which is important when it is
// called while handling branches so that the water will be seen on the
// next iteration for constant pools, but in this context, we don't want
// it. Check for this so it will be removed from the WaterList.
// Also remove any entry from NewWaterList.
MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
IP = find(WaterList, WaterBB);
if (IP != WaterList.end())
NewWaterList.erase(WaterBB);
// We are adding new water. Update NewWaterList.
NewWaterList.insert(NewIsland);
}
// Remove the original WaterList entry; we want subsequent insertions in
// this vicinity to go after the one we're about to insert. This
// considerably reduces the number of times we have to move the same CPE
// more than once and is also important to ensure the algorithm terminates.
if (IP != WaterList.end())
WaterList.erase(IP);
// Okay, we know we can put an island before NewMBB now, do it!
MF->insert(NewMBB->getIterator(), NewIsland);
// Update internal data structures to account for the newly inserted MBB.
<API key>(NewIsland);
// Decrement the old entry, and remove it if refcount becomes 0.
<API key>(CPI, CPEMI);
// No existing clone of this CPE is within range.
// We will be generating a new clone. Get a UID for it.
unsigned ID = createPICLabelUId();
// Now that we have an island to add the CPE to, clone the original CPE and
// add it to the island.
U.HighWaterMark = NewIsland;
U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
.addImm(ID).<API key>(CPI).addImm(Size);
CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
++NumCPEs;
// Mark the basic block as aligned as required by the const-pool entry.
NewIsland->setAlignment(getCPELogAlign(*U.CPEMI));
// Increase the size of the island block to account for the new entry.
BBInfo[NewIsland->getNumber()].Size += Size;
<API key>(&*--NewIsland->getIterator());
// Finally, change the CPI in the instruction operand to be ID.
for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
if (UserMI->getOperand(i).isCPI()) {
UserMI->getOperand(i).setIndex(ID);
break;
}
DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
<< format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
return true;
}
removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
sizes and offsets of impacted basic blocks.
void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
MachineBasicBlock *CPEBB = CPEMI->getParent();
unsigned Size = CPEMI->getOperand(2).getImm();
CPEMI->eraseFromParent();
BBInfo[CPEBB->getNumber()].Size -= Size;
// All succeeding offsets have the current size value added in, fix this.
if (CPEBB->empty()) {
BBInfo[CPEBB->getNumber()].Size = 0;
// This block no longer needs to be aligned.
CPEBB->setAlignment(0);
} else
// Entries are sorted by descending alignment, so realign from the front.
CPEBB->setAlignment(getCPELogAlign(*CPEBB->begin()));
<API key>(CPEBB);
// An island has only one predecessor BB and one successor BB. Check if
// this BB's predecessor jumps directly to this BB's successor. This
// shouldn't happen currently.
assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
// FIXME: remove the empty blocks after all the work is done?
}
<API key> - Remove constant pool entries whose refcounts
are zero.
bool MipsConstantIslands::<API key>() {
unsigned MadeChange = false;
for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
std::vector<CPEntry> &CPEs = CPEntries[i];
for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
removeDeadCPEMI(CPEs[j].CPEMI);
CPEs[j].CPEMI = nullptr;
MadeChange = true;
}
}
}
return MadeChange;
}
isBBInRange - Returns true if the distance between specific MI and
specific BB can fit in MI's displacement field.
bool MipsConstantIslands::isBBInRange
(MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
unsigned PCAdj = 4;
unsigned BrOffset = getOffsetOf(MI) + PCAdj;
unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
<< " from BB#" << MI->getParent()->getNumber()
<< " max delta=" << MaxDisp
<< " from " << getOffsetOf(MI) << " to " << DestOffset
<< " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
if (BrOffset <= DestOffset) {
// Branch before the Dest.
if (DestOffset-BrOffset <= MaxDisp)
return true;
} else {
if (BrOffset-DestOffset <= MaxDisp)
return true;
}
return false;
}
fixupImmediateBr - Fix up an immediate branch whose destination is too far
away to fit in its displacement field.
bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
unsigned TargetOperand = branchTargetOperand(MI);
MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
// Check to see if the DestBB is already in-range.
if (isBBInRange(MI, DestBB, Br.MaxDisp))
return false;
if (!Br.isCond)
return <API key>(Br);
return fixupConditionalBr(Br);
}
<API key> - Fix up an unconditional branch whose destination is
too far away to fit in its displacement field. If the LR register has been
spilled in the epilogue, then we can use BL to implement a far jump.
Otherwise, add an intermediate branch instruction to a branch.
bool
MipsConstantIslands::<API key>(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
MachineBasicBlock *MBB = MI->getParent();
MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
// Use BL to implement far jump.
unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
Br.MaxDisp = BimmX16MaxDisp;
MI->setDesc(TII->get(Mips::BimmX16));
}
else {
// need to give the math a more careful look here
// this is really a segment address and not
// a PC relative address. FIXME. But I think that
// just reducing the bits by 1 as I've done is correct.
// The basic block we are branching too much be longword aligned.
// we know that RA is saved because we always save it right now.
// this requirement will be relaxed later but we also have an alternate
// way to implement this that I will implement that does not need jal.
// We should have a way to back out this alignment restriction if we "can" later.
// but it is not harmful.
DestBB->setAlignment(2);
Br.MaxDisp = ((1<<24)-1) * 2;
MI->setDesc(TII->get(Mips::JalB16));
}
BBInfo[MBB->getNumber()].Size += 2;
<API key>(MBB);
HasFarJump = true;
++NumUBrFixed;
DEBUG(dbgs() << " Changed B to long jump " << *MI);
return true;
}
fixupConditionalBr - Fix up a conditional branch whose destination is too
far away to fit in its displacement field. It is converted to an inverse
conditional branch + an unconditional branch to the destination.
bool
MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
MachineInstr *MI = Br.MI;
unsigned TargetOperand = branchTargetOperand(MI);
MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
unsigned Opcode = MI->getOpcode();
unsigned LongFormOpcode = <API key>(Opcode);
unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
// Check to see if the DestBB is already in-range.
if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
Br.MaxDisp = LongFormMaxOff;
MI->setDesc(TII->get(LongFormOpcode));
return true;
}
// Add an unconditional branch to the destination and invert the branch
// condition to jump over it:
// bteqz L1
// bnez L2
// b L1
// If the branch is at the end of its MBB and that has a fall-through block,
// direct the updated conditional branch to the fall-through block. Otherwise,
// split the MBB before the next instruction.
MachineBasicBlock *MBB = MI->getParent();
MachineInstr *BMI = &MBB->back();
bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
unsigned <API key> = TII-><API key>(Opcode);
++NumCBrFixed;
if (BMI != MI) {
if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
BMI-><API key>()) {
// Last MI in the BB is an unconditional branch. Can we simply invert the
// condition and swap destinations:
// beqz L1
// b L2
// bnez L2
// b L1
unsigned BMITargetOperand = branchTargetOperand(BMI);
MachineBasicBlock *NewDest =
BMI->getOperand(BMITargetOperand).getMBB();
if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
<< *BMI);
MI->setDesc(TII->get(<API key>));
BMI->getOperand(BMITargetOperand).setMBB(DestBB);
MI->getOperand(TargetOperand).setMBB(NewDest);
return true;
}
}
}
if (NeedSplit) {
<API key>(*MI);
// No need for the branch to the next block. We're adding an unconditional
// branch to the destination.
int delta = TII->getInstSizeInBytes(MBB->back());
BBInfo[MBB->getNumber()].Size -= delta;
MBB->back().eraseFromParent();
// BBInfo[SplitBB].Offset is wrong temporarily, fixed below
}
MachineBasicBlock *NextBB = &*++MBB->getIterator();
DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
<< " also invert condition and change dest. to BB
<< NextBB->getNumber() << "\n");
// Insert a new conditional branch and a new unconditional branch.
// Also update the ImmBranch as well as adding a new entry for the new branch.
if (MI-><API key>() == 2) {
BuildMI(MBB, DebugLoc(), TII->get(<API key>))
.addReg(MI->getOperand(0).getReg())
.addMBB(NextBB);
} else {
BuildMI(MBB, DebugLoc(), TII->get(<API key>))
.addMBB(NextBB);
}
Br.MI = &MBB->back();
BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
unsigned MaxDisp = <API key>(Br.UncondBr);
ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
// Remove the old conditional branch. It may or may not still be in MBB.
BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
MI->eraseFromParent();
<API key>(MBB);
return true;
}
void MipsConstantIslands::prescanForConstants() {
unsigned J = 0;
(void)J;
for (MachineFunction::iterator B =
MF->begin(), E = MF->end(); B != E; ++B) {
for (MachineBasicBlock::instr_iterator I =
B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
switch(I->getDesc().getOpcode()) {
case Mips::LwConstant32: {
<API key> = true;
DEBUG(dbgs() << "constant island constant " << *I << "\n");
J = I->getNumOperands();
DEBUG(dbgs() << "num operands " << J << "\n");
MachineOperand& Literal = I->getOperand(1);
if (Literal.isImm()) {
int64_t V = Literal.getImm();
DEBUG(dbgs() << "literal " << V << "\n");
Type *Int32Ty =
Type::getInt32Ty(MF->getFunction()->getContext());
const Constant *C = ConstantInt::get(Int32Ty, V);
unsigned index = MCP-><API key>(C, 4);
I->getOperand(2).ChangeToImmediate(index);
DEBUG(dbgs() << "constant island constant " << *I << "\n");
I->setDesc(TII->get(Mips::LwRxPcTcp16));
I->RemoveOperand(1);
I->RemoveOperand(1);
I->addOperand(MachineOperand::CreateCPI(index, 0));
I->addOperand(MachineOperand::CreateImm(4));
}
break;
}
default:
break;
}
}
}
} |
'use strict';
// Methods
export var GET = 'GET';
export var POST = 'POST';
export var PUT = 'PUT';
export var DELETE = 'DELETE';
// Header
export namespace Header {
export var CONTENT_TYPE = 'Content-Type';
export var CONTENT_LENGTH = 'Content-Length';
export var LAST_MODIFIED = 'Last-Modified';
export var LOCATION = 'Location';
export var ETAG = 'ETag';
export var X_CONTENT_CHARSET = 'X-Content-Charset';
export var X_CONTENT_TYPES = 'X-Content-Types';
export var X_CONTENT_HASH = 'X-Content-Hash';
export var X_FILEPATH = 'X-Filepath';
export var X_RESOURCE = 'X-Resource';
}
// Mime
export namespace Mime {
export var RAW = 'application/octet-stream';
export var JSON = 'application/json';
export var TEXT = 'text/plain';
export var HTML = 'text/html';
}
// Charset
export namespace Charset {
export var UTF8 = 'utf-8';
export var UTF8_BOM = 'UTF8_BOM';
}
export interface IDataChunk {
header(name:string):string;
value():string;
}
export interface IXHROptions {
type?:string;
url?:string;
user?:string;
password?:string;
responseType?:string;
headers?:any;
timeout?: number;
followRedirects?: number;
data?:any;
}
export interface IXHRResponse {
responseText: string;
status: number;
readyState : number;
getResponseHeader: (header:string) => string;
}
export function isRedirect(status: number) : boolean {
return status >= 300 && status <= 303 || status === 307;
}
var <API key> = /X-Chunk-Length:(\d+)\r\n\r\n/gi,
headerPattern = /(.+?):(.+?)\r\n(\r\n)?/gm;
function newDataChunk(responseText:string, headerStartOffset:number, headerEndOffset:number, contentLength:number):IDataChunk {
var _value:string,
_headers:{[name:string]:string};
return {
header: function(name:string):string {
if(typeof _headers === 'undefined') {
_headers = Object.create(null);
headerPattern.lastIndex = headerStartOffset;
while(true) {
var match = headerPattern.exec(responseText);
if(!match) {
// no header found
break;
}
_headers[match[1].toLowerCase()] = match[2];
if(match[3]) {
// the last header found
break;
}
}
}
return _headers[name.toLowerCase()];
},
value: function() {
if(typeof _value === 'undefined') {
_value = responseText.substr(headerEndOffset + 2 /*crlf*/, contentLength);
}
return _value;
}
};
}
/**
* Parses the response text of the provided request into individual data chunks. The chunks
* are filled into the provided array.
*/
export function parseChunkedData(request:IXHRResponse, collection:IDataChunk[], offset:number = 0):number {
var responseText = request.responseText;
<API key>.lastIndex = offset;
while(true) {
var match = <API key>.exec(responseText);
if(!match) {
return offset;
}
var contentLength = parseInt(match[1], 10);
if(responseText.length < <API key>.lastIndex + contentLength) {
return offset;
}
collection.push(newDataChunk(responseText, offset, <API key>.lastIndex - 2, contentLength));
offset = <API key>.lastIndex + contentLength;
}
} |
/*jshint esnext:true*/
/*exported DNSPacket*/
'use strict';
module.exports = window.DNSPacket = (function() {
var DNSRecord = require('./dns-record');
var DNSResourceRecord = require('./dns-resource-record');
var DNSUtils = require('./dns-utils');
var ByteArray = require('./byte-array');
const <API key> = [
'QD', // Question
'AN', // Answer
'NS', // Authority
'AR' // Additional
];
function DNSPacket(byteArray) {
this.flags = DNSUtils.valueToFlags(0x0000);
this.records = {};
DNSPacket.<API key>.forEach((recordSectionType) => {
this.records[recordSectionType] = [];
});
if (!byteArray) {
return this;
}
var reader = byteArray.getReader();
if (reader.getValue(2) !== 0x0000) {
throw new Error('Packet must start with 0x0000');
}
this.flags = DNSUtils.valueToFlags(reader.getValue(2));
var recordCounts = {};
// Parse the record counts.
DNSPacket.<API key>.forEach((recordSectionType) => {
recordCounts[recordSectionType] = reader.getValue(2);
});
// Parse the actual records.
DNSPacket.<API key>.forEach((recordSectionType) => {
iterate(recordCounts[recordSectionType], () => {
var record;
if (recordSectionType === 'QD') {
record = DNSRecord.<API key>(reader);
this.addRecord(recordSectionType, record);
}
else {
record = DNSResourceRecord.<API key>(reader);
this.addRecord(recordSectionType, record);
}
});
});
if (!reader.eof) {
console.warn('Did not complete parsing packet data');
}
}
DNSPacket.<API key> = <API key>;
DNSPacket.prototype.constructor = DNSPacket;
DNSPacket.prototype.addRecord = function(recordSectionType, record) {
record.packet = this;
this.records[recordSectionType].push(record);
};
DNSPacket.prototype.getRecords = function(recordSectionType) {
return this.records[recordSectionType];
};
DNSPacket.prototype.serialize = function() {
var byteArray = new ByteArray();
// Write leading 0x0000 (2 bytes)
byteArray.push(0x0000, 2);
// Write `flags` (2 bytes)
byteArray.push(DNSUtils.flagsToValue(this.flags), 2);
// Write lengths of record sections (2 bytes each)
DNSPacket.<API key>.forEach((recordSectionType) => {
byteArray.push(this.records[recordSectionType].length, 2);
});
// Write records
DNSPacket.<API key>.forEach((recordSectionType) => {
this.records[recordSectionType].forEach((record) => {
byteArray.append(record.serialize());
});
});
return byteArray.buffer;
};
function iterate(count, iterator) {
for (var i = 0; i < count; i++) {
iterator(i);
}
}
return DNSPacket;
})(); |
#include "stdneb.h"
#include "particles/particlesystem.h"
#include "particles/particletarget.h"
#include "particles/particle.h"
#include "particles/particleserver.h"
#include "app/basegamefeature/managers/timemanager.h"
#include "particles/particlepool.h"
#include "particles/emitters/<API key>.h"
#include "particles/emitters/particleBoxEmitter.h"
#include "particles/emitters/particleConeEmitter.h"
#include "particles/emitters/<API key>.h"
#include "particles/targets/<API key>.h"
#include "particles/targets/<API key>.h"
namespace Particles
{
__ImplementClass(Particles::ParticleSystem,'PARS', Core::RefCounted)
const GPtr<ParticleSystem> ParticleSystem::NullParSystem(NULL);
const Timing::Time ParticleSystem::DefaultFrameTime(1.0/30);
const Timing::Time ParticleSystem::MinFrameTime(0.000001);
ParticleSystem::ParticleSystem()
: mIsActive(false)
, mIsPreLoop(false)
, mPlayBackTime(0.0)
, mTransparency(255)
, mCurFrameTime(0.0)
, mFrameIndex(0)
, <API key>(-1)
, mName("ParticleSystem")
, mPlayOnAwake(true)
, mIsPlaying(true)
, mIsStop(false)
, mbStepOne(false)
, mPreDelay(0.0f)
, mPlayRateScale(1.0f)
, mUseExternBB(false)
, mLiveTime(0.0)
, mQuota( ConstDefine::<API key> )
, mPoolNeedIncrease(true)
, mIsMoveWorldCoord(false)
, mIsLoadEmitterMesh(false)
, mspf(DefaultFrameTime)
, mfps(30)
, mCurrentTimeForFps(0.0f)
, mLoop(true)
, mDuration(10.0)
, mDelayTime(0.0)
, mNeedUpdate(true)
, mUpdateUnVis(false)
, mUpdateTarget(false)
{
#ifdef __GENESIS_EDITOR__ // edtior use
mCubeEmitter = NULL;
mConeEmitter = NULL;
mSphereEmitter = NULL;
mModelEmitter = NULL;
mBillBoardTarget = NULL;
mRibbonTarget = NULL;
#endif
}
ParticleSystem::~ParticleSystem()
{
}
void
ParticleSystem::Active(void)
{
ParticleServer::Instance()-><API key>( GPtr<ParticleSystem>(this) );
mNeedUpdate = true;
}
void
ParticleSystem::DeActive(void)
{
ParticleServer::Instance()-><API key>( GPtr<ParticleSystem>(this) );
}
void
ParticleSystem::_onActive()
{
n_assert( !mIsActive );
n_assert( !mPool.isvalid() );
mPool = ParticlePool::Create();
_preparePool();
if(mEmitter)
{
mEmitter->_onActivate();
}
for ( IndexT index = 0; index < mAffectors.Size(); ++index )
{
mAffectors[index]->_onActivate();
}
if ( mTarget )
{
mTarget->_onActivate();
}
mIsActive = true;
}
void
ParticleSystem::_onDeactive()
{
n_assert( mIsActive );
if(mEmitter)
{
mEmitter->_onDeactivate();
}
for ( IndexT index = 0; index < mAffectors.Size(); ++index )
{
mAffectors[index]->_onDeactivate();
}
if ( mTarget )
{
mTarget->_onDeactivate();
}
mPool = NULL;
mPoolNeedIncrease = true;
mIsActive = false;
}
void
ParticleSystem::Addtime(Timing::Time t, IndexT frameIndex)
{
if (!mIsPlaying)
{
t = 0;
}
if (mbStepOne)
{
t = DefaultFrameTime;
mbStepOne = false;
}
else
{
t *= mPlayRateScale;
}
ParticleEmitterPtr emit = mEmitter;
if ( emit.isvalid() )
{
if ( !mLoop && mLiveTime < mDuration && (mLiveTime + t) > mDuration && (mDuration - mLiveTime) > 0.002f )
{
t = mDuration - mLiveTime - 1e-9;
}
}
mCurFrameTime = t;
mFrameIndex = frameIndex;
}
void
ParticleSystem::Update(void)
{
if (!mNeedUpdate && !mUpdateUnVis)
{
mUpdateTarget = false;
return;
}
mNeedUpdate = false;
mUpdateTarget = true;
Timing::Time time = App::GameTime::Instance()->GetFrameTime();
mCurrentTimeForFps += time;
if(mCurrentTimeForFps < mspf)
{
return;
}
Timing::Time total = 0.0f;
while(mCurrentTimeForFps >= mspf)
{
total += mspf;
mCurrentTimeForFps -= mspf;
}
Addtime( total,App::TimeManager::Instance()->GetFrameIndex() );
if( mIsPlaying && mIsPreLoop && mLiveTime <= MinFrameTime)
{
if(mPlayBackTime > 0.0f)
{
SetPlayTime(mPlayBackTime);
}
else
{
float playtime = 2.0f;
_repeatUpdate(playtime);
mPreDelay = playtime;
}
}
if ( <API key> != mFrameIndex )
{
_techUpdate(mCurFrameTime, mFrameIndex);
<API key> = mFrameIndex;
}
if(mIsPlaying && !mLoop && (GetCurEmitTime() + 0.00001 > mDuration)
&& mPool->IsEmpty())
{
Stop();
}
}
bool ParticleSystem::IsDirtyPrim(IndexT nIdx) const
{
if(mTarget.isvalid())
return mTarget->IsDirtyPrim();
return false;
}
void ParticleSystem::SetDirtyPrim(IndexT nIdx, bool bset)
{
if(mTarget.isvalid())
mTarget->SetDirtyPrim(bset);
}
void ParticleSystem::_InitTime()
{
// mLiveTime = 0.f;
mCurFrameTime = 0.f;
mFrameIndex = 0;
<API key> = 0;
}
void ParticleSystem::_repeatUpdate(float time)
{
float LiveNextFrameTime = (float)DefaultFrameTime;
do
{
_techUpdate(DefaultFrameTime, mFrameIndex);
LiveNextFrameTime += (float)DefaultFrameTime;
} while ( LiveNextFrameTime <= time);
_techUpdate( time - LiveNextFrameTime + DefaultFrameTime, mFrameIndex);
}
void ParticleSystem::_techUpdate(Timing::Time frameTime,IndexT frameIndex )
{
mCurFrameTime = frameTime;
mLiveTime += mCurFrameTime;
mFrameIndex = frameIndex;
_preparePool();
_emitParticles();
<API key>();
_processParticles();
}
void ParticleSystem::Stop()
{
mIsPlaying = false;
mIsStop = true;
Reset();
}
void ParticleSystem::SetPlayTime(Timing::Time timePoint)
{
_InitTime();
if (mIsActive)
{
Reset();
_repeatUpdate((float)timePoint);
}
}
Math::float3
ParticleSystem::GetDerivedPosition(void)
{
Math::float3 sysPos(mWorldMatrix.get_position().x(),
mWorldMatrix.get_position().y(),
mWorldMatrix.get_position().z());
return sysPos;
}
Math::float3 ParticleSystem::GetDerivedScale(void)
{
Math::float3 sysScale(mWorldMatrix.getrow0().x(),
mWorldMatrix.getrow1().y(),
mWorldMatrix.getrow2().z());
return sysScale;
}
Math::quaternion ParticleSystem::GetDerivedRotation(void)
{
Math::quaternion quat = Math::matrix44::rotationmatrix(mWorldMatrix);
return quat;
}
void
ParticleSystem::SetParticleQuota(SizeT quota)
{
if ( quota <= 0 )
{
n_warning(" ParticleTechnique::SetParticleQuota, should bigger than 0");
quota = 1;
}
if ( quota > ConstDefine::MAX_TECHNIQUE_QUOTA )
{
n_warning(" ParticleTechnique::SetParticleQuota, should smaller than %d", ConstDefine::MAX_TECHNIQUE_QUOTA );
quota = ConstDefine::MAX_TECHNIQUE_QUOTA;
}
mQuota = quota;
mPoolNeedIncrease = true;
}
void ParticleSystem::Reset()
{
mLiveTime = 0;
mFrameIndex = 0;
mCurFrameTime = 0;
<API key> = -1;
_resetPool(mQuota);
}
void
ParticleSystem::_emitParticles(void)
{
if(mLiveTime < mDelayTime || !mEmitter )
return;
if(!mLoop && (mDuration + mDelayTime) < mLiveTime)
return ;
SizeT requested = mEmitter-><API key>(mCurFrameTime);
<API key>( mEmitter, requested );
}
void
ParticleSystem::<API key>(ParticleEmitterPtr& emitter, SizeT requested)
{
n_assert( mPool.isvalid() );
n_assert( emitter.isvalid() );
if ( requested == 0 )
{
return;
}
for ( IndexT index = 0; index < requested; ++index )
{
Particle* particle = mPool->ReleaseParticle();
if ( !particle )
{
return;
}
emitter->_emit( particle );
<API key>(particle);
}
}
void ParticleSystem::<API key>(void)
{
for ( IndexT index = 0; index < mAffectors.Size(); ++index)
{
mAffectors[index]-><API key>();
}
}
void ParticleSystem::_processParticles(void)
{
if ( mPool->IsEmpty())
return;
Particle* particle = mPool->GetFirst();
ParticleEmitter* emitter = 0;
bool firstParticle = true;
bool firstActiveParticle = true;
while ( !mPool->End() )
{
if (particle)
{
if ( !_isExpired(particle, mCurFrameTime) )
{
_processAffectors(particle, firstActiveParticle);
firstActiveParticle = false;
}
else
{
//add by zhangjitao
particle->mOrbitPositions.Reset();
mPool->LockLatestParticle();
}
// Decrement time to live
particle->mTimeToLive -= (Math::scalar)mCurFrameTime;
particle->mTimeFraction = (particle->mTotalTimeToLive - particle->mTimeToLive)/particle->mTotalTimeToLive;
}
firstParticle = false;
particle = mPool->GetNext();
}
}
void ParticleSystem::<API key>(Particle* particle)
{
if ( !mAffectors.IsEmpty() )
{
for ( IndexT index = 0; index < mAffectors.Size(); ++index)
{
mAffectors[index]-><API key>(particle);
}
}
}
void ParticleSystem::_processAffectors(Particle* particle, bool firstActiveParticle)
{
if ( !mAffectors.IsEmpty() )
{
for ( IndexT index = 0; index < mAffectors.Size(); ++index)
{
mAffectors[index]->_processParticle(particle, firstActiveParticle);
}
}
}
void ParticleSystem::<API key>(void)
{
if (!mUpdateTarget || mPoolNeedIncrease)
{
return;
}
for ( IndexT index = 0; index < mAffectors.Size(); ++index)
{
mAffectors[index]-><API key>();
}
if ( mTarget.isvalid() && mPool.isvalid())
{
mTarget->_updateTarget( mPool, mCurFrameTime );
}
}
void ParticleSystem::<API key>(bool isWorld)
{
if(mIsMoveWorldCoord == isWorld || NULL == mPool)
return;
Particle* particle = mPool->GetFirst();
Math::matrix44 techMat = mWorldMatrix;
if(!isWorld)
techMat = Math::matrix44::inverse(techMat);
while ( particle )
{
particle->mPosition = particle->mPosition.transformPoint(techMat);
particle = mPool->GetNext();
}
}
const ParticleEmitterPtr&
ParticleSystem::GetEmitter() const
{
return mEmitter;
}
const ParticleAffectorPtr&
ParticleSystem::GetAffector(IndexT index) const
{
if ( index >=0 && index < mAffectors.Size() )
{
return mAffectors[index];
}
else
{
return ParticleAffector::NullAffector;
}
}
void
ParticleSystem::AddAffector( const ParticleAffectorPtr& affector, IndexT index)
{
if ( !affector.isvalid() )
{
return;
}
if ( affector->GetParentSystem() != NULL )
{
return;
}
if (index >= 0)
mAffectors.Insert( index, affector );
else
mAffectors.Append( affector );
affector->SetParentSystem( this );
if ( IsActive() )
{
affector->_onActivate();
}
}
void
ParticleSystem::RemoveAffector( IndexT index )
{
if ( index >= 0 && index < mAffectors.Size() )
{
ParticleAffectorPtr& affector = mAffectors[index];
n_assert(affector.isvalid());
if ( affector->IsActive() )
{
affector->_onDeactivate();
}
affector->SetParentSystem(NULL);
mAffectors.EraseIndex( index );
}
}
void
ParticleSystem::RemoveAllAffector(void)
{
for ( IndexT index = 0; index < mAffectors.Size(); ++index)
{
ParticleAffectorPtr& affector = mAffectors[index];
n_assert(affector.isvalid());
if ( affector->IsActive() )
{
affector->_onDeactivate();
}
affector->SetParentSystem(NULL);
}
mAffectors.Clear();
}
void
ParticleSystem::SetTarget( const ParticleTargetPtr& target)
{
if(mTarget.isvalid())
RemoveTarget();
if ( target.isvalid() )
{
if ( target->GetParentSystem() != NULL )
{
return;
}
}
if ( mTarget.isvalid() )
{
if ( mTarget->IsActive() )
{
mTarget->_onDeactivate();
}
mTarget->SetParentSystem(NULL);
mTarget = NULL;
}
n_assert( !mTarget.isvalid() );
mTarget = target;
if ( mTarget.isvalid() )
{
mTarget->SetParentSystem(this);
if ( IsActive() )
{
mTarget->_onActivate();
}
}
#ifdef __GENESIS_EDITOR__ // edtior use
uint emtfourcc = mTarget->GetClassFourCC().AsUInt();
switch(emtfourcc)
{
case CPFCC::TARGET_BILLBOARD:
if(mBillBoardTarget.isvalid())
{
GPtr<<API key>> billboardTarget = mTarget.downcast<<API key>>();
billboardTarget-><API key>(mBillBoardTarget-><API key>());
billboardTarget->SetBillBoardType(mBillBoardTarget->GetBillBoardType());
billboardTarget->SetStretchScale(mBillBoardTarget->GetStretchScale());
billboardTarget->SetOrientType(mBillBoardTarget->GetOrientType());
}
break;
case CPFCC::TARGET_RIBBONTRAIL:
if(mRibbonTarget.isvalid())
{
GPtr<RibbonTrailTarget> ribbonTarget = mTarget.downcast<RibbonTrailTarget>();
ribbonTarget->SetTrailLength(mRibbonTarget->GetTrailLength());
ribbonTarget->SetMaxElements(mRibbonTarget->GetMaxElements());
}
break;
}
#endif
}
void ParticleSystem::RemoveTarget()
{
if( !mTarget.isvalid())
return;
#ifdef __GENESIS_EDITOR__ // edtior use
uint emtfourcc = mTarget->GetClassFourCC().AsUInt();
switch(emtfourcc)
{
case CPFCC::TARGET_BILLBOARD:
mBillBoardTarget = mTarget.downcast<<API key>>();
break;
case CPFCC::TARGET_RIBBONTRAIL:
mRibbonTarget = mTarget.downcast<RibbonTrailTarget>();
break;
}
#endif
if ( mTarget->IsActive() )
{
mTarget->_onDeactivate();
}
mTarget->SetParentSystem(NULL);
mTarget = NULL;
}
void
ParticleSystem::RemoveEmitter()
{
if ( mEmitter )
{
#ifdef __GENESIS_EDITOR__ // edtior use
uint emtfourcc = mEmitter->GetClassFourCC().AsUInt();
switch(emtfourcc)
{
case CPFCC::EMITTER_BOX:
mCubeEmitter = mEmitter.downcast<BoxEmitter>();
break;
case CPFCC::<API key>:
mSphereEmitter = mEmitter.downcast<<API key>>();
break;
case CPFCC::EMITTER_CONE:
mConeEmitter = mEmitter.downcast<ConeEmitter>();
break;
case CPFCC::EMITTER_MODEL:
mModelEmitter = mEmitter.downcast<ModelEmitter>();
break;
}
#endif
n_assert(mEmitter.isvalid());
if ( mEmitter->IsActive() )
{
mEmitter->_onDeactivate();
}
mEmitter->SetParentSystem(NULL);
mEmitter = NULL;
}
}
void
ParticleSystem::SetEmitter( const ParticleEmitterPtr& emitter)
{
if ( !emitter.isvalid() )
{
return;
}
if ( emitter->GetParentSystem() != NULL )
{
return;
}
mEmitter = emitter;
emitter->SetParentSystem( this );
if ( IsActive() )
{
emitter->_onActivate();
}
#ifdef __GENESIS_EDITOR__ // edtior use
uint emtfourcc = emitter->GetClassFourCC().AsUInt();
switch(emtfourcc)
{
case CPFCC::EMITTER_BOX:
if(mCubeEmitter.isvalid())
{
mEmitter->SetNormalDir(mCubeEmitter->IsNormalDir());
mEmitter->SetNormalSpeed(mCubeEmitter->GetNormalSpeed());
mEmitter-><API key>(mCubeEmitter-><API key>());
emitter->getMinMaxCurve(Emitter_BoxSizeX)->CopyFrom(*mCubeEmitter->getMinMaxCurve(Emitter_BoxSizeX));
emitter->getMinMaxCurve(Emitter_BoxSizeY)->CopyFrom(*mCubeEmitter->getMinMaxCurve(Emitter_BoxSizeY));
emitter->getMinMaxCurve(Emitter_BoxSizeZ)->CopyFrom(*mCubeEmitter->getMinMaxCurve(Emitter_BoxSizeZ));
}
break;
case CPFCC::<API key>:
if(mSphereEmitter.isvalid())
{
mEmitter->SetNormalDir(mSphereEmitter->IsNormalDir());
mEmitter->SetNormalSpeed(mSphereEmitter->GetNormalSpeed());
mEmitter-><API key>(mSphereEmitter-><API key>());
emitter->getMinMaxCurve(<API key>)->CopyFrom(*mSphereEmitter->getMinMaxCurve(<API key>));
emitter->getMinMaxCurve(Emitter_SphereHem)->CopyFrom(*mSphereEmitter->getMinMaxCurve(Emitter_SphereHem));
emitter->getMinMaxCurve(Emitter_SphereSlice)->CopyFrom(*mSphereEmitter->getMinMaxCurve(Emitter_SphereSlice));
}
break;
case CPFCC::EMITTER_CONE:
if(mConeEmitter.isvalid())
{
mEmitter->SetNormalDir(mConeEmitter->IsNormalDir());
mEmitter->SetNormalSpeed(mConeEmitter->GetNormalSpeed());
mEmitter-><API key>(mConeEmitter-><API key>());
emitter->getMinMaxCurve(<API key>)->CopyFrom(*mConeEmitter->getMinMaxCurve(<API key>));
emitter->getMinMaxCurve(<API key>)->CopyFrom(*mConeEmitter->getMinMaxCurve(<API key>));
emitter->getMinMaxCurve(Emitter_ConeHeight)->CopyFrom(*mConeEmitter->getMinMaxCurve(Emitter_ConeHeight));
emitter->getMinMaxCurve(Emitter_ConeAngle)->CopyFrom(*mConeEmitter->getMinMaxCurve(Emitter_ConeAngle));
}
break;
case CPFCC::EMITTER_MODEL:
if(mModelEmitter.isvalid())
{
mEmitter->SetNormalDir(mModelEmitter->IsNormalDir());
mEmitter->SetNormalSpeed(mModelEmitter->GetNormalSpeed());
mEmitter-><API key>(mModelEmitter-><API key>());
GPtr<ModelEmitter> modelEmitter = mEmitter.downcast<ModelEmitter>();
modelEmitter->SetMeshName(mModelEmitter->GetMeshName());
}
break;
}
#endif
}
void ParticleSystem::_preparePool(void)
{
if ( mPoolNeedIncrease )
{
n_assert( mPool.isvalid() );
mPool-><API key>();
mPool-><API key>( mQuota );
mPoolNeedIncrease = false;
}
}
void ParticleSystem::_resetPool(int nQuota)
{
mPool-><API key>();
SetParticleQuota(nQuota);
}
Timing::Time ParticleSystem::GetCurEmitTime()
{
double curEmitTime = 0;
Timing::Time delayTime = mDelayTime;
bool isLoop = mLoop;
if (mDuration > 0)
{
double tmp = mLiveTime - delayTime;
if (tmp <= 0)
{
curEmitTime = 0;
}
else
{
if (tmp <= mDuration)
{
curEmitTime = tmp;
}
else
{
if (isLoop)
{
int tmpInt = (int)(tmp / mDuration);
curEmitTime = tmp - tmpInt * mDuration;
}
else
{
curEmitTime = mDuration;
}
}
}
}
else
{
curEmitTime = 0;
}
return curEmitTime;
}
Timing::Time ParticleSystem::GetCorrectTime(void) const
{
Timing::Time delayTime = mDelayTime;
if (mIsPreLoop)
{
delayTime = 0.0f;
}
return delayTime;
}
} |
* {
box-sizing: border-box;
}
#fuzzSearch {
width: 50%;
}
#fuzzNameContainer {
height: 40px;
padding: 4px 10px;
border: 1px solid #999;
box-shadow: inset 0 0 2px 0px #333;
width: 100%;
cursor: pointer;
line-height: 1.9em;
}
.fuzzName {
display: inline-block;
width: 96%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.fuzzArrow {
width: 0;
border-style: solid;
border-color: #333 transparent transparent transparent;
border-width: 7px;
display: inline-block;
cursor: pointer;
position: relative;
top: -3px;
-webkit-transition: all 0.1s ease-in;
transition: all 0.1s ease-in;
}
.fuzzArrow:hover {
border-top-color: #888;
}
.fuzzArrow.fuzzArrowUp {
border-color: transparent transparent #333 transparent;
top: -11px;
}
#<API key> {
display: none;
width: 100%;
margin: 0 0 5px 0;
border: 1px solid #999;
padding: 12px 4px 4px;
position: relative;
}
.fuzzMagicBox {
width: 99%;
height: 26px;
margin: 0 auto;
}
.fuzzSearchIcon {
width: 20px;
height: 14px;
position: relative;
display: inline-block;
background: transparent;
top: -20px;
left: 95%;
}
.fuzzSearchIcon:before, .fuzzSearchIcon:after {
content: '';
display: block;
position: absolute;
right: 5px;
}
.fuzzSearchIcon:before {
width: 8px;
height: 8px;
border-radius: 50%;
border: 1px solid #aaa;
}
.fuzzSearchIcon:after {
height: 7px;
border-right: 1px solid #aaa;
top: 9px;
-webkit-transform: rotate(-32deg);
-ms-transform: rotate(-32deg);
}
#fuzzResults {
cursor: pointer;
padding: 0;
margin: 0;
}
#fuzzResults li {
list-style: none;
margin-bottom: 10px;
padding: 10px;
transition: all 0.1s ease-out;
}
#fuzzResults li:hover, #fuzzResults li.selected {
color: #fff;
background: #1251a4;
} |
<!-- Main content -->
<section class='content'>
<div class='row'>
<div class='col-xs-12'>
<div class='box'>
<div class='box-header'>
<h3 class='box-title'>JURUSAN LIST <?php echo anchor('jurusan/create/','Create',array('class'=>'btn btn-danger btn-sm'));?>
<?php echo anchor(site_url('jurusan/excel'), ' <i class="fa fa-file-excel-o"></i> Excel', 'class="btn btn-primary btn-sm"'); ?>
<?php echo anchor(site_url('jurusan/word'), '<i class="fa fa-file-word-o"></i> Word', 'class="btn btn-primary btn-sm"'); ?>
<?php echo anchor(site_url('jurusan/pdf'), '<i class="fa fa-file-pdf-o"></i> PDF', 'class="btn btn-primary btn-sm"'); ?></h3>
</div><!-- /.box-header -->
<div class='box-body'>
<table class="table table-bordered table-striped" id="mytable">
<thead>
<tr>
<th width="80px">No</th>
<th>Jurusan</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$start = 0;
foreach ($jurusan_data as $jurusan)
{
?>
<tr>
<td><?php echo ++$start ?></td>
<td><?php echo $jurusan->jurusan ?></td>
<td style="text-align:center" width="140px">
<?php
echo anchor(site_url('jurusan/read/'.$jurusan->id_jurusan),'<i class="fa fa-eye"></i>',array('title'=>'detail','class'=>'btn btn-danger btn-sm'));
echo ' ';
echo anchor(site_url('jurusan/update/'.$jurusan->id_jurusan),'<i class="fa fa-pencil-square-o"></i>',array('title'=>'edit','class'=>'btn btn-danger btn-sm'));
echo ' ';
echo anchor(site_url('jurusan/delete/'.$jurusan->id_jurusan),'<i class="fa fa-trash-o"></i>','title="delete" class="btn btn-danger btn-sm" onclick="javasciprt: return confirm(\'Are You Sure ?\')"');
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<script src="<?php echo base_url('assets/js/jquery-1.11.2.min.js') ?>"></script>
<script src="<?php echo base_url('assets/datatables/jquery.dataTables.js') ?>"></script>
<script src="<?php echo base_url('assets/datatables/dataTables.bootstrap.js') ?>"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#mytable").dataTable();
});
</script>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section><!-- /.content --> |
# Chrono
[![Latest Version on Packagist][ico-version]][link-version]
[![Software License][ico-license]][link-license]
[![Build Status][ico-build]][link-build]
[![Coverage Status][ico-coverage]][link-coverage]
[![SensioLabsInsight][ico-security]][link-security]
[![StyleCI][ico-code-style]][link-code-style]
Version Control System wrapper for PHP.
## Installation using Composer
Run the following command to add the package to your composer.json:
bash
$ composer require accompli/chrono
## Usage
The `Repository` class will detect which registered VCS adapter to use based on the URL of the repository.
php
<?php
use Accompli\Chrono\Process\ProcessExecutor;
use Accompli\Chrono\Repository;
$repository = new Repository('https://github.com/accompli/chrono.git', '/vcs/checkout/directory', new ProcessExecutor());
$repository->getBranches(); // Returns an array with all available branches in the repository.
$repository->getTags(); // Returns an array with all available tags in the repository.
$repository->checkout('0.1.0'); // Creates or updates a checkout of a tag or branch in the repository directory.
# Versioning
Chrono uses [Semantic Versioning 2][link-semver] for new versions.
## Credits and acknowledgements
- [Niels Nijens][link-author]
- [All Contributors][link-contributors]
- Inspired by the VCS drivers of Composer.
Chrono is licensed under the MIT License. Please see the [LICENSE file][link-license] for details.
[ico-version]: https://img.shields.io/packagist/v/accompli/chrono.svg
[ico-license]: https://img.shields.io/badge/<API key>.svg
[ico-build]: https://travis-ci.org/accompli/chrono.svg?branch=master
[ico-coverage]: https://coveralls.io/repos/accompli/chrono/badge.svg?branch=master
[ico-security]: https://img.shields.io/sensiolabs/i/<API key>.svg
[ico-code-style]: https://styleci.io/repos/45839394/shield?style=flat
[link-version]: https://packagist.org/packages/accompli/chrono
[link-license]: LICENSE.md
[link-build]: https://travis-ci.org/accompli/chrono
[link-coverage]: https://coveralls.io/r/accompli/chrono?branch=master
[link-security]: https://insight.sensiolabs.com/projects/<API key>
[link-code-style]: https://styleci.io/repos/45839394
[link-semver]: http://semver.org/
[link-author]: https://github.com/niels-nijens
[link-contributors]: https://github.com/accompli/chrono/contributors |
namespace StayWell.ServiceDefinitions.ServiceLines.Objects
{
public class KeywordResponse
{
public string Keyword { get; set; }
public string KeywordSlug { get; set; }
}
} |
#ifndef GROESTL_H__
#define GROESTL_H__
#include <stddef.h>
/**
* This structure is a context for Groestl-384 and Groestl-512 computations:
* it contains the intermediate values and some data from the last
* entered block. Once a Groestl computation has been performed, the
* context can be reused for another computation.
*
* The contents of this structure are private. A running Groestl
* computation can be cloned by copying the context (e.g. with a simple
* <code>memcpy()</code>).
*/
typedef struct {
unsigned char buf[128]; /* first field, for alignment */
size_t ptr;
union {
uint64_t wide[16];
uint32_t narrow[32];
} state;
uint64_t count;
} <API key>;
typedef <API key> GROESTL512_CTX;
/**
* Initialize a Groestl-512 context. This process performs no memory allocation.
*
* @param cc the Groestl-512 context (pointer to a
* <code>GROESTL512_CTX</code>)
*/
void groestl512_Init(void *cc);
/**
* Process some data bytes. It is acceptable that <code>len</code> is zero
* (in which case this function does nothing).
*
* @param cc the Groestl-512 context
* @param data the input data
* @param len the input data length (in bytes)
*/
void groestl512_Update(void *cc, const void *data, size_t len);
/**
* Terminate the current Groestl-512 computation and output the result into
* the provided buffer. The destination buffer must be wide enough to
* accomodate the result (64 bytes). The context is automatically
* reinitialized.
*
* @param cc the Groestl-512 context
* @param dst the destination buffer
*/
void groestl512_Final(void *cc, void *dst);
/* Calculate double Groestl-512 hash and truncate it to 256-bits. */
void <API key>(void *cc, void *dst);
#endif |
<!
Before opening an issue, verify:
- Is this a feature request? Post it on https://feathub.com/Flexget/Flexget
- Is this an issue with webui? Make an issue over on https://github.com/Flexget/webui
- Did you recently upgrade? Look at the Change Log and Upgrade Actions to make sure that you don't need to make any changes to your config https:
- Are you running FlexGet as a daemon? Stop it completely and then start it again https://flexget.com/CLI/daemon
- Did you search to see if the issue already exists? https://github.com/Flexget/Flexget/issues
- Did you fill out the issue template as completely as possible?
The issue template is here because it helps to ensure you submitted all the necessary information the first time, and allows us to more quickly review issues. Please fill it out correctly and do not ignore it, no matter how irrelevant you think it may be. Thanks in advance for your help with this!
>
Expected behaviour:
<!
Please don't just say "it doesn't crash" or "it works". Explain what the expected result is.
>
Actual behaviour:
Steps to reproduce:
- Step 1: ...
# Config:
yaml
Paste FULL config and remove any personal info if config is too long, attach the file to the ticket.
If issue is with a single task, you can get get resulting configuration by running:
flexget execute --task <NAME> --dump-config
Make sure to redact any personal information (passwords, api keys, etc) !
# Log:
<details>
<summary>(click to expand)</summary>
paste log output here
</details>
Additional information:
- FlexGet version:
- Python version:
- Installation method:
- Using daemon (yes/no):
- OS and version:
- Link to crash log:
<!
In config and debug/crash logs, remember to redact any personal or sensitive information such as passwords, API keys, private URLs and so on.
Please verify that the following data is present before submitting your issue:
- Link to a paste service or paste above the relevant config (preferably full config, including templates if present). Please make sure the paste does not expire, if possible.
- Link to a paste service or paste above debug-level logs of the relevant task/s (use `flexget -L debug execute --tasks <Task_name>`).
- FlexGet version (use `flexget -V` to get it).
- Full Python version, for example `2.7.11` (use `python -V` to get it).
- Installation method (pip, git install, etc).
- Whether or not you're running FlexGet as a daemon.
- OS and version.
- Attach crash log if one was generated, in addition to the debug-level log. It can be found in the directory with your config file.
> |
<?php
namespace Component\Processor\Processors;
use Component\Processor\Processors\AbstractProcessor;
use Component\Processor\StatusManager;
use Component\Storage\FileInfo;
use Component\Preparer\Types\MediaTypes;
use FFMpeg\FFMpeg;
use FFMpeg\Format\Audio\Mp3;
use FFMpeg\Format\Audio\Vorbis;
/**
* Processor for standard video types
*/
class AudioProcessor extends AbstractProcessor
{
// PROPERTIES //
/**
* Timeout for a ffmpeg job
* @var int
*/
private $timeout;
/**
* Number of threads to allow ffmpeg to use
* @var int
*/
private $threads;
/**
* Location of the FFMpeg Binary
* @var string
*/
private $ffmpegBinary;
/**
* Location of the FFProbe Binary
* @var string
*/
private $ffprobeBinary;
// CONSTRUCTOR //
public function __construct(
$timeout = 60000,
$threads = 8,
$ffmpegBinary = '/usr/bin/ffmpeg',
$ffprobeBinary = '/usr/bin/ffprobe'
) {
// Set
$this->timeout = $timeout;
$this->threads = $threads;
$this->ffmpegBinary = $ffmpegBinary;
$this->ffprobeBinary = $ffprobeBinary;
}
// IMPLEMENTED METHODS //
/**
* Get an array of supported mime types by this processor
* @return array List of supported mime types
*/
public function getSupportedTypes()
{
return array(
'audio/mp4',
'audio/mpeg',
'audio/mpeg3',
'audio/x-mpeg-3',
'audio/x-mpeg',
'application/ogg',
'audio/ogg',
'audio/flac',
'audio/vorbis',
'audio/vnd.rn-realaudio',
'audio/vnd.wave',
'audio/webm'
);
}
/**
* Get the media type that this processor handles
* @return string Media type
*/
public function getMediaType()
{
return MediaTypes::AUDIO;
}
/**
* Get array of export data
* @return array Export info
*/
private function getExports()
{
return array(
'low' => array('bitrate' => 64),
'high' => array('bitrate' => 192)
);
}
/**
* Process the media file
* @param FileInfo $file Original File
* @return boolean Operation success
*/
public function process(FileInfo $file)
{
// Init the FFmpeg library
$ffmpeg = FFMpeg::create(array(
'ffmpeg.binaries' => $this->ffmpegBinary,
'ffprobe.binaries' => $this->ffprobeBinary,
'timeout' => $this->timeout,
'ffmpeg.threads' => $this->threads
));
// Prep the storage for streaming
$originalPath = $file->getBasePath()
. $file->getMediaFile()->getFilename();
// Create a new status manager
$statusManager = new StatusManager(
$file->getMediaId(),
$this->storage,
count($this->getExports()) * 2
);
// Create the different sizes
foreach ($this->getExports() as $name => $size)
{
// Create an anonymous function for progress callback
$progressFunc = function($audio, $format, $percentage) use ($statusManager)
{
$statusManager-><API key>($percentage);
};
// Create the formats
$mp3 = new Mp3();
$mp3->setAudioChannels(2);
$mp3->setAudioKiloBitrate($size['bitrate']);
$mp3->on('progress', $progressFunc);
$vorbis = new Vorbis();
$vorbis->setAudioChannels(2);
$vorbis->setAudioKiloBitrate($size['bitrate']);
$vorbis->on('progress', $progressFunc);
// Resize and encode the video
$audio = $ffmpeg->open($originalPath);
$statusManager->startNewPhase();
$audio->save($mp3, $file->getBasePath() . $name . '.mp3');
$statusManager->endPhase();
$statusManager->startNewPhase();
$audio->save($vorbis, $file->getBasePath() . $name . '.oga');
$statusManager->endPhase();
$this->storage->addFile($file->getMediaId(),
$file->getBasePath() . $name . '.mp3',
$name . '.mp3', 'audio/mpeg',
null, null, $size['bitrate']);
$this->storage->addFile($file->getMediaId(),
$file->getBasePath() . $name . '.oga',
$name . '.oga', 'audio/vorbis',
null, null, $size['bitrate']);
}
// Mark the video as ready
$this->storage->markAsReady($file->getMediaId());
// Complete
return true;
}
} |
package com.iluwatar.promise;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A really simplified implementation of future that allows completing it successfully with a value
* or exceptionally with an exception.
*/
class PromiseSupport<T> implements Future<T> {
private static final int RUNNING = 1;
private static final int FAILED = 2;
private static final int COMPLETED = 3;
private final Object lock;
private volatile int state = RUNNING;
private T value;
private Exception exception;
PromiseSupport() {
this.lock = new Object();
}
void fulfill(T value) {
this.value = value;
this.state = COMPLETED;
synchronized (lock) {
lock.notifyAll();
}
}
void <API key>(Exception exception) {
this.exception = exception;
this.state = FAILED;
synchronized (lock) {
lock.notifyAll();
}
}
@Override
public boolean cancel(boolean <API key>) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return state > RUNNING;
}
@Override
public T get() throws <API key>, ExecutionException {
if (state == COMPLETED) {
return value;
} else if (state == FAILED) {
throw new ExecutionException(exception);
} else {
synchronized (lock) {
lock.wait();
if (state == COMPLETED) {
return value;
} else {
throw new ExecutionException(exception);
}
}
}
}
@Override
public T get(long timeout, TimeUnit unit)
throws <API key>, ExecutionException, TimeoutException {
if (state == COMPLETED) {
return value;
} else if (state == FAILED) {
throw new ExecutionException(exception);
} else {
synchronized (lock) {
lock.wait(unit.toMillis(timeout));
if (state == COMPLETED) {
return value;
} else if (state == FAILED) {
throw new ExecutionException(exception);
} else {
throw new TimeoutException();
}
}
}
}
} |
/*
* CFrustum is a collection of planes which define a viewing space.
*/
/*
Usually associated with the camera, there are 6 planes which define the
view pyramid. But we allow more planes per frustum which may be used for
portal rendering, where a portal may have 3 or more edges.
*/
#ifndef INCLUDED_FRUSTUM
#define INCLUDED_FRUSTUM
#include "maths/Plane.h"
//10 planes should be enough
#define <API key> (10)
class CBoundingBoxAligned;
class CMatrix3D;
class CFrustum
{
public:
CFrustum ();
~CFrustum ();
//Set the number of planes to use for
//calculations. This is clipped to
//[0,<API key>]
void SetNumPlanes (size_t num);
size_t GetNumPlanes() const { return m_NumPlanes; }
void AddPlane (const CPlane& plane);
void Transform(CMatrix3D& m);
//The following methods return true if the shape is
//partially or completely in front of the frustum planes
bool IsPointVisible(const CVector3D& point) const;
bool <API key>(const CVector3D& start, const CVector3D& end) const;
bool IsSphereVisible(const CVector3D& center, float radius) const;
bool IsBoxVisible(const CVector3D& position, const CBoundingBoxAligned& bounds) const;
bool IsBoxVisible(const CBoundingBoxAligned& bounds) const;
CPlane& operator[](size_t idx) { return m_aPlanes[idx]; }
const CPlane& operator[](size_t idx) const { return m_aPlanes[idx]; }
public:
//make the planes public for ease of use
CPlane m_aPlanes[<API key>];
private:
size_t m_NumPlanes;
};
#endif |
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/runtime.h"
#include "py/mphal.h"
#include "py/mperrno.h"
#include "netutils.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"
#include "esp_log.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "lwip/dns.h"
#include "tcpip_adapter.h"
#include "modnetwork.h"
#define <API key> (1)
NORETURN void _esp_exceptions(esp_err_t e) {
switch (e) {
case <API key>:
mp_raise_msg(&mp_type_OSError, "Wifi Not Initialized");
case <API key>:
mp_raise_msg(&mp_type_OSError, "Wifi Not Started");
case ESP_ERR_WIFI_CONN:
mp_raise_msg(&mp_type_OSError, "Wifi Internal Error");
case ESP_ERR_WIFI_SSID:
mp_raise_msg(&mp_type_OSError, "Wifi SSID Invalid");
case ESP_ERR_WIFI_FAIL:
mp_raise_msg(&mp_type_OSError, "Wifi Internal Failure");
case ESP_ERR_WIFI_IF:
mp_raise_msg(&mp_type_OSError, "Wifi Invalid Interface");
case ESP_ERR_WIFI_MAC:
mp_raise_msg(&mp_type_OSError, "Wifi Invalid MAC Address");
case ESP_ERR_WIFI_ARG:
mp_raise_msg(&mp_type_OSError, "Wifi Invalid Argument");
case ESP_ERR_WIFI_MODE:
mp_raise_msg(&mp_type_OSError, "Wifi Invalid Mode");
case <API key>:
mp_raise_msg(&mp_type_OSError, "Wifi Invalid Password");
case ESP_ERR_WIFI_NVS:
mp_raise_msg(&mp_type_OSError, "Wifi Internal NVS Error");
case <API key>:
mp_raise_msg(&mp_type_OSError, "TCP/IP Invalid Parameters");
case <API key>:
mp_raise_msg(&mp_type_OSError, "TCP/IP IF Not Ready");
case <API key>:
mp_raise_msg(&mp_type_OSError, "TCP/IP DHCP Client Start Failed");
case <API key>:
mp_raise_OSError(MP_ETIMEDOUT);
case <API key>:
case ESP_ERR_WIFI_NO_MEM:
mp_raise_OSError(MP_ENOMEM);
default:
nlr_raise(<API key>(
&<API key>, "Wifi Unknown Error 0x%04x", e
));
}
}
static inline void esp_exceptions(esp_err_t e) {
if (e != ESP_OK) _esp_exceptions(e);
}
#define ESP_EXCEPTIONS(x) do { esp_exceptions(x); } while (0);
typedef struct _wlan_if_obj_t {
mp_obj_base_t base;
int if_id;
} wlan_if_obj_t;
const mp_obj_type_t wlan_if_type;
STATIC const wlan_if_obj_t wlan_sta_obj = {{&wlan_if_type}, WIFI_IF_STA};
STATIC const wlan_if_obj_t wlan_ap_obj = {{&wlan_if_type}, WIFI_IF_AP};
//static wifi_config_t wifi_ap_config = {{{0}}};
static wifi_config_t wifi_sta_config = {{{0}}};
// Set to "true" if the STA interface is requested to be connected by the
// user, used for automatic reassociation.
static bool wifi_sta_connected = false;
// This function is called by the system-event task and so runs in a different
// thread to the main MicroPython task. It must not raise any Python exceptions.
static esp_err_t event_handler(void *ctx, system_event_t *event) {
switch(event->event_id) {
case <API key>:
ESP_LOGI("wifi", "STA_START");
break;
case <API key>:
ESP_LOGI("network", "GOT_IP");
break;
case <API key>: {
// This is a workaround as ESP32 WiFi libs don't currently
// auto-reassociate.
<API key> *disconn = &event->event_info.disconnected;
ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d", disconn->reason);
switch (disconn->reason) {
case <API key>:
mp_printf(MP_PYTHON_PRINTER, "beacon timeout\n");
// AP has dropped out; try to reconnect.
break;
case <API key>:
mp_printf(MP_PYTHON_PRINTER, "no AP found\n");
// AP may not exist, or it may have momentarily dropped out; try to reconnect.
break;
case <API key>:
mp_printf(MP_PYTHON_PRINTER, "authentication failed\n");
wifi_sta_connected = false;
break;
default:
// Let other errors through and try to reconnect.
break;
}
if (wifi_sta_connected) {
wifi_mode_t mode;
if (esp_wifi_get_mode(&mode) == ESP_OK) {
if (mode & WIFI_MODE_STA) {
// STA is active so attempt to reconnect.
esp_err_t e = esp_wifi_connect();
if (e != ESP_OK) {
mp_printf(MP_PYTHON_PRINTER, "error attempting to reconnect: 0x%04x", e);
}
}
}
}
break;
}
default:
ESP_LOGI("network", "event %d", event->event_id);
break;
}
return ESP_OK;
}
/*void error_check(bool status, const char *msg) {
if (!status) {
nlr_raise(<API key>(&mp_type_OSError, msg));
}
}
*/
STATIC void require_if(mp_obj_t wlan_if, int if_no) {
wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if);
if (self->if_id != if_no) {
mp_raise_msg(&mp_type_OSError, if_no == WIFI_IF_STA ? "STA required" : "AP required");
}
}
STATIC mp_obj_t get_wlan(size_t n_args, const mp_obj_t *args) {
static int initialized = 0;
if (!initialized) {
wifi_init_config_t cfg = <API key>();
ESP_LOGD("modnetwork", "Initializing WiFi");
ESP_EXCEPTIONS( esp_wifi_init(&cfg) );
ESP_EXCEPTIONS( <API key>(WIFI_STORAGE_RAM) );
ESP_LOGD("modnetwork", "Initialized");
ESP_EXCEPTIONS( esp_wifi_set_mode(0) );
ESP_EXCEPTIONS( esp_wifi_start() );
ESP_LOGD("modnetwork", "Started");
initialized = 1;
}
int idx = (n_args > 0) ? mp_obj_get_int(args[0]) : WIFI_IF_STA;
if (idx == WIFI_IF_STA) {
return MP_OBJ_FROM_PTR(&wlan_sta_obj);
} else if (idx == WIFI_IF_AP) {
return MP_OBJ_FROM_PTR(&wlan_ap_obj);
} else {
mp_raise_ValueError("invalid WLAN interface identifier");
}
}
STATIC <API key>(get_wlan_obj, 0, 1, get_wlan);
STATIC mp_obj_t esp_initialize() {
static int initialized = 0;
if (!initialized) {
ESP_LOGD("modnetwork", "Initializing TCP/IP");
tcpip_adapter_init();
ESP_LOGD("modnetwork", "Initializing Event Loop");
ESP_EXCEPTIONS( esp_event_loop_init(event_handler, NULL) );
ESP_LOGD("modnetwork", "esp_event_loop_init done");
initialized = 1;
}
return mp_const_none;
}
STATIC <API key>(esp_initialize_obj, esp_initialize);
#if (WIFI_MODE_STA & WIFI_MODE_AP != WIFI_MODE_NULL || WIFI_MODE_STA | WIFI_MODE_AP != WIFI_MODE_APSTA)
#error WIFI_MODE_STA and WIFI_MODE_AP are supposed to be bitfields!
#endif
STATIC mp_obj_t esp_active(size_t n_args, const mp_obj_t *args) {
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
wifi_mode_t mode;
ESP_EXCEPTIONS( esp_wifi_get_mode(&mode) );
int bit = (self->if_id == WIFI_IF_STA) ? WIFI_MODE_STA : WIFI_MODE_AP;
if (n_args > 1) {
bool active = mp_obj_is_true(args[1]);
mode = active ? (mode | bit) : (mode & ~bit);
ESP_EXCEPTIONS( esp_wifi_set_mode(mode) );
}
return (mode & bit) ? mp_const_true : mp_const_false;
}
STATIC <API key>(esp_active_obj, 1, 2, esp_active);
STATIC mp_obj_t esp_connect(size_t n_args, const mp_obj_t *args) {
mp_uint_t len;
const char *p;
if (n_args > 1) {
memset(&wifi_sta_config, 0, sizeof(wifi_sta_config));
p = mp_obj_str_get_data(args[1], &len);
memcpy(wifi_sta_config.sta.ssid, p, MIN(len, sizeof(wifi_sta_config.sta.ssid)));
p = (n_args > 2) ? mp_obj_str_get_data(args[2], &len) : "";
memcpy(wifi_sta_config.sta.password, p, MIN(len, sizeof(wifi_sta_config.sta.password)));
ESP_EXCEPTIONS( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config) );
}
MP_THREAD_GIL_EXIT();
ESP_EXCEPTIONS( esp_wifi_connect() );
MP_THREAD_GIL_ENTER();
wifi_sta_connected = true;
return mp_const_none;
}
STATIC <API key>(esp_connect_obj, 1, 7, esp_connect);
STATIC mp_obj_t esp_disconnect(mp_obj_t self_in) {
wifi_sta_connected = false;
ESP_EXCEPTIONS( esp_wifi_disconnect() );
return mp_const_none;
}
STATIC <API key>(esp_disconnect_obj, esp_disconnect);
STATIC mp_obj_t esp_status(mp_obj_t self_in) {
return mp_const_none;
}
STATIC <API key>(esp_status_obj, esp_status);
STATIC mp_obj_t esp_scan(mp_obj_t self_in) {
// check that STA mode is active
wifi_mode_t mode;
ESP_EXCEPTIONS(esp_wifi_get_mode(&mode));
if ((mode & WIFI_MODE_STA) == 0) {
nlr_raise(<API key>(&mp_type_OSError, "STA must be active"));
}
mp_obj_t list = mp_obj_new_list(0, NULL);
wifi_scan_config_t config = { 0 };
// XXX how do we scan hidden APs (and if we can scan them, are they really hidden?)
MP_THREAD_GIL_EXIT();
esp_err_t status = esp_wifi_scan_start(&config, 1);
MP_THREAD_GIL_ENTER();
if (status == 0) {
uint16_t count = 0;
ESP_EXCEPTIONS( <API key>(&count) );
wifi_ap_record_t *wifi_ap_records = calloc(count, sizeof(wifi_ap_record_t));
ESP_EXCEPTIONS( <API key>(&count, wifi_ap_records) );
for (uint16_t i = 0; i < count; i++) {
mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL);
uint8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid));
int ssid_len = x ? x - wifi_ap_records[i].ssid : sizeof(wifi_ap_records[i].ssid);
t->items[0] = mp_obj_new_bytes(wifi_ap_records[i].ssid, ssid_len);
t->items[1] = mp_obj_new_bytes(wifi_ap_records[i].bssid, sizeof(wifi_ap_records[i].bssid));
t->items[2] = <API key>(wifi_ap_records[i].primary);
t->items[3] = <API key>(wifi_ap_records[i].rssi);
t->items[4] = <API key>(wifi_ap_records[i].authmode);
t->items[5] = mp_const_false; // XXX hidden?
mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
}
free(wifi_ap_records);
}
return list;
}
STATIC <API key>(esp_scan_obj, esp_scan);
STATIC mp_obj_t esp_isconnected(mp_obj_t self_in) {
wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->if_id == WIFI_IF_STA) {
<API key> info;
<API key>(WIFI_IF_STA, &info);
return mp_obj_new_bool(info.ip.addr != 0);
} else {
wifi_sta_list_t sta;
<API key>(&sta);
return mp_obj_new_bool(sta.num != 0);
}
}
STATIC <API key>(esp_isconnected_obj, esp_isconnected);
STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) {
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
<API key> info;
<API key> dns_info;
<API key>(self->if_id, &info);
<API key>(self->if_id, <API key>, &dns_info);
if (n_args == 1) {
// get
mp_obj_t tuple[4] = {
<API key>((uint8_t*)&info.ip, NETUTILS_BIG),
<API key>((uint8_t*)&info.netmask, NETUTILS_BIG),
<API key>((uint8_t*)&info.gw, NETUTILS_BIG),
<API key>((uint8_t*)&dns_info.ip, NETUTILS_BIG),
};
return mp_obj_new_tuple(4, tuple);
} else {
// set
mp_obj_t *items;
<API key>(args[1], 4, &items);
<API key>(items[0], (void*)&info.ip, NETUTILS_BIG);
if (mp_obj_is_integer(items[1])) {
// allow numeric netmask, i.e.:
// 24 -> 255.255.255.0
// 16 -> 255.255.0.0
// etc...
uint32_t* m = (uint32_t*)&info.netmask;
*m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1])));
} else {
<API key>(items[1], (void*)&info.netmask, NETUTILS_BIG);
}
<API key>(items[2], (void*)&info.gw, NETUTILS_BIG);
<API key>(items[3], (void*)&dns_info.ip, NETUTILS_BIG);
// To set a static IP we have to disable DHCP first
if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) {
esp_err_t e = <API key>(self->if_id);
if (e != ESP_OK && e != <API key>) _esp_exceptions(e);
ESP_EXCEPTIONS(<API key>(self->if_id, &info));
ESP_EXCEPTIONS(<API key>(self->if_id, <API key>, &dns_info));
} else if (self->if_id == WIFI_IF_AP) {
esp_err_t e = <API key>(WIFI_IF_AP);
if (e != ESP_OK && e != <API key>) _esp_exceptions(e);
ESP_EXCEPTIONS(<API key>(WIFI_IF_AP, &info));
ESP_EXCEPTIONS(<API key>(WIFI_IF_AP, <API key>, &dns_info));
ESP_EXCEPTIONS(<API key>(WIFI_IF_AP));
}
return mp_const_none;
}
}
<API key>(esp_ifconfig_obj, 1, 2, esp_ifconfig);
STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
if (n_args != 1 && kwargs->used != 0) {
mp_raise_TypeError("either pos or kw args are allowed");
}
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
// get the config for the interface
wifi_config_t cfg;
ESP_EXCEPTIONS(esp_wifi_get_config(self->if_id, &cfg));
if (kwargs->used != 0) {
for (size_t i = 0; i < kwargs->alloc; i++) {
if (<API key>(kwargs, i)) {
int req_if = -1;
#define QS(x) (uintptr_t)MP_OBJ_NEW_QSTR(x)
switch ((uintptr_t)kwargs->table[i].key) {
case QS(MP_QSTR_mac): {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(kwargs->table[i].value, &bufinfo, MP_BUFFER_READ);
if (bufinfo.len != 6) {
mp_raise_ValueError("invalid buffer length");
}
ESP_EXCEPTIONS(esp_wifi_set_mac(self->if_id, bufinfo.buf));
break;
}
case QS(MP_QSTR_essid): {
req_if = WIFI_IF_AP;
mp_uint_t len;
const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
len = MIN(len, sizeof(cfg.ap.ssid));
memcpy(cfg.ap.ssid, s, len);
cfg.ap.ssid_len = len;
break;
}
case QS(MP_QSTR_hidden): {
req_if = WIFI_IF_AP;
cfg.ap.ssid_hidden = mp_obj_is_true(kwargs->table[i].value);
break;
}
case QS(MP_QSTR_authmode): {
req_if = WIFI_IF_AP;
cfg.ap.authmode = mp_obj_get_int(kwargs->table[i].value);
break;
}
case QS(MP_QSTR_password): {
req_if = WIFI_IF_AP;
mp_uint_t len;
const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len);
len = MIN(len, sizeof(cfg.ap.password) - 1);
memcpy(cfg.ap.password, s, len);
cfg.ap.password[len] = 0;
break;
}
case QS(MP_QSTR_channel): {
req_if = WIFI_IF_AP;
cfg.ap.channel = mp_obj_get_int(kwargs->table[i].value);
break;
}
default:
goto unknown;
}
#undef QS
// We post-check interface requirements to save on code size
if (req_if >= 0) {
require_if(args[0], req_if);
}
}
}
ESP_EXCEPTIONS(esp_wifi_set_config(self->if_id, &cfg));
return mp_const_none;
}
// Get config
if (n_args != 2) {
mp_raise_TypeError("can query only one param");
}
int req_if = -1;
mp_obj_t val;
#define QS(x) (uintptr_t)MP_OBJ_NEW_QSTR(x)
switch ((uintptr_t)args[1]) {
case QS(MP_QSTR_mac): {
uint8_t mac[6];
ESP_EXCEPTIONS(esp_wifi_get_mac(self->if_id, mac));
return mp_obj_new_bytes(mac, sizeof(mac));
}
case QS(MP_QSTR_essid):
req_if = WIFI_IF_AP;
val = mp_obj_new_str((char*)cfg.ap.ssid, cfg.ap.ssid_len);
break;
case QS(MP_QSTR_hidden):
req_if = WIFI_IF_AP;
val = mp_obj_new_bool(cfg.ap.ssid_hidden);
break;
case QS(MP_QSTR_authmode):
req_if = WIFI_IF_AP;
val = <API key>(cfg.ap.authmode);
break;
case QS(MP_QSTR_channel):
req_if = WIFI_IF_AP;
val = <API key>(cfg.ap.channel);
break;
default:
goto unknown;
}
#undef QS
// We post-check interface requirements to save on code size
if (req_if >= 0) {
require_if(args[0], req_if);
}
return val;
unknown:
mp_raise_ValueError("unknown config param");
}
STATIC <API key>(esp_config_obj, 1, esp_config);
STATIC const mp_map_elem_t <API key>[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_active), (mp_obj_t)&esp_active_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), (mp_obj_t)&esp_connect_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_disconnect), (mp_obj_t)&esp_disconnect_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_status), (mp_obj_t)&esp_status_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&esp_scan_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_isconnected), (mp_obj_t)&esp_isconnected_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_config), (mp_obj_t)&esp_config_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ifconfig), (mp_obj_t)&esp_ifconfig_obj },
};
STATIC <API key>(wlan_if_locals_dict, <API key>);
const mp_obj_type_t wlan_if_type = {
{ &mp_type_type },
.name = MP_QSTR_WLAN,
.locals_dict = (mp_obj_t)&wlan_if_locals_dict,
};
STATIC mp_obj_t esp_phy_mode(size_t n_args, const mp_obj_t *args) {
return mp_const_none;
}
STATIC <API key>(esp_phy_mode_obj, 0, 1, esp_phy_mode);
STATIC const mp_map_elem_t <API key>[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_network) },
{ MP_OBJ_NEW_QSTR(MP_QSTR___init__), (mp_obj_t)&esp_initialize_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_WLAN), (mp_obj_t)&get_wlan_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_LAN), (mp_obj_t)&get_lan_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_phy_mode), (mp_obj_t)&esp_phy_mode_obj },
#if <API key>
{ MP_OBJ_NEW_QSTR(MP_QSTR_STA_IF),
<API key>(WIFI_IF_STA)},
{ MP_OBJ_NEW_QSTR(MP_QSTR_AP_IF),
<API key>(WIFI_IF_AP)},
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11B),
<API key>(WIFI_PROTOCOL_11B) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11G),
<API key>(WIFI_PROTOCOL_11G) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11N),
<API key>(WIFI_PROTOCOL_11N) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_OPEN),
<API key>(WIFI_AUTH_OPEN) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_WEP),
<API key>(WIFI_AUTH_WEP) },
{ MP_OBJ_NEW_QSTR(<API key>),
<API key>(WIFI_AUTH_WPA_PSK) },
{ MP_OBJ_NEW_QSTR(<API key>),
<API key>(WIFI_AUTH_WPA2_PSK) },
{ MP_OBJ_NEW_QSTR(<API key>),
<API key>(<API key>) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_MAX),
<API key>(WIFI_AUTH_MAX) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_PHY_LAN8720),
<API key>(PHY_LAN8720) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_PHY_TLK110),
<API key>(PHY_TLK110) },
#endif
};
STATIC <API key>(<API key>, <API key>);
const mp_obj_module_t mp_module_network = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&<API key>,
}; |
from tg import request, abort, override_template
from tg.decorators import before_validate, before_render
@before_validate
def ajax_only(*args, **kwargs):
if not request.is_xhr:
abort(400)
def ajax_expose(template):
@before_render
def _ajax_expose(*args, **kwargs):
if request.is_xhr:
override_template(request.controller_state.method, template)
return _ajax_expose |
<?php
namespace Magento\Vault\Test\Unit\Model;
use Magento\Framework\<API key>;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Magento\Vault\Api\Data\<API key>;
use Magento\Vault\Model\<API key>;
use Magento\Vault\Model\PaymentToken;
use <API key> as MockObject;
/**
* Class <API key>
*/
class <API key> extends \<API key>
{
/**
* @var <API key>|MockObject
*/
private $objectManager;
/**
* @var PaymentToken
*/
private $paymentToken;
/**
* @var <API key>
*/
private $factory;
protected function setUp()
{
$objectManager = new ObjectManager($this);
$this->paymentToken = $objectManager->getObject(PaymentToken::class);
$this->objectManager = $this->getMock(<API key>::class);
$this->factory = new <API key>($this->objectManager);
}
/**
* @covers \Magento\Vault\Model\<API key>::create
*/
public function testCreate()
{
$this->objectManager->expects(static::once())
->method('create')
->willReturn($this->paymentToken);
/** @var <API key> $paymentToken */
$paymentToken = $this->factory->create();
static::assertInstanceOf(<API key>::class, $paymentToken);
static::assertEquals(<API key>::TOKEN_TYPE_ACCOUNT, $paymentToken->getType());
}
} |
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Utilities.Internal;
using Roslyn.Utilities;
using StreamJsonRpc;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
<summary>
Defines the language server to be hooked up to an <see cref="ILanguageClient"/> using StreamJsonRpc.
This runs in proc as not all features provided by this server are available out of proc (e.g. some diagnostics).
</summary>
internal class <API key>
{
private readonly IDiagnosticService _diagnosticService;
private readonly <API key> _listener;
private readonly string? _clientName;
private readonly JsonRpc _jsonRpc;
private readonly <API key> <API key>;
private readonly CodeAnalysis.Workspace _workspace;
private <API key> _clientCapabilities;
private bool _shuttingDown;
public <API key>(Stream inputStream,
Stream outputStream,
<API key> <API key>,
CodeAnalysis.Workspace workspace,
IDiagnosticService diagnosticService,
<API key> listenerProvider,
string? clientName)
{
<API key> = <API key>;
_workspace = workspace;
var <API key> = new <API key>();
<API key>.JsonSerializer.Converters.Add(new <API key><<API key>, <API key>>());
<API key>.JsonSerializer.Converters.Add(new <API key><ClientCapabilities, <API key>>());
_jsonRpc = new JsonRpc(new <API key>(outputStream, inputStream, <API key>));
_jsonRpc.AddLocalRpcTarget(this);
_jsonRpc.StartListening();
_diagnosticService = diagnosticService;
_listener = listenerProvider.GetListener(FeatureAttribute.LanguageServer);
_clientName = clientName;
_diagnosticService.DiagnosticsUpdated += <API key>;
_clientCapabilities = new <API key>();
}
public bool Running => !_shuttingDown && !_jsonRpc.IsDisposed;
<summary>
Handle the LSP initialize request by storing the client capabilities
and responding with the server capabilities.
The specification assures that the initialize request is sent only once.
</summary>
[JsonRpcMethod(Methods.InitializeName, <API key> = true)]
public async Task<InitializeResult> InitializeAsync(InitializeParams initializeParams, Cancellation<API key>)
{
_clientCapabilities = (<API key>)initializeParams.Capabilities;
var serverCapabilities = await <API key>.ExecuteRequestAsync<InitializeParams, InitializeResult>(Methods.InitializeName,
initializeParams, _clientCapabilities, _clientName, cancellationToken).ConfigureAwait(false);
// Always support hover - if any LSP client for a content type advertises support,
// then the liveshare provider is disabled. So we must provide for both C# and razor
// or we have different content types.
serverCapabilities.Capabilities.HoverProvider = true;
return serverCapabilities;
}
[JsonRpcMethod(Methods.InitializedName)]
public async Task InitializedAsync()
{
// Publish diagnostics for all open documents immediately following initialization.
var solution = _workspace.CurrentSolution;
var openDocuments = _workspace.GetOpenDocumentIds();
foreach (var documentId in openDocuments)
{
var document = solution.GetDocument(documentId);
if (document != null)
{
await <API key>(document).ConfigureAwait(false);
}
}
}
[JsonRpcMethod(Methods.ShutdownName)]
public Task ShutdownAsync(CancellationToken _)
{
Contract.ThrowIfTrue(_shuttingDown, "Shutdown has already been called.");
_shuttingDown = true;
_diagnosticService.DiagnosticsUpdated -= <API key>;
return Task.CompletedTask;
}
[JsonRpcMethod(Methods.ExitName)]
public Task ExitAsync(CancellationToken _)
{
Contract.ThrowIfFalse(_shuttingDown, "Shutdown has not been called yet.");
try
{
_jsonRpc.Dispose();
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
// Swallow exceptions thrown by disposing our JsonRpc object. Disconnected events can potentially throw their own exceptions so
// we purposefully ignore all of those exceptions in an effort to shutdown gracefully.
}
return Task.CompletedTask;
}
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<LSP.Location[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, LSP.Location[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<WorkspaceEdit> <API key>(RenameParams renameParams, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<RenameParams, WorkspaceEdit>(Methods.<API key>,
renameParams, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<VSReferenceItem[]> <API key>(ReferenceParams referencesParams, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<ReferenceParams, VSReferenceItem[]>(Methods.<API key>,
referencesParams, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<VSCodeAction[]> <API key>(CodeActionParams codeActionParams, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<CodeActionParams, VSCodeAction[]>(Methods.<API key>,
codeActionParams, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(MSLSPMethods.<API key>, <API key> = true)]
public Task<VSCodeAction> <API key>(VSCodeAction vsCodeAction, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<VSCodeAction, VSCodeAction>(MSLSPMethods.<API key>,
vsCodeAction, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public async Task<SumType<CompletionList, CompletionItem[]>> <API key>(CompletionParams completionParams, Cancellation<API key>)
=> await <API key>.ExecuteRequestAsync<CompletionParams, CompletionList>(Methods.<API key>,
completionParams, _clientCapabilities, _clientName, cancellationToken).ConfigureAwait(false);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<CompletionItem> <API key>(CompletionItem completionItem, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<CompletionItem, CompletionItem>(Methods.<API key>,
completionItem, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<FoldingRange[]> <API key>(FoldingRangeParams <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<FoldingRangeParams, FoldingRange[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<DocumentHighlight[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, DocumentHighlight[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<Hover?> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, Hover?>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<object[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, object[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<TextEdit[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, TextEdit[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<TextEdit[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, TextEdit[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<LSP.Location[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, LSP.Location[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<TextEdit[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, TextEdit[]>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<SignatureHelp> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, SignatureHelp>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.<API key>, <API key> = true)]
public Task<object> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, object>(Methods.<API key>,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(Methods.WorkspaceSymbolName, <API key> = true)]
public Task<SymbolInformation[]> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, SymbolInformation[]>(Methods.WorkspaceSymbolName,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(MSLSPMethods.ProjectContextsName, <API key> = true)]
public Task<<API key>?> <API key>(<API key> <API key>, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, <API key>?>(MSLSPMethods.ProjectContextsName,
<API key>, _clientCapabilities, _clientName, cancellationToken);
[JsonRpcMethod(MSLSPMethods.OnAutoInsertName, <API key> = true)]
public Task<<API key>[]> <API key>(<API key> autoInsertParams, Cancellation<API key>)
=> <API key>.ExecuteRequestAsync<<API key>, <API key>[]>(MSLSPMethods.OnAutoInsertName,
autoInsertParams, _clientCapabilities, _clientName, cancellationToken);
private void <API key>(object sender, <API key> e)
{
// LSP doesnt support diagnostics without a document. So if we get project level diagnostics without a document, ignore them.
if (e.DocumentId != null && e.Solution != null)
{
var document = e.Solution.GetDocument(e.DocumentId);
if (document == null || document.FilePath == null)
{
return;
}
// Only publish document diagnostics for the languages this provider supports.
if (document.Project.Language != CodeAnalysis.LanguageNames.CSharp && document.Project.Language != CodeAnalysis.LanguageNames.VisualBasic)
{
return;
}
// LSP does not currently support publishing diagnostics incrememntally, so we re-publish all diagnostics.
var asyncToken = _listener.BeginAsyncOperation(nameof(<API key>));
Task.Run(() => <API key>(document))
.<API key>(asyncToken);
}
}
<summary>
Stores the last published LSP diagnostics with the Roslyn document that they came from.
This is useful in the following scenario. Imagine we have documentA which has contributions to mapped files m1 and m2.
dA -> m1
And m1 has contributions from documentB.
m1 -> dA, dB
When we query for diagnostic on dA, we get a subset of the diagnostics on m1 (missing the contributions from dB)
Since each publish diagnostics notification replaces diagnostics per document,
we must union the diagnostics contribution from dB and dA to produce all diagnostics for m1 and publish all at once.
This dictionary stores the previously computed diagnostics for the published file so that we can
union the currently computed diagnostics (e.g. for dA) with previously computed diagnostics (e.g. from dB).
</summary>
private readonly Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LanguageServer.Protocol.Diagnostic>>> <API key> =
new Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LanguageServer.Protocol.Diagnostic>>>();
<summary>
Stores the mapping of a document to the uri(s) of diagnostics previously produced for this document.
When we get empty diagnostics for the document we need to find the uris we previously published for this document.
Then we can publish the updated diagnostics set for those uris (either empty or the diagnostic contributions from other documents).
We use a sorted set to ensure consistency in the order in which we report URIs.
While it's not necessary to publish a document's mapped file diagnostics in a particular order,
it does make it much easier to write tests and debug issues if we have a consistent ordering.
</summary>
private readonly Dictionary<DocumentId, ImmutableSortedSet<Uri>> <API key> = new Dictionary<DocumentId, ImmutableSortedSet<Uri>>();
<summary>
Basic comparer for Uris used by <see cref="<API key>"/> when publishing notifications.
</summary>
private static readonly Comparer<Uri> s_uriComparer = Comparer<Uri>.Create((uri1, uri2)
=> Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase));
internal async Task <API key>(CodeAnalysis.Document document)
{
// Retrieve all diagnostics for the current document grouped by their actual file uri.
var <API key> = await GetDiagnosticsAsync(document, CancellationToken.None).ConfigureAwait(false);
// Get the list of file uris with diagnostics (for the document).
// We need to join the uris from current diagnostics with those previously published
// so that we clear out any diagnostics in mapped files that are no longer a part
// of the current diagnostics set (because the diagnostics were fixed).
// Use sorted set to have consistent publish ordering for tests and debugging.
var <API key> = <API key>.GetValueOrDefault(document.Id, ImmutableSortedSet.Create<Uri>(s_uriComparer)).Union(<API key>.Keys);
// Update the mapping for this document to be the uris we're about to publish diagnostics for.
<API key>[document.Id] = <API key>;
// Go through each uri and publish the updated set of diagnostics per uri.
foreach (var fileUri in <API key>)
{
// Get the updated diagnostics for a single uri that were contributed by the current document.
var diagnostics = <API key>.GetValueOrDefault(fileUri, ImmutableArray<LanguageServer.Protocol.Diagnostic>.Empty);
if (<API key>.ContainsKey(fileUri))
{
// Get all previously published diagnostics for this uri excluding those that were contributed from the current document.
// We don't need those since we just computed the updated values above.
var <API key> = <API key>[fileUri].Where(kvp => kvp.Key != document.Id).SelectMany(kvp => kvp.Value);
// Since diagnostics are replaced per uri, we must publish both contributions from this document and any other document
// that has diagnostic contributions to this uri, so union the two sets.
diagnostics = diagnostics.AddRange(<API key>);
}
await <API key>(fileUri, diagnostics).ConfigureAwait(false);
// There are three cases here ->
// 1. There are no diagnostics to publish for this fileUri. We no longer need to track the fileUri at all.
// 2. There are diagnostics from the current document. Store the diagnostics for the fileUri and document
// so they can be published along with contributions to the fileUri from other documents.
// 3. There are no diagnostics contributed by this document to the fileUri (could be some from other documents).
// We should clear out the diagnostics for this document for the fileUri.
if (diagnostics.IsEmpty)
{
// We published an empty set of diagnostics for this uri. We no longer need to keep track of this mapping
// since there will be no previous diagnostics that we need to clear out.
<API key>.MultiRemove(document.Id, fileUri);
// There are not any diagnostics to keep track of for this file, so we can stop.
<API key>.Remove(fileUri);
}
else if (<API key>.ContainsKey(fileUri))
{
// We do have diagnostics from the current document - update the published diagnostics map
// to contain the new diagnostics contributed by this document for this uri.
var <API key> = <API key>.GetOrAdd(fileUri, (_) =>
new Dictionary<DocumentId, ImmutableArray<LanguageServer.Protocol.Diagnostic>>());
<API key>[document.Id] = <API key>[fileUri];
}
else
{
// There were diagnostics from other documents, but none from the current document.
// If we're tracking the current document, we can stop.
<API key>.GetOrDefault(fileUri)?.Remove(document.Id);
<API key>.MultiRemove(document.Id, fileUri);
}
}
}
private async Task <API key>(Uri uri, ImmutableArray<LanguageServer.Protocol.Diagnostic> diagnostics)
{
var <API key> = new <API key> { Diagnostics = diagnostics.ToArray(), Uri = uri };
await _jsonRpc.<API key>(Methods.<API key>, <API key>).ConfigureAwait(false);
}
private async Task<Dictionary<Uri, ImmutableArray<LanguageServer.Protocol.Diagnostic>>> GetDiagnosticsAsync(CodeAnalysis.Document document, Cancellation<API key>)
{
var diagnostics = _diagnosticService.GetDiagnostics(document.Project.Solution.Workspace, document.Project.Id, document.Id, null, false, cancellationToken)
.Where(IncludeDiagnostic);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// Retrieve diagnostics for the document. These diagnostics could be for the current document, or they could map
// to a different location in a different file. We need to publish the diagnostics for the mapped locations as well.
// An example of this is razor imports where the generated C# document maps to many razor documents.
// https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-3.1#<API key>
// https://docs.microsoft.com/en-us/aspnet/core/blazor/layouts?view=aspnetcore-3.1#<API key>
// So we get the diagnostics and group them by the actual mapped path so we can publish notifications
// for each mapped file's diagnostics.
var <API key> = diagnostics.GroupBy(diagnostic => GetDiagnosticUri(document, diagnostic)).ToDictionary(
group => group.Key,
group => group.Select(diagnostic => <API key>(diagnostic, text)).ToImmutableArray());
return <API key>;
static Uri GetDiagnosticUri(Document document, DiagnosticData diagnosticData)
{
Contract.ThrowIfNull(diagnosticData.DataLocation, "Diagnostic data location should not be null here");
var filePath = diagnosticData.DataLocation.MappedFilePath ?? diagnosticData.DataLocation.OriginalFilePath;
return ProtocolConversions.GetUriFromFilePath(filePath);
}
static LanguageServer.Protocol.Diagnostic <API key>(DiagnosticData diagnosticData, SourceText text)
{
return new LanguageServer.Protocol.Diagnostic
{
Code = diagnosticData.Id,
Message = diagnosticData.Message,
Severity = ProtocolConversions.<API key>(diagnosticData.Severity),
Range = GetDiagnosticRange(diagnosticData.DataLocation, text),
// Only the unnecessary diagnostic tag is currently supported via LSP.
Tags = diagnosticData.CustomTags.Contains(<API key>.Unnecessary)
? new DiagnosticTag[] { DiagnosticTag.Unnecessary }
: Array.Empty<DiagnosticTag>()
};
}
}
// Some diagnostics only apply to certain clients and document types, e.g. Razor.
// If the <API key>.<API key> property exists, we only include the
// diagnostic if it directly matches the client name.
// If the <API key>.<API key> property doesn't exist,
// we know that the diagnostic we're working with is contained in a C#/VB file, since
// if we were working with a non-C#/VB file, then the property should have been populated.
// In this case, unless we have a null client name, we don't want to publish the diagnostic
// (since a null client name represents the C#/VB language server).
private bool IncludeDiagnostic(DiagnosticData diagnostic) =>
diagnostic.Properties.GetOrDefault(nameof(<API key>.<API key>)) == _clientName;
private static LanguageServer.Protocol.Range? GetDiagnosticRange(<API key>? <API key>, SourceText text)
{
var linePositionSpan = DiagnosticData.GetLinePositionSpan(<API key>, text, useMapped: true);
return ProtocolConversions.LinePositionToRange(linePositionSpan);
}
internal TestAccessor GetTestAccessor() => new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly <API key> _server;
internal TestAccessor(<API key> server)
{
_server = server;
}
internal ImmutableArray<Uri> <API key>()
=> _server.<API key>.Keys.ToImmutableArray();
internal ImmutableArray<DocumentId> <API key>()
=> _server.<API key>.Keys.ToImmutableArray();
internal IImmutableSet<Uri> <API key>(DocumentId documentId)
=> _server.<API key>.GetValueOrDefault(documentId, ImmutableSortedSet<Uri>.Empty);
internal ImmutableArray<LanguageServer.Protocol.Diagnostic> <API key>(DocumentId documentId, Uri uri)
{
if (_server.<API key>.TryGetValue(uri, out var dict) && dict.TryGetValue(documentId, out var diagnostics))
{
return diagnostics;
}
return ImmutableArray<LanguageServer.Protocol.Diagnostic>.Empty;
}
}
}
} |
-- SETTINGS
SET @iTypeOrder = (SELECT MAX(`order`) FROM `sys_options_types` WHERE `group` = 'modules');
INSERT INTO `sys_options_types`(`group`, `name`, `caption`, `icon`, `order`) VALUES
('modules', 'bx_videos', '_bx_videos', 'bx_videos@modules/boonex/videos/|std-icon.svg', IF(ISNULL(@iTypeOrder), 1, @iTypeOrder + 1));
SET @iTypeId = LAST_INSERT_ID();
INSERT INTO `<API key>` (`type_id`, `name`, `caption`, `order`)
VALUES (@iTypeId, 'bx_videos', '_bx_videos', 1);
SET @iCategId = LAST_INSERT_ID();
INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `check`, `check_error`, `extra`, `order`) VALUES
('<API key>', '700', @iCategId, '<API key>', 'digit', '', '', '', 1),
('<API key>', '240', @iCategId, '<API key>', 'digit', '', '', '', 2),
('<API key>', '12', @iCategId, '<API key>', 'digit', '', '', '', 10),
('<API key>', '6', @iCategId, '<API key>', 'digit', '', '', '', 12),
('<API key>', '32', @iCategId, '<API key>', 'digit', '', '', '', 15),
('bx_videos_rss_num', '10', @iCategId, '<API key>', 'digit', '', '', '', 20),
('<API key>', 'title,text', @iCategId, '<API key>', 'list', '', '', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:21:"<API key>";}', 30);
-- PAGE: create entry
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'create-video', 'page.php?i=create-video', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"entity_create";}', 0, 1, 1);
-- PAGE: edit entry
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'edit-video', '', '', '', '', 0, 1, 0, 'BxVideosPageEntry', 'modules/boonex/videos/classes/BxVideosPageEntry.php');
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:11:"entity_edit";}', 0, 0, 0);
-- PAGE: delete entry
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'delete-video', '', '', '', '', 0, 1, 0, 'BxVideosPageEntry', 'modules/boonex/videos/classes/BxVideosPageEntry.php');
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"entity_delete";}', 0, 0, 0);
-- PAGE: view entry
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 12, 2147483647, 1, 'view-video', '', '', '', '', 0, 1, 0, 'BxVideosPageEntry', 'modules/boonex/videos/classes/BxVideosPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('<API key>', 2, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:18:"entity_video_block";}', 0, 0, 0, 0),
('<API key>', 2, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:17:"entity_text_block";}', 0, 0, 1, 1),
('<API key>', 2, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"entity_author";}', 0, 0, 1, 3),
('<API key>', 3, 'bx_videos', '<API key>', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_videos\";s:6:\"method\";s:14:\"entity_context\";}', 0, 0, 1, 1),
('<API key>', 2, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"entity_rating";}', 0, 0, 0, 0),
('<API key>', 3, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:11:"entity_info";}', 0, 0, 1, 2),
('<API key>', 3, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"entity_location";}', 0, 0, 0, 0),
('<API key>', 2, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:18:"entity_all_actions";}', 0, 0, 1, 2),
('<API key>', 4, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:14:"entity_actions";}', 0, 0, 0, 0),
('<API key>', 4, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:21:"<API key>";}', 0, 0, 0, 0),
('<API key>', 4, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:18:"entity_attachments";}', 0, 0, 0, 0),
('<API key>', 2, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"entity_comments";}', 0, 0, 1, 4),
('<API key>', 3, 'bx_videos', '', '<API key>', 3, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:13:"locations_map";s:6:"params";a:2:{i:0;s:9:"bx_videos";i:1;s:4:"{id}";}s:5:"class";s:20:"<API key>";}', 0, 0, 1, 3),
('<API key>', 3, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"browse_featured";s:6:"params";a:1:{i:0;s:8:"extended";}}', 0, 0, 1, 4);
-- PAGE: view entry comments
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'view-video-comments', '', '', '', '', 0, 1, 0, 'BxVideosPageEntry', 'modules/boonex/videos/classes/BxVideosPageEntry.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', 1, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"entity_comments";}', 0, 0, 1);
-- PAGE: popular entries
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_popular', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'videos-popular', 'page.php?i=videos-popular', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_videos_popular', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:14:"browse_popular";s:6:"params";a:3:{s:9:"unit_view";s:7:"gallery";s:13:"empty_message";b:1;s:13:"ajax_paginate";b:0;}}', 0, 1, 1);
-- PAGE: recently updated entries
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_updated', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'videos-updated', 'page.php?i=videos-updated', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_videos_updated', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:14:"browse_updated";s:6:"params";a:3:{s:9:"unit_view";s:7:"gallery";s:13:"empty_message";b:1;s:13:"ajax_paginate";b:0;}}', 0, 1, 1);
-- PAGE: entries of author
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_author', 'videos-author', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, '', '', '', '', 0, 1, 0, 'BxVideosPageAuthor', 'modules/boonex/videos/classes/BxVideosPageAuthor.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_videos_author', 1, 'bx_videos', '', '<API key>', 13, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:18:"my_entries_actions";}', 0, 0, 1, 1),
('bx_videos_author', 1, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"browse_favorite";s:6:"params";a:1:{i:0;s:12:"{profile_id}";}}', 0, 1, 1, 2),
('bx_videos_author', 1, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_author";}', 0, 0, 1, 3);
-- PAGE: entries in context
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_context', 'videos-context', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, '', '', '', '', 0, 1, 0, 'BxVideosPageAuthor', 'modules/boonex/videos/classes/BxVideosPageAuthor.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_videos_context', 1, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:\"module\";s:9:\"bx_videos\";s:6:\"method\";s:14:\"browse_context\";}', 0, 0, 1, 1);
-- PAGE: module home
INSERT INTO `sys_objects_page`(`object`, `uri`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_home', 'videos-home', '<API key>', '<API key>', 'bx_videos', 2, 2147483647, 1, 'page.php?i=videos-home', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_videos_home', 1, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"browse_featured";s:6:"params";a:1:{i:0;s:8:"extended";}}', 0, 1, 1, 0),
('bx_videos_home', 1, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_public";s:6:"params";a:1:{i:0;s:8:"extended";}}', 0, 1, 1, 1),
('bx_videos_home', 2, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:14:"keywords_cloud";s:6:"params";a:2:{i:0;s:9:"bx_videos";i:1;s:9:"bx_videos";}s:5:"class";s:20:"<API key>";}', 0, 1, 1, 0),
('bx_videos_home', 2, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:15:"categories_list";s:6:"params";a:2:{i:0;s:14:"bx_videos_cats";i:1;a:1:{s:10:"show_empty";b:1;}}s:5:"class";s:20:"<API key>";}', 0, 1, 1, 1);
-- PAGE: search for entries
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_search', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'videos-search', 'page.php?i=videos-search', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('bx_videos_search', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:8:"get_form";s:6:"params";a:1:{i:0;a:1:{s:6:"object";s:9:"bx_videos";}}s:5:"class";s:27:"<API key>";}', 0, 1, 1, 1),
('bx_videos_search', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_results";s:6:"params";a:1:{i:0;a:2:{s:6:"object";s:9:"bx_videos";s:10:"show_empty";b:1;}}s:5:"class";s:27:"<API key>";}', 0, 1, 1, 2),
('bx_videos_search', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:8:"get_form";s:6:"params";a:1:{i:0;a:1:{s:6:"object";s:14:"bx_videos_cmts";}}s:5:"class";s:27:"<API key>";}', 0, 1, 0, 3),
('bx_videos_search', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_results";s:6:"params";a:1:{i:0;a:2:{s:6:"object";s:14:"bx_videos_cmts";s:10:"show_empty";b:1;}}s:5:"class";s:27:"<API key>";}', 0, 1, 0, 4);
-- PAGE: module manage own
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_manage', '<API key>', '<API key>', 'bx_videos', 5, 2147483647, 1, 'videos-manage', 'page.php?i=videos-manage', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('bx_videos_manage', 1, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:12:"manage_tools";}}', 0, 1, 0);
-- PAGE: module manage all
INSERT INTO `sys_objects_page`(`object`, `title_system`, `title`, `module`, `layout_id`, `visible_for_levels`, `<API key>`, `uri`, `url`, `meta_description`, `meta_keywords`, `meta_robots`, `cache_lifetime`, `cache_editable`, `deletable`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 5, 192, 1, '<API key>', 'page.php?i=<API key>', '', '', '', 0, 1, 0, 'BxVideosPageBrowse', 'modules/boonex/videos/classes/BxVideosPageBrowse.php');
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', 1, 'bx_videos', '<API key>', '<API key>', 11, 192, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:12:"manage_tools";s:6:"params";a:1:{i:0;s:14:"administration";}}', 0, 1, 0);
-- PAGE: add block to homepage
SET @iBlockOrder = (SELECT `order` FROM `sys_pages_blocks` WHERE `object` = 'sys_home' AND `cell_id` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `active`, `order`) VALUES
('sys_home', 1, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_public";s:6:"params";a:2:{i:0;b:0;i:1;b:0;}}', 1, 0, 0, IFNULL(@iBlockOrder, 0) + 1);
-- PAGES: add page block to profiles modules (trigger* page objects are processed separately upon modules enable/disable)
SET @iPBCellProfile = 3;
INSERT INTO `sys_pages_blocks` (`object`, `cell_id`, `module`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('<API key>', @iPBCellProfile, 'bx_videos', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_author";s:6:"params";a:2:{i:0;s:12:"{profile_id}";i:1;a:2:{s:8:"per_page";s:26:"<API key>";s:13:"empty_message";b:0;}}}', 0, 0, 0);
-- PAGE: service blocks
SET @iBlockOrder = (SELECT `order` FROM `sys_pages_blocks` WHERE `object` = '' AND `cell_id` = 0 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_pages_blocks`(`object`, `cell_id`, `module`, `title_system`, `title`, `designbox_id`, `visible_for_levels`, `type`, `content`, `deletable`, `copyable`, `order`) VALUES
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_public";s:6:"params";a:1:{i:0;s:7:"gallery";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 1),
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:13:"browse_public";s:6:"params";a:1:{i:0;s:4:"full";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 2),
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:14:"browse_popular";s:6:"params";a:1:{i:0;s:8:"extended";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 3),
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:14:"browse_popular";s:6:"params";a:1:{i:0;s:4:"full";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 4),
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"browse_featured";s:6:"params";a:1:{i:0;s:7:"gallery";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 5),
('', 0, 'bx_videos', '', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:"module";s:9:"bx_videos";s:6:"method";s:15:"browse_featured";s:6:"params";a:1:{i:0;s:4:"full";}}', 0, 1, IFNULL(@iBlockOrder, 0) + 6),
('', 0, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_videos\";s:6:\"method\";s:13:\"browse_public\";s:6:\"params\";a:3:{s:9:\"unit_view\";s:8:\"showcase\";s:13:\"empty_message\";b:0;s:13:\"ajax_paginate\";b:0;}}', 0, 1, IFNULL(@iBlockOrder, 0) + 7),
('', 0, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_videos\";s:6:\"method\";s:14:\"browse_popular\";s:6:\"params\";a:3:{s:9:\"unit_view\";s:8:\"showcase\";s:13:\"empty_message\";b:0;s:13:\"ajax_paginate\";b:0;}}', 0, 1, IFNULL(@iBlockOrder, 0) + 8),
('', 0, 'bx_videos', '<API key>', '<API key>', 11, 2147483647, 'service', 'a:3:{s:6:\"module\";s:9:\"bx_videos\";s:6:\"method\";s:15:\"browse_featured\";s:6:\"params\";a:3:{s:9:\"unit_view\";s:8:\"showcase\";s:13:\"empty_message\";b:0;s:13:\"ajax_paginate\";b:0;}}', 0, 1, IFNULL(@iBlockOrder, 0) + 9);
-- MENU: add to site menu
SET @iSiteMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = 'sys_site' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_site', 'bx_videos', 'videos-home', '<API key>', '<API key>', 'page.php?i=videos-home', '', '', 'film col-gray', 'bx_videos_submenu', 2147483647, 1, 1, IFNULL(@iSiteMenuOrder, 0) + 1);
-- MENU: add to homepage menu
SET @iHomepageMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = 'sys_homepage' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_homepage', 'bx_videos', 'videos-home', '<API key>', '<API key>', 'page.php?i=videos-home', '', '', 'film col-gray', 'bx_videos_submenu', 2147483647, 1, 1, IFNULL(@iHomepageMenuOrder, 0) + 1);
-- MENU: add to "add content" menu
SET @iAddMenuOrder = (SELECT `order` FROM `sys_menu_items` WHERE `set_name` = '<API key>' AND `active` = 1 ORDER BY `order` DESC LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('<API key>', 'bx_videos', 'create-video', '<API key>', '<API key>', 'page.php?i=create-video', '', '', 'film col-gray', '', 2147483647, 1, 1, IFNULL(@iAddMenuOrder, 0) + 1);
-- MENU: actions menu for view entry
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_view', '<API key>', 'bx_videos_view', 'bx_videos', 9, 0, 1, 'BxVideosMenuView', 'modules/boonex/videos/classes/BxVideosMenuView.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_videos_view', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_videos_view', 'bx_videos', 'edit-video', '<API key>', '<API key>', 'page.php?i=edit-video&id={content_id}', '', '', 'pencil-alt', '', 2147483647, 1, 0, 1),
('bx_videos_view', 'bx_videos', 'delete-video', '<API key>', '<API key>', 'page.php?i=delete-video&id={content_id}', '', '', 'remove', '', 2147483647, 1, 0, 2);
-- MENU: all actions menu for view entry
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 15, 0, 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('<API key>', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `submenu_popup`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('<API key>', 'bx_videos', 'edit-video', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 10),
('<API key>', 'bx_videos', 'delete-video', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 20),
('<API key>', 'bx_videos', 'comment', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 0, 0, 200),
('<API key>', 'bx_videos', 'view', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 210),
('<API key>', 'bx_videos', 'vote', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 0, 0, 220),
('<API key>', 'bx_videos', 'reaction', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 225),
('<API key>', 'bx_videos', 'score', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 230),
('<API key>', 'bx_videos', 'favorite', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 240),
('<API key>', 'bx_videos', 'feature', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 250),
('<API key>', 'bx_videos', 'repost', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 260),
('<API key>', 'bx_videos', 'report', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 270),
('<API key>', 'bx_videos', '<API key>', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 300),
('<API key>', 'bx_videos', '<API key>', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 320),
('<API key>', 'bx_videos', '<API key>', '<API key>', '', '', '', '', '', '', '', 0, 2147483647, 1, 0, 330),
('<API key>', 'bx_videos', 'more-auto', '<API key>', '<API key>', 'javascript:void(0)', '', '', 'ellipsis-v', '', '', 0, 2147483647, 1, 0, 9999);
-- MENU: actions menu for my entries
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_my', '<API key>', 'bx_videos_my', 'bx_videos', 9, 0, 1, 'BxVideosMenu', 'modules/boonex/videos/classes/BxVideosMenu.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_videos_my', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_videos_my', 'bx_videos', 'create-video', '<API key>', '<API key>', 'page.php?i=create-video', '', '', 'plus', '', 2147483647, 1, 0, 0);
-- MENU: module sub-menu
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_submenu', '<API key>', 'bx_videos_submenu', 'bx_videos', 8, 0, 1, '', '');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('bx_videos_submenu', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('bx_videos_submenu', 'bx_videos', 'videos-home', '<API key>', '<API key>', 'page.php?i=videos-home', '', '', '', '', 2147483647, 1, 1, 1),
('bx_videos_submenu', 'bx_videos', 'videos-popular', '<API key>', '<API key>', 'page.php?i=videos-popular', '', '', '', '', 2147483647, 1, 1, 2),
('bx_videos_submenu', 'bx_videos', 'videos-search', '<API key>', '<API key>', 'page.php?i=videos-search', '', '', '', '', 2147483647, 1, 1, 3),
('bx_videos_submenu', 'bx_videos', 'videos-manage', '<API key>', '<API key>', 'page.php?i=videos-manage', '', '', '', '', 2147483646, 1, 1, 4);
-- MENU: sub-menu for view entry
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 8, 0, 1, 'BxVideosMenuView', 'modules/boonex/videos/classes/BxVideosMenuView.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('<API key>', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('<API key>', 'bx_videos', 'view-video', '<API key>', '<API key>', 'page.php?i=view-video&id={content_id}', '', '', '', '', 2147483647, 0, 0, 1),
('<API key>', 'bx_videos', 'view-video-comments', '<API key>', '<API key>', 'page.php?i=view-video-comments&id={content_id}', '', '', '', '', 2147483647, 0, 0, 2);
-- MENU: custom menu for snippet meta info
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 15, 0, 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('<API key>', 'bx_videos', '<API key>', 0);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `editable`, `order`) VALUES
('<API key>', 'bx_videos', 'date', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 1, 0, 1, 1),
('<API key>', 'bx_videos', 'rating', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 1, 0, 1, 2),
('<API key>', 'bx_videos', 'author', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 1, 0, 1, 3),
('<API key>', 'bx_videos', 'category', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 0, 0, 1, 4),
('<API key>', 'bx_videos', 'tags', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 0, 0, 1, 5),
('<API key>', 'bx_videos', 'views', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 0, 0, 1, 6),
('<API key>', 'bx_videos', 'comments', '<API key>', '<API key>', '', '', '', '', '', 2147483647, 0, 0, 1, 7);
-- MENU: profile stats
SET @iNotifMenuOrder = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name` = 'sys_profile_stats' AND `active` = 1 LIMIT 1);
INSERT INTO `sys_menu_items` (`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('sys_profile_stats', 'bx_videos', '<API key>', '<API key>', '<API key>', 'page.php?i=videos-manage', '', '_self', 'film col-gray', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:41:"<API key>";}', '', 2147483646, 1, 0, @iNotifMenuOrder + 1);
-- MENU: manage tools submenu
INSERT INTO `sys_objects_menu`(`object`, `title`, `set_name`, `module`, `template_id`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('<API key>', '<API key>', '<API key>', 'bx_videos', 6, 0, 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php');
INSERT INTO `sys_menu_sets`(`set_name`, `module`, `title`, `deletable`) VALUES
('<API key>', 'bx_videos', '<API key>', 0);
--INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
--('<API key>', 'bx_videos', 'delete-with-content', '<API key>', '<API key>', 'javascript:void(0)', 'javascript:{js_object}.<API key>({content_id});', '_self', 'far trash-alt', '', 128, 1, 0, 0);
-- MENU: dashboard manage tools
SET @iManageMenuOrder = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_menu_items` WHERE `set_name`='<API key>' LIMIT 1);
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `addon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('<API key>', 'bx_videos', '<API key>', '<API key>', '<API key>', 'page.php?i=<API key>', '', '_self', 'film', 'a:2:{s:6:"module";s:9:"bx_videos";s:6:"method";s:27:"<API key>";}', '', 192, 1, 0, @iManageMenuOrder + 1);
-- MENU: add menu item to profiles modules (trigger* menu sets are processed separately upon modules enable/disable)
INSERT INTO `sys_menu_items`(`set_name`, `module`, `name`, `title_system`, `title`, `link`, `onclick`, `target`, `icon`, `submenu_object`, `visible_for_levels`, `active`, `copyable`, `order`) VALUES
('<API key>', 'bx_videos', 'videos-author', '<API key>', '<API key>', 'page.php?i=videos-author&profile_id={profile_id}', '', '', 'film col-gray', '', 2147483647, 1, 0, 0),
('<API key>', 'bx_videos', 'videos-context', '<API key>', '<API key>', 'page.php?i=videos-context&profile_id={profile_id}', '', '', 'film col-gray', '', 2147483647, 1, 0, 0);
-- PRIVACY
INSERT INTO `sys_objects_privacy` (`object`, `module`, `action`, `title`, `default_group`, `table`, `table_field_id`, `table_field_author`, `override_class_name`, `override_class_file`) VALUES
('<API key>', 'bx_videos', 'view', '<API key>', '3', 'bx_videos_entries', 'id', 'author', '', '');
-- ACL
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_videos', 'create entry', NULL, '<API key>', '', 1, 3);
SET @<API key> = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_videos', 'delete entry', NULL, '<API key>', '', 1, 3);
SET @<API key> = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_videos', 'view entry', NULL, '<API key>', '', 1, 0);
SET @iIdActionEntryView = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_videos', 'set thumb', NULL, '<API key>', '', 1, 3);
SET @iIdActionSetThumb = LAST_INSERT_ID();
INSERT INTO `sys_acl_actions` (`Module`, `Name`, `AdditionalParamName`, `Title`, `Desc`, `Countable`, `DisabledForLevels`) VALUES
('bx_videos', 'edit any entry', NULL, '<API key>', '', 1, 3);
SET @<API key> = LAST_INSERT_ID();
SET @iUnauthenticated = 1;
SET @iAccount = 2;
SET @iStandard = 3;
SET @iUnconfirmed = 4;
SET @iPending = 5;
SET @iSuspended = 6;
SET @iModerator = 7;
SET @iAdministrator = 8;
SET @iPremium = 9;
INSERT INTO `sys_acl_matrix` (`IDLevel`, `IDAction`) VALUES
-- entry create
(@iStandard, @<API key>),
(@iModerator, @<API key>),
(@iAdministrator, @<API key>),
(@iPremium, @<API key>),
-- entry delete
(@iStandard, @<API key>),
(@iModerator, @<API key>),
(@iAdministrator, @<API key>),
(@iPremium, @<API key>),
-- entry view
(@iUnauthenticated, @iIdActionEntryView),
(@iAccount, @iIdActionEntryView),
(@iStandard, @iIdActionEntryView),
(@iUnconfirmed, @iIdActionEntryView),
(@iPending, @iIdActionEntryView),
(@iModerator, @iIdActionEntryView),
(@iAdministrator, @iIdActionEntryView),
(@iPremium, @iIdActionEntryView),
-- set entry thumb
(@iStandard, @iIdActionSetThumb),
(@iModerator, @iIdActionSetThumb),
(@iAdministrator, @iIdActionSetThumb),
(@iPremium, @iIdActionSetThumb),
-- edit any entry
(@iModerator, @<API key>),
(@iAdministrator, @<API key>);
-- SEARCH
SET @iSearchOrder = (SELECT IFNULL(MAX(`Order`), 0) FROM `sys_objects_search`);
INSERT INTO `sys_objects_search` (`ObjectName`, `Title`, `Order`, `ClassName`, `ClassPath`) VALUES
('bx_videos', '_bx_videos', @iSearchOrder + 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php'),
('bx_videos_cmts', '_bx_videos_cmts', @iSearchOrder + 2, '<API key>', 'modules/boonex/videos/classes/<API key>.php');
-- METATAGS
INSERT INTO `<API key>` (`object`, `table_keywords`, `table_locations`, `table_mentions`, `override_class_name`, `override_class_file`) VALUES
('bx_videos', '<API key>', '<API key>', '<API key>', '', '');
-- CATEGORY
INSERT INTO `<API key>` (`object`, `search_object`, `form_object`, `list_name`, `table`, `field`, `join`, `where`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_cats', 'bx_videos', 'bx_videos', 'bx_videos_cats', 'bx_videos_entries', 'cat', 'INNER JOIN `sys_profiles` ON (`sys_profiles`.`id` = `bx_videos_entries`.`author`)', 'AND `sys_profiles`.`status` = ''active''', '', '');
-- STATS
SET @iMaxOrderStats = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_statistics`);
INSERT INTO `sys_statistics` (`module`, `name`, `title`, `link`, `icon`, `query`, `order`) VALUES
('bx_videos', 'bx_videos', '_bx_videos', 'page.php?i=videos-home', 'film col-gray', 'SELECT COUNT(*) FROM `bx_videos_entries` WHERE 1 AND `status` = ''active'' AND `status_admin` = ''active''', @iMaxOrderStats + 1);
-- CHARTS
SET @iMaxOrderCharts = (SELECT IFNULL(MAX(`order`), 0) FROM `sys_objects_chart`);
INSERT INTO `sys_objects_chart` (`object`, `title`, `table`, `field_date_ts`, `field_date_dt`, `field_status`, `query`, `active`, `order`, `class_name`, `class_file`) VALUES
('bx_videos_growth', '<API key>', 'bx_videos_entries', 'added', '', 'status,status_admin', '', 1, @iMaxOrderCharts + 1, 'BxDolChartGrowth', ''),
('<API key>', '<API key>', 'bx_videos_entries', 'added', '', 'status,status_admin', '', 1, @iMaxOrderCharts + 2, '<API key>', '');
-- GRIDS: moderation tools
INSERT INTO `sys_objects_grid` (`object`, `source_type`, `source`, `table`, `field_id`, `field_order`, `field_active`, `paginate_url`, `paginate_per_page`, `paginate_simple`, `paginate_get_start`, `<API key>`, `filter_fields`, `<API key>`, `filter_mode`, `sorting_fields`, `<API key>`, `visible_for_levels`, `override_class_name`, `override_class_file`) VALUES
('<API key>', 'Sql', 'SELECT * FROM `bx_videos_entries` WHERE 1 ', 'bx_videos_entries', 'id', 'added', 'status_admin', '', 20, NULL, 'start', '', 'title,text', '', 'like', 'reports', '', 192, '<API key>', 'modules/boonex/videos/classes/<API key>.php'),
('bx_videos_common', 'Sql', 'SELECT * FROM `bx_videos_entries` WHERE 1 ', 'bx_videos_entries', 'id', 'added', 'status', '', 20, NULL, 'start', '', 'title,text', '', 'like', '', '', 2147483647, 'BxVideosGridCommon', 'modules/boonex/videos/classes/BxVideosGridCommon.php');
INSERT INTO `sys_grid_fields` (`object`, `name`, `title`, `width`, `translatable`, `chars_limit`, `params`, `order`) VALUES
('<API key>', 'checkbox', '_sys_select', '2%', 0, '', '', 1),
('<API key>', 'switcher', '<API key>', '8%', 0, '', '', 2),
('<API key>', 'reports', '<API key>', '5%', 0, '', '', 3),
('<API key>', 'title', '<API key>', '25%', 0, '25', '', 4),
('<API key>', 'added', '<API key>', '20%', 1, '25', '', 5),
('<API key>', 'author', '<API key>', '20%', 0, '25', '', 6),
('<API key>', 'actions', '', '20%', 0, '', '', 7),
('bx_videos_common', 'checkbox', '_sys_select', '2%', 0, '', '', 1),
('bx_videos_common', 'switcher', '<API key>', '8%', 0, '', '', 2),
('bx_videos_common', 'title', '<API key>', '40%', 0, '35', '', 3),
('bx_videos_common', 'added', '<API key>', '30%', 1, '25', '', 4),
('bx_videos_common', 'actions', '', '20%', 0, '', '', 5);
INSERT INTO `sys_grid_actions` (`object`, `type`, `name`, `title`, `icon`, `icon_only`, `confirm`, `order`) VALUES
('<API key>', 'bulk', 'delete', '<API key>', '', 0, 1, 1),
('<API key>', 'single', 'edit', '<API key>', 'pencil-alt', 1, 0, 1),
('<API key>', 'single', 'delete', '<API key>', 'remove', 1, 1, 2),
('<API key>', 'single', 'settings', '<API key>', 'cog', 1, 0, 3),
('bx_videos_common', 'bulk', 'delete', '<API key>', '', 0, 1, 1),
('bx_videos_common', 'single', 'edit', '<API key>', 'pencil-alt', 1, 0, 1),
('bx_videos_common', 'single', 'delete', '<API key>', 'remove', 1, 1, 2),
('bx_videos_common', 'single', 'settings', '<API key>', 'cog', 1, 0, 3);
-- UPLOADERS
INSERT INTO `<API key>` (`object`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_videos_simple', 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php'),
('bx_videos_html5', 1, '<API key>', 'modules/boonex/videos/classes/<API key>.php');
-- ALERTS
INSERT INTO `sys_alerts_handlers` (`name`, `class`, `file`, `service_call`) VALUES
('bx_videos', '<API key>', 'modules/boonex/videos/classes/<API key>.php', '');
SET @iHandler := LAST_INSERT_ID();
INSERT INTO `sys_alerts` (`unit`, `action`, `handler_id`) VALUES
('system', 'save_setting', @iHandler),
('profile', 'delete', @iHandler),
('bx_videos_video_mp4', 'transcoded', @iHandler); |
<?php
namespace Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit;
class MassStatus extends \Magento\Catalog\Controller\Adminhtml\Product\MassStatus
{
} |
<?php
/*
* A class to make it easy to send lots of API requests together asynchronously
*/
namespace iRAP\VidaSDK;
class AsyncRequester
{
private $m_requests;
function __construct(\iRAP\VidaSDK\Models\APIRequest ...$requests)
{
$this->m_requests = $requests;
$this->run();
}
private function run()
{
// Create get requests for each URL
$curlMultiHandle = curl_multi_init();
foreach ($this->m_requests as $i => $request)
{
/* @var $request \iRAP\VidaSDK\Models\APIRequest */
$curlHandles[$i] = $request-><API key>();
<API key>($curlMultiHandle, $curlHandles[$i]);
}
// Start performing the request
do {
$execReturnValue = curl_multi_exec($curlMultiHandle, $runningHandles);
} while ($execReturnValue == <API key>);
// Loop and continue processing the request
while ($runningHandles && $execReturnValue == CURLM_OK)
{
if (curl_multi_select($curlMultiHandle) != -1)
{
usleep(100);
}
do {
$execReturnValue = curl_multi_exec($curlMultiHandle, $runningHandles);
} while ($execReturnValue == <API key>);
}
// Check for any errors
if ($execReturnValue != CURLM_OK)
{
trigger_error("Curl multi read error $execReturnValue\n", E_USER_WARNING);
}
// Extract the content
foreach ($this->m_requests as $i => $request)
{
// Check for errors
$curlError = curl_error($curlHandles[$i]);
if ($curlError == "")
{
$responseContent = <API key>($curlHandles[$i]);
$this->m_requests[$i]->processResponse($responseContent, $curlHandles[$i]);
}
else
{
print "Curl error on handle $i: $curlError\n";
}
// Remove and close the handle
<API key>($curlMultiHandle, $curlHandles[$i]);
curl_close($curlHandles[$i]);
}
// Clean up the curl_multi handle
curl_multi_close($curlMultiHandle);
}
} |
namespace Hopac.Core {
using Microsoft.FSharp.Core;
using Hopac.Core;
using System;
using System.Runtime.CompilerServices;
<summary>Represents a continuation of a parallel job.</summary>
public abstract class Cont<T> : Work {
internal T Value;
internal virtual Pick GetPick(ref int me) {
return null;
}
Use DoCont when NOT invoking continuation from a Job or Alt.
internal abstract void DoCont(ref Worker wr, T value);
}
public abstract class ContIterate<X, Y> : Cont<X> {
internal Cont<Y> yK;
[MethodImpl(AggressiveInlining.Flag)]
public Cont<X> InternalInit(X x, Cont<Y> yK) { this.Value = x; this.yK = yK; return this; }
public abstract Job<X> Do(X x);
internal override Proc GetProc(ref Worker wr) {
return Handler.GetProc(ref wr, ref yK);
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(yK, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
Do(this.Value).DoJob(ref wr, this);
}
internal override void DoCont(ref Worker wr, X x) {
Do(x).DoJob(ref wr, this);
}
}
internal sealed class Fail<T> : Cont<T> {
internal Exception exn;
internal Fail(Exception exn) {
this.exn = exn;
}
internal override Proc GetProc(ref Worker wr) {
throw new <API key>();
}
internal override void DoHandle(ref Worker wr, Exception e) {
throw new <API key>();
}
internal override void DoCont(ref Worker wr, T value) {
throw new <API key>();
}
internal override void DoWork(ref Worker wr) {
throw new <API key>();
}
}
internal static class Cont {
Use Cont.Do when invoking continuation from a Job or Alt.
[MethodImpl(AggressiveInlining.Flag)]
internal static void Do<T>(Cont<T> tK, ref Worker wr, T value) {
#if TRAMPOLINE
unsafe {
if (Unsafe.GetStackPtr() < wr.StackLimit) {
tK.Value = value;
tK.Next = wr.WorkStack;
wr.WorkStack = tK;
} else {
tK.DoCont(ref wr, value);
}
}
#else
tK.DoCont(ref wr, value);
#endif
}
}
internal sealed class FailCont<T> : Cont<T> {
private Handler hr;
private readonly Exception e;
[MethodImpl(AggressiveInlining.Flag)]
internal FailCont(Handler hr, Exception e) {
this.hr = hr;
this.e = e;
}
internal override Proc GetProc(ref Worker wr) {
throw new <API key>();
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(this.hr, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
internal override void DoCont(ref Worker wr, T value) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
}
internal abstract class Cont_State<T, S> : Cont<T> {
internal S State;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont<T> Init(S s) { State = s; return this; }
}
internal abstract class Cont_State<T, S1, S2> : Cont<T> {
internal S1 State1;
internal S2 State2;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont<T> Init(S1 s1, S2 s2) { State1 = s1; State2 = s2; return this; }
}
internal abstract class Cont_State<T, S1, S2, S3> : Cont<T> {
internal S1 State1;
internal S2 State2;
internal S3 State3;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont<T> Init(S1 s1, S2 s2, S3 s3) { State1 = s1; State2 = s2; State3 = s3; return this; }
}
} |
/* Sort.java */
package sorting;
import edu.princeton.cs.introcs.StdRandom;
import edu.princeton.cs.introcs.StdDraw;
/**
* Contains several sorting routines implemented as static methods.
* Arrays are rearranged with smallest item first using compares.
* Sorting algorithms are modified to make visualization better
* Not all algorithms will be implemented as efficiently as they could be
* @author
**/
public final class Sort {
/**
* Simple insertion sort.
* @param a an array of int items.
**/
public static void insertionSort(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0; j -= 1) {
if (less(a[j-1], a[j])) {
break;
}
exch(a, j, j-1);
}
}
}
/**
* Implementation of the SelectionSort algorithm on integer arrays.
* @param a an array of int items.
**/
public static void selectionSort(int[] a) {
int N = a.length;
for (int i = 0; i < N; i += 1) {
int min = i;
for (int j = i+1; j < N; j += 1) {
if (less(a[j], a[min])) {
min = j;
}
}
exch(a, i, min);
}
}
/**
* Shellsort, using a sequence suggested by Gonnet.
* @param a an array of int items.
**/
public static void shellsort(int[] a) {
int N = a.length;
// 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ...
//int h = 1;
//while (h < N/3) h = 3*h + 1;
for (int h = a.length / 2; h > 0;
h = (h == 2) ? 1 : (int) (h / 2.2)) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && (a[j] < a[j-h]); j -= h) {
exch(a, j, j-h);
}
}
}
}
/**
* Standard heapsort.
* @param a an array of int items.
**/
public static void heapsort(int[] a) {
heapify(a);
for (int end = a.length - 1; end > 0;) {
exch(a, end, 0);
end
siftDown(a, 0, end);
}
}
/**
* Turns an array into a max heap
* @param a the array to heapify
*/
private static void heapify(int[] a) {
for (int i = (a.length - 2) / 2; i >= 0; i
siftDown(a, i, a.length - 1);
}
}
/**
* Sifts down an element through the heap.
* @param a array that represents the heap
* @param start the index of the element to sift down
* @param end the end of the heap, the right boundary in the array
*/
private static void siftDown(int[] a, int start, int end) {
int root = start;
while (root * 2 + 1 <= end) {
int child = leftChild(root);
int tmp = root;
if (a[tmp] < a[child]) {
tmp = child;
}
if (child + 1 <= end && a[tmp] < a[child + 1]) {
tmp = child + 1;
}
if (tmp != root) {
exch(a, root, tmp);
root = tmp;
} else {
break;
}
}
}
/**
* Internal method for heapsort.
* @param i the index of an item in the heap.
* @return the index of the left child.
**/
private static int leftChild(int i) {
return 2 * i + 1;
}
/**
* Mergesort algorithm.
* @param a an array of int items.
**/
public static void mergeSort(int[] a) {
int[] tmpArray = new int[a.length];
mergeSort(a, tmpArray, 0, a.length - 1);
}
/**
* Internal method that makes recursive calls.
* @param a an array of int items.
* @param tmpArray an array to place the merged result.
* @param left the left-most index of the subarray.
* @param right the right-most index of the subarray.
**/
private static void mergeSort(int[] a, int[] tmpArray, int left, int right) {
if (left < right) {
int center = (left + right) / 2;
mergeSort(a, tmpArray, left, center);
mergeSort(a, tmpArray, center + 1, right);
merge(a, tmpArray, left, center + 1, right);
}
}
/**
* Internal method that merges two sorted halves of a subarray.
* @param a an array of int items.
* @param tmpArray an array to place the merged result.
* @param leftPos the left-most index of the subarray.
* @param rightPos the index of the start of the second half.
* @param rightEnd the right-most index of the subarray.
**/
private static void merge(int[] a, int[] tmpArray, int leftPos, int rightPos,
int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while (leftPos <= leftEnd && rightPos <= rightEnd) {
if (a[leftPos] < a[rightPos]) {
tmpArray[tmpPos++] = a[leftPos++];
} else {
tmpArray[tmpPos++] = a[rightPos++];
}
}
while (leftPos <= leftEnd) {
tmpArray[tmpPos++] = a[leftPos++];
}
while(rightPos <= rightEnd) {
tmpArray[tmpPos++] = a[rightPos++];
}
// Copy TmpArray back
for (int i = 0; i < numElements; i++, rightEnd
SortSounds.clearRectangle(rightEnd);
a[rightEnd] = tmpArray[rightEnd];
SortSounds.drawRectangle(StdDraw.RED, rightEnd);
StdDraw.show(5);
SortSounds.play(rightEnd);
SortSounds.drawRectangle(StdDraw.CYAN, rightEnd);
StdDraw.show(5);
}
}
/** Quicksort
*/
public static void quicksort(int[] a) {
// StdRandom.shuffle(a);
sort(a, 0, a.length - 1);
}
// quicksort the subarray from a[lo] to a[hi]
private static void sort(int[] a, int lo, int hi) {
if (hi <= lo) return;
int j = partition(a, lo, hi);
sort(a, lo, j-1);
sort(a, j+1, hi);
}
// partition the subarray a[lo..hi] so that a[lo..j-1] <= a[j] <= a[j+1..hi]
// and return the index j.
private static int partition(int[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
int v = a[lo];
while (true) {
// find item on lo to swap
while (less(a[++i], v))
if (i == hi) break;
// find item on hi to swap
while (less(v, a[--j]))
if (j == lo) break; // redundant since a[lo] acts as sentinel
// check if pointers cross
if (i >= j) break;
exch(a, i, j);
}
// put partitioning item v at a[j]
exch(a, lo, j);
// now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi]
return j;
}
/** Returns true if x < y, false otherwise. */
private static boolean less(int x, int y) {
/** YOUR CODE HERE! */
return x < y;
}
/**
* Method to swap two ints in an array.
* @param a an array of ints.
* @param index1 the index of the first int to be swapped.
* @param index2 the index of the second int to be swapped.
**/
private static void exch(int[] a, int index1, int index2) {
/** YOUR CODE HERE! */
int tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
/** YOUR CODE HERE! */
}
} |
<?php
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Verificar_usuario');
$this->load->library('session');
}
public function Index(){
$titulo =array ('titulo'=> 'A Comer! : Conectarse') ;
$this->load->view('plantilla/Header',$titulo);
$this->load->view('conectarse/Index');
$this->load->view('plantilla/Footer');
}
public function verificar_sesion(){
if($this->input->post('submit_login',TRUE)){
//Vemos si el usuario existe.
$variable = $this->Verificar_usuario->verificar_sesion($this->input->post('correo',TRUE),$this->input->post('password',TRUE));
if($variable == TRUE){
//Creando el array con los datos de la session.
$session = array('email'=> $this->input->post('correo',TRUE));
//Esto sirve para asignar una sesion.
$this->session->set_userdata($session);
redirect(base_url(). 'Panel');
}else{
$titulo =array ('titulo'=> 'A Comer! : Conectarse') ;
$mensaje = array('mensaje'=>'El usuario o la contraseña son incorrectos');
$this->load->view('plantilla/Header',$titulo);
$this->load->view('conectarse/Index',$mensaje);
$this->load->view('plantilla/Footer');
}
}
}
} |
<?php
namespace Former\Interfaces;
use Former\Traits\Field;
/**
* Mandatory methods on all frameworks
*/
interface FrameworkInterface
{
/**
* Filter buttons classes
*
* @param array $classes An array of classes
*
* @return array A filtered array
*/
public function filterButtonClasses($classes);
/**
* Filter field classes
*
* @param array $classes An array of classes
*
* @return array A filtered array
*/
public function filterFieldClasses($classes);
/**
* Add classes to a field
*
* @param Field $field
* @param array $classes The possible classes to add
*
* @return Field
*/
public function getFieldClasses(Field $field, $classes);
/**
* Add group classes
*
* @return string A list of group classes
*/
public function getGroupClasses();
/**
* Add label classes
*
* @param array $attributes An array of attributes
*
* @return array An array of attributes with the label class
*/
public function getLabelClasses();
/**
* Add uneditable field classes
*
* @param array $attributes The attributes
*
* @return array An array of attributes with the uneditable class
*/
public function <API key>();
/**
* Add form class
*
* @param array $attributes The attributes
* @param string $type The type of form to add
*
* @return array
*/
public function getFormClasses($type);
/**
* Add actions block class
*
* @param array $attributes The attributes
*
* @return array
*/
public function getActionClasses();
/**
* Render an help text
*
* @param string $text
* @param array $attributes
*
* @return string
*/
public function createHelp($text, $attributes = array());
/**
* Render a disabled field
*
* @param Field $field
*
* @return string
*/
public function createDisabledField(Field $field);
/**
* Render an icon
*
* @param string $icon The icon name
* @param array $attributes Its attributes
*
* @return string
*/
public function createIcon($iconType, $attributes = array());
/**
* Wrap an item to be prepended or appended to the current field
*
* @param string $item
*
* @return string A wrapped item
*/
public function placeAround($item);
/**
* Wrap a field with prepended and appended items
*
* @param Field $field
* @param array $prepend
* @param array $append
*
* @return string A field concatented with prepended and/or appended items
*/
public function prependAppend($field, $prepend, $append);
/**
* Wrap a field with potential additional tags
*
* @param Field $field
*
* @return string A wrapped field
*/
public function wrapField($field);
} |
# Kanye
> Smash your keyboards with ease
Browser support includes every sane browser and **IE7+**.
# Install
From `npm`
shell
npm install kanye --save
From `bower`
shell
bower install kanye --save
# API
Kanye exposes a few methods for interacting with keyboard events.
## `kanye.on(combo, options?, listener)`
Adds an event listener `listener` to the registry. This event listener will fire only when the user input is `combo`, and it can be optionally filtered by a `filter` selector.
The `combo` is expected to be a human-readable keyboard input string such as `cmd+a` or `cmd+shift+b`. If the conditions are satisfied, `listener` will be invoked passing the `event` as an argument. Options are outlined below and they can be omitted.
- `filter` allows you to filter out the event target based on a selector or a DOM element
- `context` allows you to group different shortcuts together, making them easier to remove on the future
## `kanye.off(combo, options?, listener)`
Removes an event listener previously registered by `kanye.on`. You'll need to specify the options again to make sure that the event listener is correctly removed.
## `kanye.clear(context?)`
Remove all event listeners previously added with `.on` to `context`. If a `context` is not provided, every single event listener ever registered with Kanye will be removed.
MIT |
.<API key> { position: relative; text-align: center; background: #efefef; padding: 2px; margin-bottom: 2px; border-radius: 4px; -moz-border-radius: 4px; -<API key>: 4px;}
.<API key> .display { margin: 0 80px; line-height: 1.8em; }
.<API key> .yui3-button { position: absolute; top: 3px; }
.<API key> .prev-year { left: 3px; }
.<API key> .prev-month { left: 35px; }
.<API key> .next-month { right: 35px; }
.<API key> .next-year { right: 3px; } |
(function() {
Dagaz.AI.AI_FRAME = 2000;
Dagaz.AI.REP_DEEP = 30;
Dagaz.AI.MAX_QS_LEVEL = 5;
Dagaz.AI.MAX_AB_VARS = 1000;
Dagaz.AI.MAX_QS_VARS = 5;
Dagaz.AI.STALEMATE = -1;
var penalty =
[ -60, -30, -10, 20, 20, -10, -30, -60,
40, 70, 90, 120, 120, 90, 70, 40,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60,
-60, -30, -10, 20, 20, -10, -30, -60 ];
Dagaz.AI.getPrice = function(design, piece, pos) {
if (pos >= 64) pos -= 64;
if (pos >= 64) return 0;
var r = design.price[piece.type];
if (piece.player == 1) {
r += penalty[pos];
} else {
r += penalty[63 - pos];
}
return r;
}
Dagaz.AI.isMajorPiece = function(type) {
return type > 0;
}
Dagaz.AI.isRepDraw = function(board) {
var z = board.zSign;
for (var i = 0; i < Dagaz.AI.REP_DEEP; i++) {
if (board.parent === null) return false;
var pos = Dagaz.AI.getTarget(board.move);
board = board.parent;
if (board.zSign == z) return true;
if (pos === null) continue;
if (board.getPiece(pos) !== null) return false;
}
return true;
}
var checkStep = function(design, board, player, pos, dir) {
var p = design.navigate(player, pos, dir);
if (p === null) return false;
var piece = board.getPiece(p);
if (piece === null) return false;
if (piece.player == player) return false;
if (piece.type > 1) return false;
return true;
}
var checkSlide = function(design, board, player, pos, dir) {
var p = design.navigate(player, pos, dir);
if (p === null) return false;
var piece = board.getPiece(p);
while (piece === null) {
p = design.navigate(player, p, dir);
if (p === null) return false;
piece = board.getPiece(p);
}
if ((piece.player != player) && (piece.type == 5)) return true;
p = design.navigate(player, p, dir);
if (p === null) return false;
piece = board.getPiece(p);
while (piece === null) {
p = design.navigate(player, p, dir);
if (p === null) return false;
piece = board.getPiece(p);
}
if (piece.player == player) return false;
if (piece.type != 4) return false;
return true;
}
var checkJump = function(design, board, player, pos, d, o, t) {
var p = design.navigate(player, pos, d);
if (p === null) return false;
if (board.getPiece(p) !== null) return false;
p = design.navigate(player, p, o);
if (p === null) return false;
var piece = board.getPiece(p);
if (piece === null) return false;
if (piece.player == player) return false;
if (piece.type != t) return false;
return true;
}
var isAttacked = function(design, board, player, pos) {
return checkStep(design, board, player, pos, 7) ||
checkStep(design, board, player, pos, 4) ||
checkStep(design, board, player, pos, 3) ||
checkSlide(design, board, player, pos, 4) ||
checkSlide(design, board, player, pos, 3) ||
checkSlide(design, board, player, pos, 1) ||
checkSlide(design, board, player, pos, 7) ||
checkJump(design, board, player, pos, 5, 5, 8) || // ne, ne
checkJump(design, board, player, pos, 0, 0, 8) || // se, se
checkJump(design, board, player, pos, 2, 2, 8) || // sw, sw
checkJump(design, board, player, pos, 6, 6, 8) || // nw, nw
checkJump(design, board, player, pos, 5, 7, 7) || // ne, n
checkJump(design, board, player, pos, 5, 3, 7) || // ne, e
checkJump(design, board, player, pos, 0, 1, 7) || // se, s
checkJump(design, board, player, pos, 0, 3, 7) || // se, e
checkJump(design, board, player, pos, 2, 1, 7) || // sw, s
checkJump(design, board, player, pos, 2, 4, 7) || // sw, w
checkJump(design, board, player, pos, 6, 4, 7) || // nw, w
checkJump(design, board, player, pos, 6, 7, 7); // nw, n
}
Dagaz.AI.see = function(design, board, move) {
if (!move.isSimpleMove()) return false;
var pos = move.actions[0][0][0];
var piece = board.getPiece(pos);
if (piece === null) return false;
pos = move.actions[0][1][0];
var target = board.getPiece(pos);
if (target === null) return false;
if (!isAttacked(design, board, piece.player, pos)) return true;
return Dagaz.AI.getPrice(design, target, pos) > Dagaz.AI.getPrice(design, piece, pos);
}
Dagaz.AI.inCheck = function(design, board) {
if (_.isUndefined(board.inCheck)) {
board.inCheck = false;
var king = null;
for (var pos = 0; pos < design.positions.length; pos++) {
var piece = board.getPiece(pos);
if ((piece !== null) && (piece.player == board.player) && (piece.type == 12)) {
if (king !== null) return false;
king = pos;
}
}
if (king === null) return false;
board.inCheck = isAttacked(design, board, board.player, king);
}
return board.inCheck;
}
Dagaz.AI.heuristic = function(ai, design, board, move) {
var r = 1;
if (move.isSimpleMove()) {
var pos = move.actions[0][1][0];
var piece = board.getPiece(pos);
if (piece !== null) {
r += Dagaz.AI.getPrice(design, piece, pos);
pos = move.actions[0][0][0];
piece = board.getPiece(pos);
if (piece !== null) {
r -= Dagaz.AI.getPrice(design, piece, pos);
}
}
}
return r;
}
Dagaz.AI.eval = function(design, params, board, player) {
if (_.isUndefined(board.completeEval)) {
board.completeEval = 0;
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
if (piece === null) return;
var v = Dagaz.AI.getPrice(design, piece, pos);
if (piece.player == board.player) {
board.completeEval += v;
} else {
board.completeEval -= v;
}
});
}
if (board.player == player) {
return board.completeEval;
} else {
return -board.completeEval;
}
}
})(); |
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Literal values</h2>
<pre><code>0
32
true
false</code></pre>
<h2>Full example</h2>
<pre><code>/*
* Checks if two input bits are equal
*/
CHIP Eq {
IN a, b;
OUT out; // True iff a=b
PARTS:
Xor(a=a, b=b, out=uneq);
Not(in=uneq, out=out);
}</code></pre> |
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, a = 0, b = 0;
char c;
string str;
vector<string> v;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> c >> str;
(c == '+') ? a++ : b++;
v.push_back(str);
}
sort(v.begin(), v.end());
for (int i = 0; i < n; i++)
cout << v.at(i) << endl;
cout << "Se comportaram: " << a << " | Nao se comportaram: " << b << endl;
return 0;
} |
package org.politicos.web.rest.vm;
import java.time.ZonedDateTime;
import java.util.Set;
import org.politicos.domain.User;
import org.politicos.service.dto.UserDTO;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* View Model extending the UserDTO, which is meant to be used in the user management UI.
*/
public class ManagedUserVM extends UserDTO {
public static final int PASSWORD_MIN_LENGTH = 4;
public static final int PASSWORD_MAX_LENGTH = 100;
private String id;
private String createdBy;
private ZonedDateTime createdDate;
private String lastModifiedBy;
private ZonedDateTime lastModifiedDate;
@NotNull
@Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH)
private String password;
public ManagedUserVM() {
}
public ManagedUserVM(User user) {
super(user);
this.id = user.getId();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.password = null;
}
public ManagedUserVM(String id, String login, String password, String firstName, String lastName,
String email, boolean activated, String langKey, Set<String> authorities,
String createdBy, ZonedDateTime createdDate, String lastModifiedBy, ZonedDateTime lastModifiedDate) {
super(login, firstName, lastName, email, activated, langKey, authorities);
this.id = id;
this.createdBy = createdBy;
this.createdDate = createdDate;
this.lastModifiedBy = lastModifiedBy;
this.lastModifiedDate = lastModifiedDate;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public ZonedDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(ZonedDateTime createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public ZonedDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(ZonedDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "ManagedUserVM{" +
"id=" + id +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
"} " + super.toString();
}
} |
/*@import url("//fonts.googleapis.com/css?family=Raleway:400");*/
/* line 12, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice {
-moz-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
font-family: "Raleway", sans-serif;
}
/* line 16, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message {
-<API key>: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.14), 0 4px #aaaaaa, 0 5px rgba(0, 0, 0, 0.05);
-moz-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.14), 0 4px #aaaaaa, 0 5px rgba(0, 0, 0, 0.05);
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.14), 0 4px #aaaaaa, 0 5px rgba(0, 0, 0, 0.05);
border: 0px;
background-color: #f6f6f6;
position: relative;
margin-bottom: 1.5em;
font-size: 13px;
color: #666666;
font-weight: 500;
padding: 12px 22px;
}
/* line 28, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-close {
position: absolute;
top: 0px;
right: 0px;
color: #888888;
opacity: 1;
font-weight: bold;
display: block;
font-size: 20px;
line-height: 20px;
padding: 8px 10px 7px 7px;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
}
/* line 44, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-close:hover {
color: #444444;
}
/* line 47, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-close:active {
color: #222222;
}
/* line 50, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-actions {
float: none;
margin-top: 10px;
}
/* line 54, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-actions a {
-webkit-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.05);
-moz-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.05);
box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.05);
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
position: relative;
text-decoration: none;
display: inline-block;
padding: 10px;
color: #888888;
margin-right: 10px;
padding: 3px 10px 5px;
text-transform: capitalize;
}
/* line 66, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-actions a:hover, ul.messenger-theme-ice .messenger-message .messenger-actions a:active {
-webkit-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 2px #aaaaaa;
-moz-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 2px #aaaaaa;
box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 2px #aaaaaa;
color: #444444;
}
/* line 70, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-actions a:active {
-webkit-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 1px #aaaaaa;
-moz-box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 1px #aaaaaa;
box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1), inset 0px 1px rgba(255, 255, 255, 0.15), 0 1px #aaaaaa;
top: 1px;
}
/* line 74, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .messenger-actions .messenger-phrase {
display: none;
}
/* line 77, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message .<API key>:before {
display: block;
z-index: 20;
font-weight: bold;
margin-bottom: 2px;
}
/* line 84, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message.alert-success .<API key>:before {
content: "Success";
}
/* line 88, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message.alert-error .<API key>:before {
content: "Error";
}
/* line 92, ../../src/sass/messenger-theme-ice.sass */
ul.messenger-theme-ice .messenger-message.alert-info .<API key>:before {
content: "Information";
} |
define(function () {
console.log('file-shimmed.js');
}); |
# Elasticsearch Dockerfile
# Pull base image.
FROM elasticsearch:1.5.1
ADD http://stedolan.github.io/jq/download/linux64/jq /usr/local/bin/jq
RUN chmod +x /usr/local/bin/jq
ADD /<API key>.sh /
RUN chmod +x /<API key>.sh
RUN plugin -install mobz/elasticsearch-head
CMD ["/<API key>.sh"] |
package org.diorite.impl.connection.packets.play.server;
import java.io.IOException;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.impl.connection.EnumProtocol;
import org.diorite.impl.connection.<API key>;
import org.diorite.impl.connection.packets.PacketClass;
import org.diorite.impl.connection.packets.<API key>;
import org.diorite.impl.connection.packets.play.<API key>;
import org.diorite.impl.entity.EntityImpl;
import org.diorite.impl.entity.meta.entry.EntityMetadataEntry;
@PacketClass(id = 0x0F, protocol = EnumProtocol.PLAY, direction = <API key>.CLIENTBOUND, size = 150)
public class <API key> extends PacketPlayServer
{
private int entityId; // ~5 bytes
private byte entityTypeId; // 1 byte
private int x; // 4 bytes, WARNING! This is 'fixed-point' number
private int y; // 4 bytes, WARNING! This is 'fixed-point' number
private int z; // 4 bytes, WARNING! This is 'fixed-point' number
private byte yaw; // 1 byte
private byte pitch; // 1 byte
private byte headPitch; // 1 byte
private short movX; // 2 bytes
private short movY; // 2 bytes
private short movZ; // 2 bytes
private Iterable<EntityMetadataEntry<?>> metadata; // ~not more than 128 bytes
public <API key>()
{
}
@SuppressWarnings("MagicNumber")
public <API key>(final EntityImpl entity)
{
this.entityId = entity.getId();
this.entityTypeId = (byte) entity.getMcId();
this.x = (int) (entity.getX() * 32);
this.y = (int) (entity.getY() * 32);
this.z = (int) (entity.getZ() * 32);
this.yaw = (byte) ((entity.getYaw() * 256.0F) / 360.0F);
this.pitch = (byte) ((entity.getPitch() * 256.0F) / 360.0F);
this.headPitch = (byte) ((entity.getHeadPitch() * 256.0F) / 360.0F);
this.movX = (short) (entity.getVelocityX() * 8000); // IDK why 8000
this.movY = (short) (entity.getVelocityY() * 8000);
this.movZ = (short) (entity.getVelocityZ() * 8000);
// TODO pasre metadata from entity, or get it if possible
this.metadata = entity.getMetadata().getEntries();
}
@Override
public void readPacket(final <API key> data) throws IOException
{
this.entityId = data.readVarInt();
this.entityTypeId = data.readByte();
this.x = data.readInt();
this.y = data.readInt();
this.z = data.readInt();
this.yaw = data.readByte();
this.pitch = data.readByte();
this.headPitch = data.readByte();
this.movX = data.readShort();
this.movY = data.readShort();
this.movZ = data.readShort();
this.metadata = data.readEntityMetadata();
}
@Override
public void writeFields(final <API key> data) throws IOException
{
// System.out.println("write packet...3");
data.writeVarInt(this.entityId);
data.writeByte(this.entityTypeId);
data.writeInt(this.x);
data.writeInt(this.y);
data.writeInt(this.z);
data.writeByte(this.yaw);
data.writeByte(this.pitch);
data.writeByte(this.headPitch);
data.writeShort(this.movX);
data.writeShort(this.movY);
data.writeShort(this.movZ);
data.writeEntityMetadata(this.metadata);
}
@Override
public void handle(final <API key> listener)
{
listener.handle(this);
}
public int getEntityId()
{
return this.entityId;
}
public void setEntityId(final int entityId)
{
this.entityId = entityId;
}
public byte getEntityTypeId()
{
return this.entityTypeId;
}
public void setEntityTypeId(final byte entityTypeId)
{
this.entityTypeId = entityTypeId;
}
public int getX()
{
return this.x;
}
public void setX(final int x)
{
this.x = x;
}
public int getY()
{
return this.y;
}
public void setY(final int y)
{
this.y = y;
}
public int getZ()
{
return this.z;
}
public void setZ(final int z)
{
this.z = z;
}
public byte getPitch()
{
return this.pitch;
}
public byte getYaw()
{
return this.yaw;
}
public void setYaw(final byte yaw)
{
this.yaw = yaw;
}
public void setPitch(final byte pitch)
{
this.pitch = pitch;
}
public byte getHeadPitch()
{
return this.headPitch;
}
public void setHeadPitch(final byte headPitch)
{
this.headPitch = headPitch;
}
public short getMovX()
{
return this.movX;
}
public void setMovX(final short movX)
{
this.movX = movX;
}
public short getMovY()
{
return this.movY;
}
public void setMovY(final short movY)
{
this.movY = movY;
}
public short getMovZ()
{
return this.movZ;
}
public void setMovZ(final short movZ)
{
this.movZ = movZ;
}
public Iterable<EntityMetadataEntry<?>> getMetadata()
{
return this.metadata;
}
public void setMetadata(final Iterable<EntityMetadataEntry<?>> metadata)
{
this.metadata = metadata;
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("entityId", this.entityId).append("entityTypeId", this.entityTypeId).append("x", this.x).append("y", this.y).append("z", this.z).append("yaw", this.yaw).append("pitch", this.pitch).append("headPitch", this.headPitch).append("movX", this.movX).append("movY", this.movY).append("movZ", this.movZ).append("metadata", this.metadata).toString();
}
} |
var log = require('winston')
, Backbone = require('backbone')
, tap = require('tap')
, extend = require('util')._extend
, TestResults = require('./test_results')
var ProcessRunner = Backbone.Model.extend({
defaults: {
type: 'process'
}
, initialize: function(attrs){
this.launcher = attrs.launcher
// Assume launcher has already launched
this.set({
name: this.launcher.name
, messages: new Backbone.Collection
, results: this.isTap() ? new TestResults : null
})
this.startTests()
}
, isTap: function(){
return this.launcher.settings.protocol === 'tap'
}
, hasResults: function(){
return this.isTap()
}
, hasMessages: function(){
return this.get('messages').length > 0
}
, registerProcess: function(process){
var settings = this.launcher.settings
var stdout = process.stdout
var stderr = process.stderr
var self = this
if (!settings.hide_stdout){
stdout.on('data', function(data){
self.get('messages').push({
type: 'log'
, text: '' + data
})
})
}
if (!settings.hide_stderr){
stderr.on('data', function(data){
self.get('messages').push({
type: 'error'
, text: '' + data
})
})
}
process.on('exit', function(code){
self.set('allPassed', code === 0)
self.trigger('tests-end')
})
if (this.isTap()){
this.setupTapConsumer(process)
}
}
, setupTapConsumer: function(process){
var stdout = process.stdout
this.message = null
this.stacktrace = []
this.tapConsumer = new tap.Consumer
this.tapConsumer.on('data', this.onTapData.bind(this))
this.tapConsumer.on('end', this.onTapEnd.bind(this))
this.tapConsumer.on('bailout', this.onTapError.bind(this))
stdout.pipe(this.tapConsumer)
}
, onTapData: function(data){
if (typeof data === 'string'){
if (this.message === null){
this.message = data
}else{
this.stacktrace.push(data)
}
return
}
if (data.skip){
return
}
var results = this.get('results')
if (data.id === undefined) {
return
}
var test = {
passed: 0
, failed: 0
, total: 1
, id: data.id
, name: data.name.trim()
, items: []
}
if (!data.ok) {
var stack = data.stack
if (!stack) {
stack = this.stacktrace.join('\n')
} else if (Array.isArray(stack)) {
stack = stack.join("\n")
} else {
stack = JSON.stringify(stack, null, "\t")
}
test.items.push(extend(data, {
passed: false
, message: this.message
, stacktrace: stack
}))
test.failed++
} else {
test.passed++
}
results.addResult(test)
this.message = null
this.stacktrace = []
}
, onTapError: function(){
this.set('results', null)
}
, onTapEnd: function(err, testCount){
var results = this.get('results')
results.set('all', true)
this.tapConsumer.removeAllListeners()
this.tapConsumer = null
this.trigger('all-test-results', this.get('results'))
this.trigger('tests-end')
this.launcher.kill()
}
, startTests: function(){
var self = this
if (this.get('results')){
this.get('results').reset()
}else{
this.set('results', this.isTap() ? new TestResults : null)
}
this.get('messages').reset([])
this.set('allPassed', undefined)
this.launcher.launch(function(process){
self.registerProcess(process)
setTimeout(function(){
self.trigger('tests-start')
}, 1)
})
}
})
module.exports = ProcessRunner |
#include "buddy.hh"
#if BUDDY_DEBUG
#include "kstream.hh"
#endif
#include <cassert>
#include <cstring>
#include <iterator>
using namespace std;
buddy_allocator::buddy_allocator(void *base, size_t len,
void *track_base, size_t track_len)
{
if (track_base == nullptr && track_len == 0) {
track_base = base;
track_len = len;
}
uintptr_t free_base = (uintptr_t)base;
uintptr_t free_end = (uintptr_t)base + len;
uintptr_t track_end = (uintptr_t)track_base + track_len;
assert(track_base <= base && free_end <= track_end);
// Round tracked region out to a multiple of MAX_SIZE so that every
// trackable block has a buddy.
track_base = (void*)((uintptr_t)track_base & ~(MAX_SIZE - 1));
track_end = (track_end + MAX_SIZE - 1) & ~(MAX_SIZE - 1);
track_len = track_end - (uintptr_t)track_base;
// Use a linear allocator to allocate buddy tracking bitmaps from
// the free space.
// XXX(Austin) Should we check if we have more unaligned space at
// the end? Currently, we skip 16 megs between each buddy region.
size_t nBlocks = track_len / MIN_SIZE;
for (size_t i = 0; i < MAX_ORDER; ++i) {
size_t bitmapSize = (nBlocks + 7) / 8;
orders[i].bitmap = (unsigned char*)base;
if ((uintptr_t)base + bitmapSize >= free_end)
// Not enough room for the tracking bitmap
return;
memset(orders[i].bitmap, 0, bitmapSize);
base = (char*)base + bitmapSize;
#if BUDDY_DEBUG
orders[i].debug = (unsigned char*)base;
if ((uintptr_t)base + bitmapSize >= free_end)
return;
memset(orders[i].debug, 0, bitmapSize);
base = (char*)base + bitmapSize;
#endif
nBlocks /= 2;
}
// The MAX_ORDER bitmap is unused because it doesn't have buddy
// pairs.
orders[MAX_ORDER].bitmap = nullptr;
#if BUDDY_DEBUG
orders[MAX_ORDER].debug = nullptr;
#endif
// Record the region we can track. These must be multiples of
// MIN_SIZE, but they will be since we've already rounded to
// MAX_SIZE above.
this->base = (uintptr_t)track_base;
limit = track_end;
// Create free block list.
uintptr_t block_base = ((uintptr_t)base + MIN_SIZE - 1) & ~(MIN_SIZE - 1);
uintptr_t block_end = free_end & ~(MIN_SIZE - 1);
for (uintptr_t block = block_base; block < block_end; ) {
if ((block & (MAX_SIZE - 1)) == 0 && block + MAX_SIZE <= block_end) {
// Fast path for MAX_SIZE blocks
free_order((void*)block, MAX_ORDER);
block += MAX_SIZE;
} else {
free_order((void*)block, 0);
block += MIN_SIZE;
}
}
free_bytes = block_end - block_base;
bitmap_bytes = (uintptr_t)base - free_base;
waste_bytes = block_base - (uintptr_t)base;
#if BUDDY_DEBUG
if (0)
console.println("bitmap ", (void*)((uintptr_t)free_base), "\n"
" ..", (void*)((uintptr_t)base - 1), "\n",
"block ", (void*)block_base, "\n"
" ..", (void*)(block_end - 1));
#endif
}
void*
buddy_allocator::alloc_order(size_t order)
{
// Is a block of this order available?
if (!orders[order].blocks.empty()) {
// Get a block
struct block *block = &orders[order].blocks.front();
orders[order].blocks.pop_front();
// Mark it as allocated
if (order < MAX_ORDER) {
bool state = flip_bit(block, order);
// Now both buddies must be allocated (otherwise they would have
// been promoted).
assert(state == 0);
mark_allocated(block, order, true);
}
assert((uintptr_t)block >= base && (uintptr_t)block < limit);
return (void*)block;
} else if (order == MAX_ORDER) {
return nullptr;
} else {
// We need to split a block. We'll allocate one of order + 1, use
// the first half of it and add the second half to order's free
// list.
void *parent = alloc_order(order + 1);
if (!parent)
return nullptr;
struct block *second_half =
(struct block*)((char*)parent + (MIN_SIZE << order));
orders[order].blocks.push_front(second_half);
// Mark this pair as half-allocated
bool state = flip_bit(parent, order);
assert(state == 1);
mark_allocated(parent, order, true);
assert((uintptr_t)parent >= base && (uintptr_t)parent < limit);
return parent;
}
}
void
buddy_allocator::free_order(void *ptr, size_t order)
{
assert(base <= (uintptr_t)ptr && (uintptr_t)ptr < limit);
#if BUDDY_DEBUG && !<API key>
/*
* Per-CPU buddy allocators cannot answer is_allocated() correctly.
*/
if (order < MAX_ORDER)
if (!is_allocated(ptr, order))
spanic.println("double free or too-small free of ", ptr,
" of size ", MIN_SIZE << order, " (order ", order, ")");
if (order > 0)
if (is_allocated(ptr, order - 1))
spanic.println("too-large free of ", ptr,
" of size ", MIN_SIZE << order, " (order ", order, ")");
#endif
mark_allocated(ptr, order, false);
if (order < MAX_ORDER && flip_bit(ptr, order) == 0) {
// This block's buddy is also free. Remove the buddy from its
// list, combine them, and free to the higher order.
uintptr_t buddy = (uintptr_t)ptr ^ ((uintptr_t)MIN_SIZE << order);
orders[order].blocks.erase(
orders[order].blocks.iterator_to((struct block*)buddy));
uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order);
free_order((void*)parent, order + 1);
} else {
// This block's buddy is allocated. Release this block to the
// current order.
orders[order].blocks.push_front((struct block*)ptr);
}
}
bool
buddy_allocator::flip_bit(void *ptr, size_t order)
{
size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1);
unsigned char mask = 1 << (bit % 8);
return (orders[order].bitmap[bit / 8] ^= mask) & mask;
}
#if BUDDY_DEBUG
bool
buddy_allocator::is_allocated(void *ptr, size_t order)
{
size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1);
unsigned char mask = 1 << (bit % 8);
uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order);
bool debug = !!(orders[order].debug[bit / 8] & mask);
if ((uintptr_t)ptr == parent)
// First of buddy pair
return debug;
else
// Second of buddy pair
return debug ^ !!(orders[order].bitmap[bit / 8] & mask);
}
void
buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated)
{
if (order == MAX_ORDER)
return;
uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order);
if ((uintptr_t)ptr != parent)
return;
size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1);
unsigned char mask = 1 << (bit % 8);
if (allocated)
orders[order].debug[bit / 8] |= mask;
else
orders[order].debug[bit / 8] &= ~mask;
}
#else
void
buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated)
{
}
#endif
buddy_allocator::stats
buddy_allocator::get_stats() const
{
stats out{};
for (size_t order = 0; order <= MAX_ORDER; ++order) {
for (auto &b : orders[order].blocks) {
(void)b; // Hush g++
++out.nfree[order];
}
out.free += out.nfree[order] * (MIN_SIZE << order);
}
assert(out.free == get_free_bytes());
out.metadata_bytes = bitmap_bytes;
out.waste_bytes = waste_bytes;
return out;
} |
package edu.umass.cs.pig.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassPrinter {
public void print(Object obj) {
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
System.out.println(f.getName());
}
for (Method m : obj.getClass().getDeclaredMethods()) {
m.setAccessible(true);
System.out.println(m.getName());
}
for (Constructor<?> c : obj.getClass().<API key>()) {
c.setAccessible(true);
System.out.println(c.getName());
}
}
} |
/* $Id: xtmrctr_intr.c,v 1.1.2.1 2011/08/09 05:09:14 svemula Exp $ */
#include "xtmrctr.h"
void XTmrCtr_SetHandler(XTmrCtr * InstancePtr, XTmrCtr_Handler FuncPtr,
void *CallBackRef)
{
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(FuncPtr != NULL);
Xil_AssertVoid(InstancePtr->IsReady == <API key>);
InstancePtr->Handler = FuncPtr;
InstancePtr->CallBackRef = CallBackRef;
}
void <API key>(void *InstancePtr)
{
XTmrCtr *TmrCtrPtr = NULL;
u8 TmrCtrNumber;
u32 ControlStatusReg;
/*
* Verify that each of the inputs are valid.
*/
Xil_AssertVoid(InstancePtr != NULL);
/*
* Convert the non-typed pointer to an timer/counter instance pointer
* such that there is access to the timer/counter
*/
TmrCtrPtr = (XTmrCtr *) InstancePtr;
/*
* Loop thru each timer counter in the device and call the callback
* function for each timer which has caused an interrupt
*/
for (TmrCtrNumber = 0;
TmrCtrNumber < <API key>; TmrCtrNumber++) {
ControlStatusReg = XTmrCtr_ReadReg(TmrCtrPtr->BaseAddress,
TmrCtrNumber,
XTC_TCSR_OFFSET);
/*
* Check if interrupt is enabled
*/
if (ControlStatusReg & <API key>) {
/*
* Check if timer expired and interrupt occured
*/
if (ControlStatusReg & <API key>) {
/*
* Increment statistics for the number of
* interrupts and call the callback to handle
* any application specific processing
*/
TmrCtrPtr->Stats.Interrupts++;
TmrCtrPtr->Handler(TmrCtrPtr->CallBackRef,
TmrCtrNumber);
/*
* Read the new Control/Status Register content.
*/
ControlStatusReg =
XTmrCtr_ReadReg(TmrCtrPtr->BaseAddress,
TmrCtrNumber,
XTC_TCSR_OFFSET);
/*
* If in compare mode and a single shot rather
* than auto reload mode then disable the timer
* and reset it such so that the interrupt can
* be acknowledged, this should be only temporary
* till the hardware is fixed
*/
if (((ControlStatusReg &
<API key>) == 0) &&
((ControlStatusReg &
<API key>)== 0)) {
/*
* Disable the timer counter and
* reset it such that the timer
* counter is loaded with the
* reset value allowing the
* interrupt to be acknowledged
*/
ControlStatusReg &=
~<API key>;
XTmrCtr_WriteReg(
TmrCtrPtr->BaseAddress,
TmrCtrNumber,
XTC_TCSR_OFFSET,
ControlStatusReg |
XTC_CSR_LOAD_MASK);
/*
* Clear the reset condition,
* the reset bit must be
* manually cleared by a 2nd write
* to the register
*/
XTmrCtr_WriteReg(
TmrCtrPtr->BaseAddress,
TmrCtrNumber,
XTC_TCSR_OFFSET,
ControlStatusReg);
}
/*
* Acknowledge the interrupt by clearing the
* interrupt bit in the timer control status
* register, this is done after calling the
* handler so the application could call
* IsExpired, the interrupt is cleared by
* writing a 1 to the interrupt bit of the
* register without changing any of the other
* bits
*/
XTmrCtr_WriteReg(TmrCtrPtr->BaseAddress,
TmrCtrNumber,
XTC_TCSR_OFFSET,
ControlStatusReg |
<API key>);
}
}
}
} |
// +build linux darwin freebsd openbsd netbsd dragonfly
package schedule
import (
"fmt"
"github.com/headmade/backuper/hmutil"
)
func (m *Manager) writeCrontab(schedule string, cmd string) error {
taskFormat := `crontab -l\
| ( grep -v 'gobackuper %s' ; echo '%s %s %s gobackuper %s >> /var/log/gobackuper_cron.log 2>&1' )\
| crontab`
task := fmt.Sprintf(taskFormat, cmd, schedule, CRON_PATH, CRON_GOTRACEBACK, cmd)
_, err := hmutil.System(task)
return err
} |
<?php
namespace Omnimail\Common;
class Credentials implements <API key>
{
private $credentials = array();
public function __construct($credentials)
{
$this->credentials = $credentials;
}
/**
* @return array
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* @param array $credentials
*/
public function setCredentials($credentials)
{
$this->credentials = $credentials;
}
/**
* Get a single credential parameter.
*
* @param string $parameter
* @return mixed|null
*/
public function get($parameter)
{
return isset($this->credentials[$parameter]) ? $this->credentials[$parameter] : null;
}
public function __debugInfo()
{
}
} |
using System.Collections.Generic;
namespace Spect.Net.TestParser.Plan
{
<summary>
Respresents a portmock plan
</summary>
public class PortMockPlan
{
<summary>
The mocked port's address
</summary>
public ushort PortAddress { get; }
<summary>
The port pulses
</summary>
public List<PortPulsePlan> Pulses { get; } = new List<PortPulsePlan>();
<summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
public PortMockPlan(ushort portAddress)
{
PortAddress = portAddress;
}
<summary>
Add a new pulse to the port mock
</summary>
<param name="pulse"></param>
public void AddPulse(PortPulsePlan pulse)
{
Pulses.Add(pulse);
}
}
} |
<!DOCTYPE html PUBLIC "-
<html>
<head>
<title>Maryland Archeology Month Events</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body background="../../Images/white_Speckle_BG.gif">
<div align="center">
<!-- Begin Page Heading -->
</div>
<table width="100%" border="0" cellpadding="5" cellspacing="5" background="../../Images/white_Speckle_BG.gif">
<tr>
<td width="23%" align="center">
<h3><a href="index.html"><img src="Archmonthlogo.gif" width="177" height="150" border="0" /></a><br />
</h3></td>
<td width="57%" align="center" valign="top">
<h1><font color="9900000">Maryland Archeology Month </font></h1>
<h1><font color="9900000">April 2018</font></h1>
<h1 dir="ltr"><font color="#990000">Charting the Past: </font><font color="9900000">30 Years of Exploring Maryland's Submerged History</font></h1></td>
<td width="20%" align="center" valign="middle" bordercolor="#FFFFFF">
<h3><img src="MMAP Symbol.jpg" alt="MMAP" width="325" height="225" /></h3> </td>
</tr>
<tr>
<td colspan="3" align="center">
<hr>
<p><b><i>Maryland Archeology Month</i> is a celebration of our shared archeological
heritage - created by Maryland's diverse inhabitants over the last
12,000 years. Protecting this irreplaceable archeological heritage
provides opportunities to discover and learn from the past. We invite
you to "Get Involved!" in Maryland's past by attending as many events
as you can.</b></p></td>
</tr>
</table>
<div align="center">
<!-- End Page Heading -->
<!-- Begin Page Content -->
</div>
<div align="center"></div>
<table width="100%" height="609" border="0" cellpadding="0" cellspacing="0" background="../../Images/white_Speckle_BG.gif">
<tr>
<td height="31" colspan="3" align="left"><hr /></td>
</tr>
<tr>
<!-- Begin Links to Map and Calendar Entry Points -->
<td width="32%" height="578" align="center" valign="top">
<table width="100%" height="474" border="1" cellpadding="5" cellspacing="5" bordercolor="#000000" background="../../Images/white_Speckle_BG.gif">
<tr>
<td align="center">
<h2>Archeology Month Events:</h2>
<hr />
<a href="Archmonth_Map.html"><img src="md.gif" alt="Location" width="290" height="151" border="0" /></a>
<h3>Events by Location</h3>
<hr />
<p><a href="Calendar1.htm"><img src="monthvsmall.GIF" width="172" height="195" border="0" /></a></p>
<p>Events by Date </p>
<hr /> </td>
</tr>
</table> </td>
<!-- End Links to Map and Calendar Entrypoints -->
<td width="68%" colspan="2" valign="top">
<table width="100%" height="164" border="0" cellpadding="5" cellspacing="5" background="../../Images/white_Speckle_BG.gif">
<tr>
<td height="154" colspan="2" align="center" valign="top" background="../../Images/white_Speckle_BG.gif">
<h2> Baltimore City Events </h2>
<hr />
<h3 align="left">There are no Maryland Archeology Month events
scheduled
at this time.</h3>
<p align="left"> </p></td>
</tr>
</table> </td>
</tr>
</table>
<div align="center"></div>
<table width="1066" border="0" align="center">
<tr>
<td width="155"><strong><font size="+2">Sponsored by</font></strong><font size="+2">:</font></td>
<td width="215"> </td>
<td width="184"> </td>
<td width="217"> </td>
<td width="273"> </td>
</tr>
<tr>
<td><div align="center"><img src="asm-seal.gif" width="149" height="150" /></div></td>
<td><div align="center"><img src="logo5.gif" width="149" height="128" /></div></td>
<td><div align="center"><img src="SHA_Logo.gif" width="175" height="133" /></div></td>
<td><div align="center"><img src="CfMA_Logo_96dpi.gif" width="149" height="84" /></div></td>
<td><div align="center"><img src="MNCPPlogo.jpg" width="180" height="85" /></div></td>
</tr>
<tr>
<td><div align="center"></div></td>
<td><div align="center"></div></td>
<td><div align="center"><img src="stmary-logo.jpg" width="213" height="49" /></div></td>
<td><div align="center"><img src="smcm_logo.jpg" width="218" height="38" /></div></td>
<td><div align="center"></div></td>
</tr>
</table>
<div align="center"></div>
<p> </p>
</body>
</html> |
var Tile = require('../Tile');
var IsInLayerBounds = require('./IsInLayerBounds');
var CalculateFacesAt = require('./CalculateFacesAt');
var SetTileCollision = require('./SetTileCollision');
/**
* Puts a tile at the given tile coordinates in the specified layer. You can pass in either an index
* or a Tile object. If you pass in a Tile, all attributes will be copied over to the specified
* location. If you pass in an index, only the index at the specified location will be changed.
* Collision information will be recalculated at the specified location.
*
* @function Phaser.Tilemaps.Components.PutTileAt
* @private
* @since 3.0.0
*
* @param {(integer|Phaser.Tilemaps.Tile)} tile - The index of this tile to set or a Tile object.
* @param {integer} tileX - The x coordinate, in tiles, not pixels.
* @param {integer} tileY - The y coordinate, in tiles, not pixels.
* @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated.
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
*
* @return {Phaser.Tilemaps.Tile} The Tile object that was created or added to this map.
*/
var PutTileAt = function (tile, tileX, tileY, recalculateFaces, layer)
{
if (!IsInLayerBounds(tileX, tileY, layer)) { return null; }
if (recalculateFaces === undefined) { recalculateFaces = true; }
var oldTile = layer.data[tileY][tileX];
var oldTileCollides = oldTile && oldTile.collides;
if (tile instanceof Tile)
{
if (layer.data[tileY][tileX] === null)
{
layer.data[tileY][tileX] = new Tile(layer, tile.index, tileX, tileY, tile.width, tile.height);
}
layer.data[tileY][tileX].copy(tile);
}
else
{
var index = tile;
if (layer.data[tileY][tileX] === null)
{
layer.data[tileY][tileX] = new Tile(layer, index, tileX, tileY, layer.tileWidth, layer.tileHeight);
}
else
{
layer.data[tileY][tileX].index = index;
}
}
// Updating colliding flag on the new tile
var newTile = layer.data[tileY][tileX];
var collides = layer.collideIndexes.indexOf(newTile.index) !== -1;
SetTileCollision(newTile, collides);
// Recalculate faces only if the colliding flag at (tileX, tileY) has changed
if (recalculateFaces && (oldTileCollides !== newTile.collides))
{
CalculateFacesAt(tileX, tileY, layer);
}
return newTile;
};
module.exports = PutTileAt; |
#include "Shape.h"
#define _USE_MATH_DEFINES // for C++
#include <cmath>
#define _USE_MATH_DEFINES // for C
#include <math.h>
using namespace glm;
// What is a shape? :P
Shape::Shape(GLfloat* coords, GLsizei dataSize, GLuint program, bool isWater, bool isStar, bool isBox, ShaderHelpers* help)
{
glGenVertexArrays(1,&vao);
glBindVertexArray(vao);
vertexCount = dataSize;
programObj=program;
dataCount=2*vertexCount;
helper = help;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER,vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*dataCount, coords, GL_STATIC_DRAW);
<API key>(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
<API key>(0);
pTime = 0;
matrix = <API key>(program, "worldMatrix");
// cases for types, guess I should've used an enum eh?
water = isWater;
star = isStar;
box = isBox;
}
Shape::~Shape(void)
{
<API key>(1,&vao);
glDeleteBuffers(1,&vbo);
}
void Shape::Draw(float x, float y, float xScale, float yScale)
{
// gets time and sets dt for fun
int currentTime = glutGet(GLUT_ELAPSED_TIME);
int dt = currentTime - (int)pTime;
// sets the vertex shader's offset and scale values
vec3 offsetV = vec3(x,y,0);
vec3 scaleV = vec3(xScale, yScale, 1.0f);
vec3 rotationV = vec3(1,0,0);
float angle = 0;
mat4 worldMatrix = translate(offsetV) * scale(scaleV) * rotate(angle,rotationV);
//helper->setShaderVec3(programObj, "position", vec3(1,0,0.5f));
helper->setShaderMatrix(programObj, "worldMatrix", worldMatrix);
glBindVertexArray(vao);
// sets the vertex shader's water boolean value
GLint isWater = <API key>(programObj, "water");
glProgramUniform1i(programObj, isWater, water);
if(water) // case for water
{
int varLoc = <API key>(programObj, "time");
glProgramUniform1f(programObj,varLoc, currentTime*0.001f);
glDrawArrays(GL_TRIANGLE_FAN,0,vertexCount);
}
else if(!star) // case if a fish or box or anything else which is neither a star nor water
{
helper->setShaderColor(programObj, "color", 0,0.5f,0.5f);
if(box)
helper->setShaderColor(programObj, "color", 0,0,0.3f);
glDrawArrays(GL_TRIANGLES,0,vertexCount);
}
else // case for stars
{
helper->setShaderColor(programObj, "color", 1.0f,1.0f,1.0f);
glDrawArrays(GL_TRIANGLES,0,vertexCount);
}
// updates the current time
pTime=(float)currentTime;
} |
require 'helper'
class <API key> < Test::Unit::TestCase
context 'EPP::Contact::Delete' do
setup do
@contact_delete = EPP::Contact::Delete.new('UK-39246923864')
@delete = EPP::Commands::Delete.new(@contact_delete)
@command = EPP::Requests::Command.new('ABC-123', @delete)
@request = EPP::Request.new(@command)
@xml = @request.to_xml
<API key>
end
should 'validate against schema' do
assert @xml.validate_schema(schema)
end
should 'set clTRID' do
assert_equal 'ABC-123', xpath_find('//epp:clTRID')
end
should 'set example.com as name' do
assert_equal 'UK-39246923864', xpath_find('//contact:id')
end
end
end |
{% load cloud_extras %}
{% load tz %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="author" content="Jan Paricka">
<meta name="keyword" content="">
<meta name="description" content="">
<link rel="<API key>" sizes="144x144" href="/static/admin-assets/ico/<API key>.png">
<link rel="<API key>" sizes="114x114" href="/static/admin-assets/ico/<API key>.png">
<link rel="<API key>" sizes="72x72" href="/static/admin-assets/ico/<API key>.png">
<link rel="<API key>" sizes="57x57" href="/static/admin-assets/ico/<API key>.png">
<link rel="shortcut icon" type="image/png" href="/static/favicon.ico"/>
<title>Project Cloudly | Login</title>
<!-- Bootstrap core CSS -->
<link href="/static/admin-assets/css/bootstrap.min.css" rel="stylesheet">
<!-- page css files -->
<link href="/static/admin-assets/css/font-awesome.min.css" rel="stylesheet">
<link href="/static/admin-assets/css/jquery-ui.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/admin-assets/css/style.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container-fluid content">
<div class="row">
<div id="content" class="col-sm-12 full">
<div class="row">
<div class="login-box">
<div class="header">
Login to the Cloud
</div>
<p>
<a class="btn btn-twitter" href="/twitter/login/"><span>Login via Twitter</span></a>
</p>
<div class="text-with-hr">
<span>or using your registered e-mail address</span>
</div>
<form action="/login/" method='POST' class='form-validate' id="login">{% csrf_token %}
{% csrf_token %}
<fieldset class="col-sm-12">
{% if err %}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
The username and/or password is incorrect.
</div>
{% endif %}
<div class="form-group">
<div class="controls row">
<div class="input-group col-sm-12">
<input class="form-control" type="text" placeholder="E-mail" required name="username">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
</div>
</div>
</div>
<div class="form-group">
<div class="controls row">
<div class="input-group col-sm-12">
<input class="form-control" type="password" placeholder="Password" required name="password">
<span class="input-group-addon"><i class="fa fa-key"></i></span>
</div>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-lg btn-primary col-xs-12">Login</button>
</div>
</fieldset>
</form>
{% comment %}
<a class="pull-left" href="#">Forgot Password?</a>
{% endcomment %}
<a class="pull-right" href="/register/">Sign Up!</a>
<div class="clearfix"></div>
</div>
</div><!--/row-->
</div>
</div><!--/row-->
</div><!--/container-->
<!-- start: JavaScript-->
<!--[if !IE]>-->
<script src="/static/admin-assets/js/jquery-2.1.0.min.js"></script>
<!--<![endif]-->
<!--[if IE]>
<script src="/static/admin-assets/js/jquery-1.11.0.min.js"></script>
<![endif]
<!--[if !IE]>-->
<script type="text/javascript">
window.jQuery || document.write("<script src='/static/admin-assets/js/jquery-2.1.0.min.js'>"+"<"+"/script>");
</script>
<!--<![endif]-->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='/static/admin-assets/js/jquery-1.11.0.min.js'>"+"<"+"/script>");
</script>
<![endif]
<script src="/static/admin-assets/js/jquery-migrate-1.2.1.min.js"></script>
<script src="/static/admin-assets/js/bootstrap.min.js"></script>
<!-- page scripts -->
<script src="/static/admin-assets/js/jquery.icheck.min.js"></script>
<!-- theme scripts -->
<script src="/static/admin-assets/js/custom.min.js"></script>
<script src="/static/admin-assets/js/core.js"></script>
<!-- inline scripts related to this page -->
<script src="/static/admin-assets/js/pages/login.js"></script>
<!-- end: JavaScript-->
{% include "google_analytics.html" %}
</body>
</html> |
.md-contact-chips .md-chips md-chip {
padding: 0 25px 0 0; }
[dir=rtl] .md-contact-chips .md-chips md-chip {
padding: 0 0 0 25px; }
.md-contact-chips .md-chips md-chip .md-contact-avatar {
float: left; }
[dir=rtl] .md-contact-chips .md-chips md-chip .md-contact-avatar {
float: right; }
.md-contact-chips .md-chips md-chip .md-contact-avatar img {
height: 32px;
border-radius: 16px; }
.md-contact-chips .md-chips md-chip .md-contact-name {
display: inline-block;
height: 32px;
margin-left: 8px; }
[dir=rtl] .md-contact-chips .md-chips md-chip .md-contact-name {
margin-left: auto;
margin-right: 8px; }
.<API key> {
height: 56px; }
.<API key> img {
height: 40px;
border-radius: 20px;
margin-top: 8px; }
.<API key> .md-contact-name {
margin-left: 8px;
width: 120px; }
[dir=rtl] .<API key> .md-contact-name {
margin-left: auto;
margin-right: 8px; }
.<API key> .md-contact-name, .<API key> .md-contact-email {
display: inline-block;
overflow: hidden;
text-overflow: ellipsis; }
.<API key> li {
height: 100%; }
.md-chips {
display: block;
font-family: Roboto, "Helvetica Neue", sans-serif;
font-size: 16px;
padding: 0 0 8px 3px;
vertical-align: middle; }
.md-chips:after {
content: '';
display: table;
clear: both; }
[dir=rtl] .md-chips {
padding: 0 3px 8px 0; }
.md-chips.md-readonly .<API key> {
min-height: 32px; }
.md-chips:not(.md-readonly) {
cursor: text; }
.md-chips.md-removable md-chip {
padding-right: 22px; }
[dir=rtl] .md-chips.md-removable md-chip {
padding-right: 0;
padding-left: 22px; }
.md-chips.md-removable md-chip .md-chip-content {
padding-right: 4px; }
[dir=rtl] .md-chips.md-removable md-chip .md-chip-content {
padding-right: 0;
padding-left: 4px; }
.md-chips md-chip {
cursor: default;
border-radius: 16px;
display: block;
height: 32px;
line-height: 32px;
margin: 8px 8px 0 0;
padding: 0 12px 0 12px;
float: left;
box-sizing: border-box;
max-width: 100%;
position: relative; }
[dir=rtl] .md-chips md-chip {
margin: 8px 0 0 8px; }
[dir=rtl] .md-chips md-chip {
float: right; }
.md-chips md-chip .md-chip-content {
display: block;
float: left;
white-space: nowrap;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis; }
[dir=rtl] .md-chips md-chip .md-chip-content {
float: right; }
.md-chips md-chip .md-chip-content:focus {
outline: none; }
.md-chips md-chip.<API key> {
-webkit-user-select: none;
/* webkit (safari, chrome) browsers */
-moz-user-select: none;
/* mozilla browsers */
-khtml-user-select: none;
/* webkit (konqueror) browsers */
-ms-user-select: none;
/* IE10+ */ }
.md-chips md-chip .<API key> {
position: absolute;
right: 0;
line-height: 22px; }
[dir=rtl] .md-chips md-chip .<API key> {
right: auto;
left: 0; }
.md-chips md-chip .md-chip-remove {
text-align: center;
width: 32px;
height: 32px;
min-width: 0;
padding: 0;
background: transparent;
border: none;
box-shadow: none;
margin: 0;
position: relative; }
.md-chips md-chip .md-chip-remove md-icon {
height: 18px;
width: 18px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate3d(-50%, -50%, 0);
transform: translate3d(-50%, -50%, 0); }
.md-chips .<API key> {
display: block;
line-height: 32px;
margin: 8px 8px 0 0;
padding: 0;
float: left; }
[dir=rtl] .md-chips .<API key> {
margin: 8px 0 0 8px; }
[dir=rtl] .md-chips .<API key> {
float: right; }
.md-chips .<API key> input:not([type]), .md-chips .<API key> input[type="email"], .md-chips .<API key> input[type="number"], .md-chips .<API key> input[type="tel"], .md-chips .<API key> input[type="url"], .md-chips .<API key> input[type="text"] {
border: 0;
height: 32px;
line-height: 32px;
padding: 0; }
.md-chips .<API key> input:not([type]):focus, .md-chips .<API key> input[type="email"]:focus, .md-chips .<API key> input[type="number"]:focus, .md-chips .<API key> input[type="tel"]:focus, .md-chips .<API key> input[type="url"]:focus, .md-chips .<API key> input[type="text"]:focus {
outline: none; }
.md-chips .<API key> md-autocomplete, .md-chips .<API key> <API key> {
background: transparent;
height: 32px; }
.md-chips .<API key> md-autocomplete <API key> {
box-shadow: none; }
.md-chips .<API key> md-autocomplete input {
position: relative; }
.md-chips .<API key> input {
border: 0;
height: 32px;
line-height: 32px;
padding: 0; }
.md-chips .<API key> input:focus {
outline: none; }
.md-chips .<API key> md-autocomplete, .md-chips .<API key> <API key> {
height: 32px; }
.md-chips .<API key> md-autocomplete {
box-shadow: none; }
.md-chips .<API key> md-autocomplete input {
position: relative; }
.md-chips .<API key>:not(:first-child) {
margin: 8px 8px 0 0; }
[dir=rtl] .md-chips .<API key>:not(:first-child) {
margin: 8px 0 0 8px; }
.md-chips .<API key> input {
background: transparent;
border-width: 0; }
.md-chips md-autocomplete button {
display: none; }
@media screen and (-ms-high-contrast: active) {
.<API key>,
md-chip {
border: 1px solid #fff; }
.<API key> md-autocomplete {
border: none; } } |
package com.dpforge.tellon.core;
import com.dpforge.tellon.core.parser.AnnotatedBlock;
import com.dpforge.tellon.core.parser.ParsedSourceCode;
import com.dpforge.tellon.core.parser.SourceCode;
import com.dpforge.tellon.core.parser.SourceCodeParser;
import com.dpforge.tellon.core.parser.resolver.AsIsWatcherResolver;
import com.dpforge.tellon.core.parser.resolver.WatcherResolver;
import java.util.*;
public class ChangesBuilder {
private final SourceCodeParser parser;
public ChangesBuilder() {
this(new AsIsWatcherResolver());
}
public ChangesBuilder(WatcherResolver watcherResolver) {
if (watcherResolver == null) {
throw new <API key>("Watcher resolver cannot be null");
}
parser = new SourceCodeParser(watcherResolver);
}
public Changes build(SourceCode oldSrc, SourceCode newSrc) {
return buildChanges(parser.parse(oldSrc), parser.parse(newSrc));
}
public Changes buildInserted(SourceCode src) {
final ParsedSourceCode code = parser.parse(src);
final Changes changes = new Changes();
for (AnnotatedBlock block : code.getAnnotatedBlocks()) {
changes.addInserted(block);
}
return changes;
}
public Changes buildDeleted(SourceCode src) {
final ParsedSourceCode code = parser.parse(src);
final Changes changes = new Changes();
for (AnnotatedBlock block : code.getAnnotatedBlocks()) {
changes.addDeleted(block);
}
return changes;
}
private static Changes buildChanges(ParsedSourceCode oldCode, ParsedSourceCode newCode) {
final Changes changes = new Changes();
final Map<String, AnnotatedBlock> oldBlocks = new HashMap<>();
for (AnnotatedBlock block : oldCode.getAnnotatedBlocks()) {
oldBlocks.put(block.getName(), block);
}
for (AnnotatedBlock newBlock : newCode.getAnnotatedBlocks()) {
final AnnotatedBlock oldBlock = oldBlocks.get(newBlock.getName());
if (oldBlock != null && oldBlock.getType() == newBlock.getType()) {
if (!bodyEquals(oldBlock, newBlock)) {
changes.addChanged(oldBlock, newBlock);
}
oldBlocks.remove(newBlock.getName());
} else {
changes.addInserted(newBlock);
}
}
for (AnnotatedBlock oldBlock : oldBlocks.values()) {
changes.addDeleted(oldBlock);
}
return changes;
}
private static boolean bodyEquals(final AnnotatedBlock oldBlock, final AnnotatedBlock newBlock) {
final List<String> oldRaw = oldBlock.getSourceCode().asRaw();
final List<String> newRaw = newBlock.getSourceCode().asRaw();
return oldRaw.equals(newRaw);
}
} |
# <API key>
> info
>
> vue webpack skeleton
skeleton[App Skeleton ](https://lavas.baidu.com/guide/vue/doc/vue/advanced/skeleton)
github [https:
[ PWA ](https://huangxuan.me/2017/07/12/<API key>/#-vue-) skeleton DOM html style JS
html
1. skeleton
2. html skeleton
skeleton html
vue [](https://ssr.vuejs.org/zh/) webpack DOM
webpack entry skeleton
js
{
target: 'node',
devtool: false,
entry: resolve('./src/entry-skeleton.js'),
output: Object.assign({}, baseWebpackConfig.output, {
libraryTarget: 'commonjs2'
}),
externals: nodeExternals({
whitelist: /\.css$/
}),
plugins: []
}
> info
>
> webpack [](https:
webpack [memory-fs](https://github.com/webpack/memory-fs)I/O bundle `<API key>` renderer Node.js
js
const <API key> = require('vue-server-renderer').<API key>;
let bundle = mfs.readFileSync(outputPath, 'utf-8');
// renderer
let renderer = <API key>(bundle);
// html
renderer.renderToString({}, (err, skeletonHtml) => {
if (err) {
reject(err);
}
else {
resolve({skeletonHtml, skeletonCss});
}
});
JS [ ExtractTextPlugin](https://github.com/webpack-contrib/<API key>)
js
// <API key>/src/ssr.js
// ExtractTextPlugin
serverWebpackConfig.plugins.push(new ExtractTextPlugin({
filename: outputCssBasename
}));
[html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin#events)`<API key>`
DOM `</head>` DOM `<div id="app">`
html-webpack-plugin[Lavas MPA ](https:
js
// <API key>/src/index.js
// chunks
let usedChunks = htmlPluginData.plugin.options.chunks;
let entryKey;
// chunks
if (Array.isArray(usedChunks)) {
entryKey = Object.keys(skeletonEntries);
entryKey = entryKey.filter(v => usedChunks.indexOf(v) > -1)[0];
}
// webpack
webpackConfig.entry = skeletonEntries[entryKey];
webpackConfig.output.filename = `skeleton-${entryKey}.js`;
ssr(webpackConfig).then(({skeletonHtml, skeletonCss}) => {});
skeleton JS
skeleton skeleton
[ loader](https://github.com/lavas-project/<API key>/blob/master/src/loader.js)
skeleton skeleton
js
// router.js
// skeleton
import Skeleton from '@/pages/Skeleton.vue'
// routes
routes: [
{
path: '/skeleton',
name: 'skeleton',
component: Skeleton
}
]
loader skeleton [](https://github.com/lavas-project/<API key>/blob/master/src/loader.js#L27-L39)
> info
>
> [](https:
loader
<API key>
- webpackConfig ** skeleton webpack
- insertAfter ** DOM `'<div id="app">'`
<API key>.loader
1. [ webpack](https://doc.webpack-china.org/configuration/module/#rule)skeleton `resource/include/test` loader
2. `options` loader
- entry **
- importTemplate ** skeleton `'import [nameCap] from \'@/pages/[nameCap].vue\';'`
- routePathTemplate **`'/skeleton-[name]'`
- insertAfter **`'routes: ['`
`importTemplate``routePathTemplate`
- `[name]` `entry`
- `[nameCap]` `entry`
`router.js``'import Page1 from \'@/pages/Page1.vue\';'``'import Page2 from \'@/pages/Page2.vue\';'`
`/skeleton-page1``/skeleton-page2`
js
{
resource: 'router.js',
options: {
entry: ['page1', 'page2'],
importTemplate: 'import [nameCap] from \'@/pages/[nameCap].vue\';',
routePathTemplate: '/skeleton-[name]'
}
}
[ github](https://github.com/lavas-project/<API key>
[ ISSUE](https://github.com/lavas-project/<API key>/issues)
[](https://github.com/lavas-project/<API key>/tree/master/examples) |
// Support code for writing backtracking recursive-descent parsers
#include <string>
#include <deque>
#include <vector>
#include <map>
#include <queue>
#include <wibble/test.h>
#include <wibble/regexp.h>
#ifndef WIBBLE_PARSE_H
#define WIBBLE_PARSE_H
namespace wibble {
struct Position {
std::string source;
int line;
int column;
Position() : source("-"), line(1), column(1) {}
bool operator==( const Position &o ) const {
return o.source == source && o.line == line && o.column == column;
}
};
template< typename _Id >
struct Token {
typedef _Id Id;
Id id;
std::string data;
Position position;
bool _valid;
bool valid() { return _valid; }
Token( Id _id, char c ) : id( _id ), _valid( true ) {
data.push_back( c );
}
Token( Id _id, std::string d ) : id( _id ), data( d ), _valid( true ) {}
Token() : id( Id( 0 ) ), _valid( false ) {}
bool operator==( const Token &o ) const {
return o._valid == _valid && o.id == id && o.data == data && o.position == position;
}
};
template< typename X, typename Y >
inline std::ostream &operator<<( std::ostream &o, const std::pair< X, Y > &x ) {
return o << "(" << x.first << ", " << x.second << ")";
}
/*
* This is a SLOW lexer (at least compared to systems like lex/flex, which
* build a finite-state machine to make decisions per input character. We could
* do that in theory, but it would still be slow, since we would be in effect
* interpreting the FSM anyway, while (f)lex uses an optimising compiler like
* gcc. So while this is friendly and flexible, it won't give you a fast
* scanner.
*/
template< typename Token, typename Stream >
struct Lexer {
Stream &stream;
typedef std::deque< char > Window;
Window _window;
Position current;
Token _match;
void shift() {
assert( !stream.eof() );
std::string r = stream.remove();
std::copy( r.begin(), r.end(), std::back_inserter( _window ) );
}
bool eof() {
return _window.empty() && stream.eof();
}
std::string window( unsigned n ) {
bool valid = ensure_window( n );
assert( valid );
static_cast< void >( valid );
std::deque< char >::iterator b = _window.begin(), e = b;
e += n;
return std::string( b, e );
}
bool ensure_window( unsigned n ) {
while ( _window.size() < n && !stream.eof() )
shift();
return _window.size() >= n;
}
void consume( int n ) {
for( int i = 0; i < n; ++i ) {
if ( _window[i] == '\n' ) {
current.line ++;
current.column = 1;
} else
current.column ++;
}
std::deque< char >::iterator b = _window.begin(), e = b;
e += n;
_window.erase( b, e );
}
void consume( const std::string &s ) {
consume( s.length() );
}
void consume( const Token &t ) {
// std::cerr << "consuming " << t << std::endl;
consume( t.data );
}
void keep( typename Token::Id id, const std::string &data ) {
Token t( id, data );
t.position = current;
if ( t.data.length() > _match.data.length() )
_match = t;
}
template< typename I >
bool match( I begin, I end ) {
if ( !ensure_window( end - begin ) )
return false;
return std::equal( begin, end, _window.begin() );
}
void match( const std::string &data, typename Token::Id id ) {
if ( match( data.begin(), data.end() ) )
return keep( id, data );
}
void match( Regexp &r, typename Token::Id id ) {
unsigned n = 1, max = 0;
while ( r.match( window( n ) ) ) {
if ( max && max == r.matchLength( 0 ) )
return keep( id, window( max ) );
max = r.matchLength( 0 );
++ n;
}
}
void match( int (*first)(int), int (*rest)(int), typename Token::Id id )
{
unsigned n = 1;
if ( !ensure_window( 1 ) )
return;
if ( !first( _window[0] ) )
return;
while ( true ) {
++ n;
if ( ensure_window( n ) && rest( _window[ n - 1 ] ) )
continue;
return keep( id, window( n - 1 ) );
}
}
void match( const std::string &from, const std::string &to, typename Token::Id id ) {
if ( !match( from.begin(), from.end() ) )
return;
Window::iterator where = _window.begin();
int n = from.length();
where += n;
while ( true ) {
if ( !ensure_window( n + to.length() ) )
return;
if ( std::equal( to.begin(), to.end(), where ) )
return keep( id, window( n + to.length() ) );
++ where;
++ n;
}
}
void skipWhile( int (*pred)(int) ) {
while ( !eof() && pred( window( 1 )[ 0 ] ) )
consume( 1 );
}
void skipWhitespace() { skipWhile( isspace ); }
Token decide() {
Token t;
std::swap( t, _match );
consume( t );
return t;
}
Lexer( Stream &s ) : stream( s ) {}
};
template< typename Token, typename Stream >
struct ParseContext
{
Stream *_stream;
Stream &stream() { assert( _stream ); return *_stream; }
std::deque< Token > window;
int window_pos;
int position;
std::string name;
typedef ParseContext< Token, Stream > This;
std::vector< This > children;
struct Fail {
enum Type { Syntax, Semantic };
int position;
const char *expected;
Type type;
bool operator<( const Fail &other ) const {
return position > other.position;
}
Fail( const char *err, int pos, Type t = Syntax) {
expected = err;
position = pos;
type = t;
}
~Fail() throw () {}
};
std::priority_queue< Fail > failures;
void clearErrors() {
failures = std::priority_queue< Fail >();
}
void error( std::ostream &o, std::string prefix, const Fail &fail ) {
Token t = window[ fail.position ];
switch ( fail.type ) {
case Fail::Syntax:
o << prefix
<< "expected " << fail.expected
<< " at line " << t.position.line
<< ", column " << t.position.column
<< ", but seen " << Token::tokenName[ static_cast< int >( t.id ) ] << " '" << t.data << "'"
<< std::endl;
return;
case Fail::Semantic:
o << prefix
<< fail.expected
<< " at line " << t.position.line
<< ", column " << t.position.column
<< std::endl;
return;
}
}
void errors( std::ostream &o ) {
for ( This & pc : children )
pc.errors( o );
if ( failures.empty() )
return;
std::string prefix;
switch ( failures.top().type ) {
case Fail::Syntax:
o << "parse";
break;
case Fail::Semantic:
o << "semantic";
break;
}
o << " error in context " << name << ": ";
if ( failures.size() > 1 ) {
o << failures.size() << " rightmost alternatives:" << std::endl;
prefix = " ";
}
while ( !failures.empty() ) {
error( o, prefix, failures.top() );
failures.pop();
}
}
Token remove() {
if ( int( window.size() ) <= window_pos ) {
Token t;
do {
t = stream().remove();
} while ( t.id == Token::Comment ); // XXX
window.push_back( t );
}
++ window_pos;
++ position;
return window[ window_pos - 1 ];
}
void rewind( int n ) {
assert( n >= 0 );
assert( n <= window_pos );
window_pos -= n;
position -= n;
}
This & createChild( Stream &s, std::string name ) {
children.push_back( This( s, name ) );
return children.back();
}
ParseContext( Stream &s, std::string name )
: _stream( &s ), window_pos( 0 ), position( 0 ), name( name )
{}
};
template< typename Token, typename Stream >
struct Parser {
typedef typename Token::Id TokenId;
typedef ParseContext< Token, Stream > Context;
Context *ctx;
typedef typename Context::Fail Fail;
typedef typename Fail::Type FailType;
int _position;
bool valid() const {
return ctx;
}
Context &context() {
assert( ctx );
return *ctx;
}
int position() {
return context().position;
}
void rewind( int i ) {
context().rewind( i );
_position = context().position;
}
void fail( const char *what, FailType type = FailType::Syntax ) __attribute__((noreturn))
{
Fail f( what, _position, type );
context().failures.push( f );
while ( context().failures.top().position < _position )
context().failures.pop();
throw f;
}
void semicolon() {
Token t = eat();
if ( t.id == Token::Punctuation && t.data == ";" )
return;
rewind( 1 );
fail( "semicolon" );
}
void colon() {
Token t = eat();
if ( t.id == Token::Punctuation && t.data == ":" )
return;
rewind( 1 );
fail( "colon" );
}
Token eat( TokenId id ) {
Token t = eat( false );
if ( t.id == id )
return t;
rewind( 1 );
fail( Token::tokenName[ static_cast< int >( id ) ].c_str() );
}
#if __cplusplus >= 201103L
template< typename F >
void either( void (F::*f)() ) {
(static_cast< F* >( this )->*f)();
}
template< typename F, typename... Args >
void either( F f, Args... args ) {
if ( maybe( f ) )
return;
either( args... );
}
#else
template< typename F, typename G >
void either( F f, void (G::*g)() ) {
if ( maybe( f ) )
return;
(static_cast< G* >( this )->*g)();
}
#endif
#if __cplusplus >= 201103L
template< typename F, typename... Args >
bool maybe( F f, Args... args ) {
if ( maybe( f ) )
return true;
return maybe( args... );
}
#else
template< typename F, typename G >
bool maybe( F f, G g ) {
if ( maybe( f ) )
return true;
return maybe( g );
}
template< typename F, typename G, typename H >
bool maybe( F f, G g, H h ) {
if ( maybe( f ) )
return true;
if ( maybe( g ) )
return true;
return maybe( h );
}
#endif
template< typename F >
bool maybe( void (F::*f)() ) {
int fallback = position();
try {
(static_cast< F* >( this )->*f)();
return true;
} catch ( Fail fail ) {
rewind( position() - fallback );
return false;
}
}
#if __cplusplus >= 201103L
template< typename F >
auto maybe( F f ) -> decltype( f(), true ) {
int fallback = position();
try {
f(); return true;
} catch ( Fail fail ) {
rewind( position() - fallback );
return false;
}
}
#endif
bool maybe( TokenId id ) {
int fallback = position();
try {
eat( id );
return true;
} catch (Fail) {
rewind( position() - fallback );
return false;
}
}
template< typename T, typename I >
void many( I i ) {
int fallback = 0;
try {
while ( true ) {
fallback = position();
*i++ = T( context() );
}
} catch (Fail) {
rewind( position() - fallback );
}
}
#if __cplusplus >= 201103L
template< typename F >
bool arbitrary( F f ) {
return maybe( f );
}
// NB. Accepts any ordering of sub-parsers, some possibly more than
// once. It is slightly bogus and won't catch all errors in most reasonable
// languages. Avoid.
template< typename F, typename... Args >
bool arbitrary( F f, Args... args ) {
bool retval = arbitrary( args... );
retval |= maybe( f );
retval |= arbitrary( args... );
return retval;
}
#endif
template< typename T, typename I >
void list( I i, TokenId sep ) {
do {
*i++ = T( context() );
} while ( next( sep ) );
}
template< typename T, typename I, typename F >
void list( I i, void (F::*sep)() ) {
int fallback = position();
try {
while ( true ) {
*i++ = T( context() );
fallback = position();
(static_cast< F* >( this )->*sep)();
}
} catch(Fail) {
rewind( position() - fallback );
}
}
template< typename T, typename I >
void list( I i, TokenId first, TokenId sep, TokenId last ) {
eat( first );
list< T >( i, sep );
eat( last );
}
Token eat( bool _fail = true ) {
Token t = context().remove();
_position = context().position;
if ( _fail && !t.valid() ) {
rewind( 1 );
fail( "valid token" );
}
return t;
}
bool next( TokenId id ) {
Token t = eat( false );
if ( t.id == id )
return true;
rewind( 1 );
return false;
}
Parser( Context &c ) : ctx( &c ) {}
Parser() : ctx( 0 ) {}
};
}
#endif |
package tsi1_test
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"testing"
"github.com/influxdata/influxdb/models"
"github.com/influxdata/influxdb/tsdb"
"github.com/influxdata/influxdb/tsdb/index/tsi1"
)
// Bloom filter settings used in tests.
const M, K = 4096, 6
// Ensure index can iterate over all measurement names.
func <API key>(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, 1)
defer idx.Close()
// Add series to index.
if err := idx.<API key>([]Series{
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "east"})},
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "west"})},
{Name: []byte("mem"), Tags: models.NewTags(map[string]string{"region": "east"})},
}); err != nil {
t.Fatal(err)
}
// Verify measurements are returned.
idx.Run(t, func(t *testing.T) {
var names []string
if err := idx.<API key>(func(name []byte) error {
names = append(names, string(name))
return nil
}); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(names, []string{"cpu", "mem"}) {
t.Fatalf("unexpected names: %#v", names)
}
})
// Add more series.
if err := idx.<API key>([]Series{
{Name: []byte("disk")},
{Name: []byte("mem")},
}); err != nil {
t.Fatal(err)
}
// Verify new measurements.
idx.Run(t, func(t *testing.T) {
var names []string
if err := idx.<API key>(func(name []byte) error {
names = append(names, string(name))
return nil
}); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(names, []string{"cpu", "disk", "mem"}) {
t.Fatalf("unexpected names: %#v", names)
}
})
}
// Ensure index can return whether a measurement exists.
func <API key>(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, 1)
defer idx.Close()
// Add series to index.
if err := idx.<API key>([]Series{
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "east"})},
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "west"})},
}); err != nil {
t.Fatal(err)
}
// Verify measurement exists.
idx.Run(t, func(t *testing.T) {
if v, err := idx.MeasurementExists([]byte("cpu")); err != nil {
t.Fatal(err)
} else if !v {
t.Fatal("expected measurement to exist")
}
})
// Delete one series.
if err := idx.DropSeries(models.MakeKey([]byte("cpu"), models.NewTags(map[string]string{"region": "east"})), 0); err != nil {
t.Fatal(err)
}
// Verify measurement still exists.
idx.Run(t, func(t *testing.T) {
if v, err := idx.MeasurementExists([]byte("cpu")); err != nil {
t.Fatal(err)
} else if !v {
t.Fatal("expected measurement to still exist")
}
})
// Delete second series.
if err := idx.DropSeries(models.MakeKey([]byte("cpu"), models.NewTags(map[string]string{"region": "west"})), 0); err != nil {
t.Fatal(err)
}
// Verify measurement is now deleted.
idx.Run(t, func(t *testing.T) {
if v, err := idx.MeasurementExists([]byte("cpu")); err != nil {
t.Fatal(err)
} else if v {
t.Fatal("expected measurement to be deleted")
}
})
}
// Ensure index can return a list of matching measurements.
func <API key>(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, 1)
defer idx.Close()
// Add series to index.
if err := idx.<API key>([]Series{
{Name: []byte("cpu")},
{Name: []byte("disk")},
{Name: []byte("mem")},
}); err != nil {
t.Fatal(err)
}
// Retrieve measurements by regex.
idx.Run(t, func(t *testing.T) {
names, err := idx.<API key>(regexp.MustCompile(`cpu|mem`))
if err != nil {
t.Fatal(err)
} else if !reflect.DeepEqual(names, [][]byte{[]byte("cpu"), []byte("mem")}) {
t.Fatalf("unexpected names: %v", names)
}
})
}
// Ensure index can delete a measurement and all related keys, values, & series.
func <API key>(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, 1)
defer idx.Close()
// Add series to index.
if err := idx.<API key>([]Series{
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "east"})},
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "west"})},
{Name: []byte("disk"), Tags: models.NewTags(map[string]string{"region": "north"})},
{Name: []byte("mem"), Tags: models.NewTags(map[string]string{"region": "west", "country": "us"})},
}); err != nil {
t.Fatal(err)
}
// Drop measurement.
if err := idx.DropMeasurement([]byte("cpu")); err != nil {
t.Fatal(err)
}
// Verify data is gone in each stage.
idx.Run(t, func(t *testing.T) {
// Verify measurement is gone.
if v, err := idx.MeasurementExists([]byte("cpu")); err != nil {
t.Fatal(err)
} else if v {
t.Fatal("expected no measurement")
}
// Obtain file set to perform lower level checks.
fs, err := idx.PartitionAt(0).RetainFileSet()
if err != nil {
t.Fatal(err)
}
defer fs.Release()
// Verify tags & values are gone.
if e := fs.TagKeyIterator([]byte("cpu")).Next(); e != nil && !e.Deleted() {
t.Fatal("expected deleted tag key")
}
if itr := fs.TagValueIterator([]byte("cpu"), []byte("region")); itr != nil {
t.Fatal("expected nil tag value iterator")
}
})
}
func TestIndex_Open(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
// Opening a fresh index should set the MANIFEST version to current version.
idx := NewIndex(sfile.SeriesFile, tsi1.DefaultPartitionN)
t.Run("open new index", func(t *testing.T) {
if err := idx.Open(); err != nil {
t.Fatal(err)
}
// Check version set appropriately.
for i := 0; uint64(i) < tsi1.DefaultPartitionN; i++ {
partition := idx.PartitionAt(i)
if got, exp := partition.Manifest().Version, 1; got != exp {
t.Fatalf("got index version %d, expected %d", got, exp)
}
}
})
// Reopening an open index should return an error.
t.Run("reopen open index", func(t *testing.T) {
err := idx.Open()
if err == nil {
idx.Close()
t.Fatal("didn't get an error on reopen, but expected one")
}
idx.Close()
})
// Opening an incompatible index should return an error.
<API key> := []int{-1, 0, 2}
for _, v := range <API key> {
t.Run(fmt.Sprintf("incompatible index version: %d", v), func(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx = NewIndex(sfile.SeriesFile, tsi1.DefaultPartitionN)
// Manually create a MANIFEST file for an incompatible index version.
// under one of the partitions.
partitionPath := filepath.Join(idx.Path(), "2")
os.MkdirAll(partitionPath, 0777)
mpath := filepath.Join(partitionPath, tsi1.ManifestFileName)
m := tsi1.NewManifest(mpath)
m.Levels = nil
m.Version = v // Set example MANIFEST version.
if _, err := m.Write(); err != nil {
t.Fatal(err)
}
// Log the MANIFEST file.
data, err := ioutil.ReadFile(mpath)
if err != nil {
panic(err)
}
t.Logf("Incompatible MANIFEST: %s", data)
// Opening this index should return an error because the MANIFEST has an
// incompatible version.
err = idx.Open()
if err != tsi1.<API key> {
idx.Close()
t.Fatalf("got error %v, expected %v", err, tsi1.<API key>)
}
})
}
}
func TestIndex_Manifest(t *testing.T) {
t.Run("current MANIFEST", func(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, tsi1.DefaultPartitionN)
// Check version set appropriately.
for i := 0; uint64(i) < tsi1.DefaultPartitionN; i++ {
partition := idx.PartitionAt(i)
if got, exp := partition.Manifest().Version, tsi1.Version; got != exp {
t.Fatalf("got MANIFEST version %d, expected %d", got, exp)
}
}
})
}
func <API key>(t *testing.T) {
sfile := MustOpenSeriesFile()
defer sfile.Close()
idx := MustOpenIndex(sfile.SeriesFile, tsi1.DefaultPartitionN)
defer idx.Close()
// Add series to index.
if err := idx.<API key>([]Series{
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "east"})},
{Name: []byte("cpu"), Tags: models.NewTags(map[string]string{"region": "west"})},
{Name: []byte("disk"), Tags: models.NewTags(map[string]string{"region": "north"})},
{Name: []byte("mem"), Tags: models.NewTags(map[string]string{"region": "west", "country": "us"})},
}); err != nil {
t.Fatal(err)
}
// Verify on disk size is the same in each stage.
// Each series stores flag(1) + series(uvarint(2)) + len(name)(1) + len(key)(1) + len(value)(1) + checksum(4).
expSize := int64(4 * 10)
// Each MANIFEST file is 419 bytes and there are tsi1.DefaultPartitionN of them
expSize += int64(tsi1.DefaultPartitionN * 419)
idx.Run(t, func(t *testing.T) {
if got, exp := idx.DiskSizeBytes(), expSize; got != exp {
t.Fatalf("got %d bytes, expected %d", got, exp)
}
})
}
// Index is a test wrapper for tsi1.Index.
type Index struct {
*tsi1.Index
}
// NewIndex returns a new instance of Index at a temporary path.
func NewIndex(sfile *tsdb.SeriesFile, partitionN uint64) *Index {
idx := &Index{Index: tsi1.NewIndex(sfile, tsi1.WithPath(MustTempDir()))}
idx.PartitionN = partitionN
return idx
}
// MustOpenIndex returns a new, open index. Panic on error.
func MustOpenIndex(sfile *tsdb.SeriesFile, partitionN uint64) *Index {
idx := NewIndex(sfile, partitionN)
if err := idx.Open(); err != nil {
panic(err)
}
return idx
}
// Close closes and removes the index directory.
func (idx *Index) Close() error {
defer os.RemoveAll(idx.Path())
return idx.Index.Close()
}
// Reopen closes and opens the index.
func (idx *Index) Reopen() error {
if err := idx.Index.Close(); err != nil {
return err
}
sfile := idx.SeriesFile()
path, partitionN := idx.Path(), idx.PartitionN
idx.Index = tsi1.NewIndex(sfile, tsi1.WithPath(path))
idx.PartitionN = partitionN
if err := idx.Open(); err != nil {
return err
}
return nil
}
// Run executes a subtest for each of several different states:
// - Immediately
// - After reopen
// - After compaction
// - After reopen again
// The index should always respond in the same fashion regardless of
// how data is stored. This helper allows the index to be easily tested
// in all major states.
func (idx *Index) Run(t *testing.T, fn func(t *testing.T)) {
// Invoke immediately.
t.Run("state=initial", fn)
// Reopen and invoke again.
if err := idx.Reopen(); err != nil {
t.Fatalf("reopen error: %s", err)
}
t.Run("state=reopen", fn)
// TODO: Request a compaction.
// if err := idx.Compact(); err != nil {
// t.Fatalf("compact error: %s", err)
// t.Run("state=post-compaction", fn)
// Reopen and invoke again.
if err := idx.Reopen(); err != nil {
t.Fatalf("post-compaction reopen error: %s", err)
}
t.Run("state=<API key>", fn)
}
// <API key> creates multiple series at a time.
func (idx *Index) <API key>(a []Series) error {
for i, s := range a {
if err := idx.<API key>(nil, [][]byte{s.Name}, []models.Tags{s.Tags}); err != nil {
return fmt.Errorf("i=%d, name=%s, tags=%v, err=%s", i, s.Name, s.Tags, err)
}
}
return nil
}
func BytesToStrings(a [][]byte) []string {
s := make([]string, 0, len(a))
for _, v := range a {
s = append(s, string(v))
}
return s
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_06) on Sat Jun 03 13:46:23 EST 2006 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Class org.apache.bcel.generic.ArrayInstruction (jakarta-bcel 5.2 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.apache.bcel.generic.ArrayInstruction (jakarta-bcel 5.2 API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/bcel/generic//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="ArrayInstruction.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.bcel.generic.ArrayInstruction</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.bcel.generic"><B>org.apache.bcel.generic</B></A></TD>
<TD>
This package contains the "generic" part of the
<a href="http://jakarta.apache.org/bcel/">Byte Code Engineering
Library</a>, i.e., classes to dynamically modify class objects and
byte code instructions. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.bcel.generic"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A> in <A HREF="../../../../../org/apache/bcel/generic/package-summary.html">org.apache.bcel.generic</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A> in <A HREF="../../../../../org/apache/bcel/generic/package-summary.html">org.apache.bcel.generic</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/AALOAD.html" title="class in org.apache.bcel.generic">AALOAD</A></B></CODE>
<BR>
AALOAD - Load reference from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/AASTORE.html" title="class in org.apache.bcel.generic">AASTORE</A></B></CODE>
<BR>
AASTORE - Store into reference array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/BALOAD.html" title="class in org.apache.bcel.generic">BALOAD</A></B></CODE>
<BR>
BALOAD - Load byte or boolean from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/BASTORE.html" title="class in org.apache.bcel.generic">BASTORE</A></B></CODE>
<BR>
BASTORE - Store into byte or boolean array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/CALOAD.html" title="class in org.apache.bcel.generic">CALOAD</A></B></CODE>
<BR>
CALOAD - Load char from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/CASTORE.html" title="class in org.apache.bcel.generic">CASTORE</A></B></CODE>
<BR>
CASTORE - Store into char array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/DALOAD.html" title="class in org.apache.bcel.generic">DALOAD</A></B></CODE>
<BR>
DALOAD - Load double from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/DASTORE.html" title="class in org.apache.bcel.generic">DASTORE</A></B></CODE>
<BR>
DASTORE - Store into double array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/FALOAD.html" title="class in org.apache.bcel.generic">FALOAD</A></B></CODE>
<BR>
FALOAD - Load float from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/FASTORE.html" title="class in org.apache.bcel.generic">FASTORE</A></B></CODE>
<BR>
FASTORE - Store into float array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/IALOAD.html" title="class in org.apache.bcel.generic">IALOAD</A></B></CODE>
<BR>
IALOAD - Load int from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/IASTORE.html" title="class in org.apache.bcel.generic">IASTORE</A></B></CODE>
<BR>
IASTORE - Store into int array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/LALOAD.html" title="class in org.apache.bcel.generic">LALOAD</A></B></CODE>
<BR>
LALOAD - Load long from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/LASTORE.html" title="class in org.apache.bcel.generic">LASTORE</A></B></CODE>
<BR>
LASTORE - Store into long array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/SALOAD.html" title="class in org.apache.bcel.generic">SALOAD</A></B></CODE>
<BR>
SALOAD - Load short from array</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/apache/bcel/generic/SASTORE.html" title="class in org.apache.bcel.generic">SASTORE</A></B></CODE>
<BR>
SASTORE - Store into short array</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../org/apache/bcel/generic/package-summary.html">org.apache.bcel.generic</A> declared as <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#AALOAD">AALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#AASTORE">AASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#BALOAD">BALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#BASTORE">BASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#CALOAD">CALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#CASTORE">CASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#DALOAD">DALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#DASTORE">DASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#FALOAD">FALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#FASTORE">FASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#IALOAD">IALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#IASTORE">IASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#LALOAD">LALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#LASTORE">LASTORE</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#SALOAD">SALOAD</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B><API key>.</B><B><A HREF="../../../../../org/apache/bcel/generic/<API key>.html#SASTORE">SASTORE</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/bcel/generic/package-summary.html">org.apache.bcel.generic</A> that return <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B>InstructionFactory.</B><B><A HREF="../../../../../org/apache/bcel/generic/InstructionFactory.html#createArrayLoad(org.apache.bcel.generic.Type)">createArrayLoad</A></B>(<A HREF="../../../../../org/apache/bcel/generic/Type.html" title="class in org.apache.bcel.generic">Type</A> type)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></CODE></FONT></TD>
<TD><CODE><B>InstructionFactory.</B><B><A HREF="../../../../../org/apache/bcel/generic/InstructionFactory.html#createArrayStore(org.apache.bcel.generic.Type)">createArrayStore</A></B>(<A HREF="../../../../../org/apache/bcel/generic/Type.html" title="class in org.apache.bcel.generic">Type</A> type)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/bcel/generic/package-summary.html">org.apache.bcel.generic</A> with parameters of type <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>Visitor.</B><B><A HREF="../../../../../org/apache/bcel/generic/Visitor.html#<API key>(org.apache.bcel.generic.ArrayInstruction)"><API key></A></B>(<A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A> obj)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>EmptyVisitor.</B><B><A HREF="../../../../../org/apache/bcel/generic/EmptyVisitor.html#<API key>(org.apache.bcel.generic.ArrayInstruction)"><API key></A></B>(<A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic">ArrayInstruction</A> obj)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/bcel/generic/ArrayInstruction.html" title="class in org.apache.bcel.generic"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/bcel/generic//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="ArrayInstruction.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright © 2002-2006 Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML> |
<?php
require('get-param.php');
require('enableCORS.php');
if (getParam('roomid')) {
$filename = getcwd().'/rooms/'.getParam('roomid').'.json';
if (file_exists($filename)) {
echo json_encode(array(
'isRoomExist' => true,
'roomid' => getParam('roomid')
));
} else {
echo json_encode(array(
'isRoomExist' => false,
'roomid' => getParam('roomid')
));
}
}
?> |
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
describe "Module#included" do
it "is invoked when self is included in another module or class" do
begin
m = Module.new do
def self.included(o)
$included_by = o
end
end
c = Class.new { include m }
$included_by.should == c
ensure
$included_by = nil
end
end
it "allows extending self with the object into which it is being included" do
m = Module.new do
def self.included(o)
o.extend(self)
end
def test
:passed
end
end
c = Class.new{ include(m) }
c.test.should == :passed
end
it "is private in its default implementation" do
Module.should <API key>(:included)
end
it "works with super using a singleton class" do
ModuleSpecs::<API key>::Bar.include ModuleSpecs::<API key>::Foo
ModuleSpecs::<API key>::Bar.included_called?.should == true
end
end |
A project for live-reload functionality for [Phoenix](http://github.com/phoenixframework/phoenix) during development.
## Usage
You can use `phoenix_live_reload` in your projects by adding it to your `mix.exs` dependencies:
elixir
def deps do
[{:phoenix_live_reload, "~> 1.0"}]
end
## Backends
This project uses [`fs`](https://github.com/synrc/fs) as a dependency to watch your filesystem whenever there is a change and it supports the following operating systems:
* Linux via [inotify](https://github.com/rvoicilas/inotify-tools/wiki) (installation required)
* Windows via [inotify-win](https://github.com/thekid/inotify-win) (no installation required)
* Mac OS X via fsevents (no installation required)
## Skipping remote CSS reload
All stylesheets are reloaded without a page refresh anytime a style is detected as having changed. In certain cases such as serving stylesheets from a remote host, you may wish to prevent unnecessary reload of these stylesheets during development. For this, you can include a `data-no-reload` attribute on the link tag, ie:
<link rel="stylesheet" href="http://example.com/style.css" data-no-reload>
[Same license as Phoenix](https: |
#include <assert.h>
#include <malloc.h>
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/utime.h>
#include <stdio.h>
#include "uv.h"
#include "internal.h"
#define UV_FS_ASYNC_QUEUED 0x0001
#define UV_FS_FREE_ARG0 0x0002
#define UV_FS_FREE_ARG1 0x0004
#define UV_FS_FREE_PTR 0x0008
#define UV_FS_CLEANEDUP 0x0010
#define UTF8_TO_UTF16(s, t) \
size = uv_utf8_to_utf16(s, NULL, 0) * sizeof(wchar_t); \
t = (wchar_t*)malloc(size); \
if (!t) { \
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); \
} \
if (!uv_utf8_to_utf16(s, t, size / sizeof(wchar_t))) { \
uv__set_sys_error(loop, GetLastError()); \
return -1; \
}
#define STRDUP_ARG(req, i) \
req->arg##i = (void*)strdup((const char*)req->arg##i); \
if (!req->arg
uv_fatal_error(ERROR_OUTOFMEMORY, "malloc"); \
} \
req->flags |= UV_FS_FREE_ARG
#define SET_ALLOCED_ARG(req, i) \
req->flags |= UV_FS_FREE_ARG
#define WRAP_REQ_ARGS1(req, a0) \
req->arg0 = (void*)a0;
#define WRAP_REQ_ARGS2(req, a0, a1) \
WRAP_REQ_ARGS1(req, a0) \
req->arg1 = (void*)a1;
#define WRAP_REQ_ARGS3(req, a0, a1, a2) \
WRAP_REQ_ARGS2(req, a0, a1) \
req->arg2 = (void*)a2;
#define WRAP_REQ_ARGS4(req, a0, a1, a2, a3) \
WRAP_REQ_ARGS3(req, a0, a1, a2) \
req->arg3 = (void*)a3;
#define QUEUE_FS_TP_JOB(loop, req) \
if (!QueueUserWorkItem(&uv_fs_thread_proc, \
req, \
<API key>)) { \
uv__set_sys_error((loop), GetLastError()); \
return -1; \
} \
req->flags |= UV_FS_ASYNC_QUEUED; \
uv_ref((loop));
#define <API key>(req) \
uv__set_error(req->loop, req->errorno, req->sys_errno_);
#define SET_REQ_RESULT(req, result_value) \
req->result = (result_value); \
if (req->result == -1) { \
req->sys_errno_ = _doserrno; \
req->errorno = <API key>(req->sys_errno_); \
}
#define SET_REQ_WIN32_ERROR(req, sys_errno) \
req->result = -1; \
req->sys_errno_ = (sys_errno); \
req->errorno = <API key>(req->sys_errno_);
#define SET_REQ_UV_ERROR(req, uv_errno, sys_errno) \
req->result = -1; \
req->sys_errno_ = (sys_errno); \
req->errorno = (uv_errno);
#define VERIFY_UV_FILE(file, req) \
if (file == -1) { \
req->result = -1; \
req->errorno = UV_EBADF; \
req->sys_errno_ = ERROR_SUCCESS; \
return; \
}
void uv_fs_init() {
_fmode = _O_BINARY;
}
static void <API key>(uv_loop_t* loop, uv_fs_t* req,
uv_fs_type fs_type, const char* path, const wchar_t* pathw, uv_fs_cb cb) {
uv_req_init(loop, (uv_req_t*) req);
req->type = UV_FS;
req->loop = loop;
req->flags = 0;
req->fs_type = fs_type;
req->cb = cb;
req->result = 0;
req->ptr = NULL;
req->path = path ? strdup(path) : NULL;
req->pathw = (wchar_t*)pathw;
req->errorno = 0;
req->sys_errno_ = 0;
memset(&req->overlapped, 0, sizeof(req->overlapped));
}
static void uv_fs_req_init_sync(uv_loop_t* loop, uv_fs_t* req,
uv_fs_type fs_type) {
uv_req_init(loop, (uv_req_t*) req);
req->type = UV_FS;
req->loop = loop;
req->flags = 0;
req->fs_type = fs_type;
req->result = 0;
req->ptr = NULL;
req->path = NULL;
req->pathw = NULL;
req->errorno = 0;
}
void fs__open(uv_fs_t* req, const wchar_t* path, int flags, int mode) {
DWORD access;
DWORD share;
DWORD disposition;
DWORD attributes;
HANDLE file;
int result, current_umask;
/* Obtain the active umask. umask() never fails and returns the previous */
/* umask. */
current_umask = umask(0);
umask(current_umask);
/* convert flags and mode to CreateFile parameters */
switch (flags & (_O_RDONLY | _O_WRONLY | _O_RDWR)) {
case _O_RDONLY:
access = FILE_GENERIC_READ;
break;
case _O_WRONLY:
access = FILE_GENERIC_WRITE;
break;
case _O_RDWR:
access = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
break;
default:
result = -1;
goto end;
}
if (flags & _O_APPEND) {
access &= ~FILE_WRITE_DATA;
access |= FILE_APPEND_DATA;
}
/*
* Here is where we deviate significantly from what CRT's _open()
* does. We indiscriminately use all the sharing modes, to match
* UNIX semantics. In particular, this ensures that the file can
* be deleted even whilst it's open, fixing issue #1449.
*/
share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
switch (flags & (_O_CREAT | _O_EXCL | _O_TRUNC)) {
case 0:
case _O_EXCL:
disposition = OPEN_EXISTING;
break;
case _O_CREAT:
disposition = OPEN_ALWAYS;
break;
case _O_CREAT | _O_EXCL:
case _O_CREAT | _O_TRUNC | _O_EXCL:
disposition = CREATE_NEW;
break;
case _O_TRUNC:
case _O_TRUNC | _O_EXCL:
disposition = TRUNCATE_EXISTING;
break;
case _O_CREAT | _O_TRUNC:
disposition = CREATE_ALWAYS;
break;
default:
result = -1;
goto end;
}
attributes = <API key>;
if (flags & _O_CREAT) {
if (!((mode & ~current_umask) & _S_IWRITE)) {
attributes |= <API key>;
}
}
if (flags & _O_TEMPORARY ) {
attributes |= <API key> | <API key>;
access |= DELETE;
}
if (flags & _O_SHORT_LIVED) {
attributes |= <API key>;
}
switch (flags & (_O_SEQUENTIAL | _O_RANDOM)) {
case 0:
break;
case _O_SEQUENTIAL:
attributes |= <API key>;
break;
case _O_RANDOM:
attributes |= <API key>;
break;
default:
result = -1;
goto end;
}
/* Figure out whether path is a file or a directory. */
if (GetFileAttributesW(path) & <API key>) {
attributes |= <API key>;
}
file = CreateFileW(path,
access,
share,
NULL,
disposition,
attributes,
NULL);
if (file == <API key>) {
DWORD error = GetLastError();
if (error == ERROR_FILE_EXISTS && (flags & _O_CREAT) &&
!(flags & _O_EXCL)) {
/* Special case: when ERROR_FILE_EXISTS happens and O_CREAT was */
/* specified, it means the path referred to a directory. */
SET_REQ_UV_ERROR(req, UV_EISDIR, error);
} else {
SET_REQ_WIN32_ERROR(req, GetLastError());
}
return;
}
result = _open_osfhandle((intptr_t)file, flags);
end:
SET_REQ_RESULT(req, result);
}
void fs__close(uv_fs_t* req, uv_file file) {
int result;
VERIFY_UV_FILE(file, req);
result = _close(file);
SET_REQ_RESULT(req, result);
}
void fs__read(uv_fs_t* req, uv_file file, void *buf, size_t length,
off_t offset) {
HANDLE handle;
OVERLAPPED overlapped, *overlapped_ptr;
LARGE_INTEGER offset_;
DWORD bytes;
DWORD error;
VERIFY_UV_FILE(file, req);
handle = (HANDLE) _get_osfhandle(file);
if (handle == <API key>) {
SET_REQ_RESULT(req, -1);
return;
}
if (length > INT_MAX) {
SET_REQ_WIN32_ERROR(req, <API key>);
return;
}
if (offset != -1) {
memset(&overlapped, 0, sizeof overlapped);
offset_.QuadPart = offset;
overlapped.Offset = offset_.LowPart;
overlapped.OffsetHigh = offset_.HighPart;
overlapped_ptr = &overlapped;
} else {
overlapped_ptr = NULL;
}
if (ReadFile(handle, buf, length, &bytes, overlapped_ptr)) {
SET_REQ_RESULT(req, bytes);
} else {
error = GetLastError();
if (error == ERROR_HANDLE_EOF) {
SET_REQ_RESULT(req, bytes);
} else {
SET_REQ_WIN32_ERROR(req, error);
}
}
}
void fs__write(uv_fs_t* req, uv_file file, void *buf, size_t length,
off_t offset) {
HANDLE handle;
OVERLAPPED overlapped, *overlapped_ptr;
LARGE_INTEGER offset_;
DWORD bytes;
VERIFY_UV_FILE(file, req);
handle = (HANDLE) _get_osfhandle(file);
if (handle == <API key>) {
SET_REQ_RESULT(req, -1);
return;
}
if (length > INT_MAX) {
SET_REQ_WIN32_ERROR(req, <API key>);
return;
}
if (offset != -1) {
memset(&overlapped, 0, sizeof overlapped);
offset_.QuadPart = offset;
overlapped.Offset = offset_.LowPart;
overlapped.OffsetHigh = offset_.HighPart;
overlapped_ptr = &overlapped;
} else {
overlapped_ptr = NULL;
}
if (WriteFile(handle, buf, length, &bytes, overlapped_ptr)) {
SET_REQ_RESULT(req, bytes);
} else {
SET_REQ_WIN32_ERROR(req, GetLastError());
}
}
void fs__unlink(uv_fs_t* req, const wchar_t* path) {
int result = _wunlink(path);
SET_REQ_RESULT(req, result);
}
void fs__mkdir(uv_fs_t* req, const wchar_t* path, int mode) {
int result = _wmkdir(path);
SET_REQ_RESULT(req, result);
}
void fs__rmdir(uv_fs_t* req, const wchar_t* path) {
int result = _wrmdir(path);
SET_REQ_RESULT(req, result);
}
void fs__readdir(uv_fs_t* req, const wchar_t* path, int flags) {
int result, size;
wchar_t* buf = NULL, *ptr, *name;
HANDLE dir;
WIN32_FIND_DATAW ent = {0};
size_t len = wcslen(path);
size_t buf_char_len = 4096;
wchar_t* path2;
/* Figure out whether path is a file or a directory. */
/* Convert result to UTF8. */
/* TODO: set st_dev and st_ino? */
/* something is seriously wrong */
/* Strip off the leading \??\ from the substitute name buffer.*/
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* TODO: add support for links. */
/* Convert to UTF16. */
/* Convert to UTF16. */
/* Convert to UTF16. */ |
package com.microsoft.azure.management.resources.v2019_05_01.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.resources.v2019_05_01.<API key>;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.resources.v2019_05_01.DeploymentOperation;
class <API key> extends WrapperImpl<<API key>> implements <API key> {
private final ResourcesManager manager;
<API key>(ResourcesManager manager) {
super(manager.inner().<API key>());
this.manager = manager;
}
public ResourcesManager manager() {
return this.manager;
}
private <API key> wrapModel(<API key> inner) {
return new <API key>(inner, manager());
}
@Override
public Observable<DeploymentOperation> <API key>(String deploymentName, String operationId) {
<API key> client = this.inner();
return client.<API key>(deploymentName, operationId)
.map(new Func1<<API key>, DeploymentOperation>() {
@Override
public DeploymentOperation call(<API key> inner) {
return new <API key>(inner, manager());
}
});
}
@Override
public Observable<DeploymentOperation> <API key>(final String deploymentName) {
<API key> client = this.inner();
return client.<API key>(deploymentName)
.flatMapIterable(new Func1<Page<<API key>>, Iterable<<API key>>>() {
@Override
public Iterable<<API key>> call(Page<<API key>> page) {
return page.items();
}
})
.map(new Func1<<API key>, DeploymentOperation>() {
@Override
public DeploymentOperation call(<API key> inner) {
return new <API key>(inner, manager());
}
});
}
@Override
public Observable<DeploymentOperation> getAsync(String resourceGroupName, String deploymentName, String operationId) {
<API key> client = this.inner();
return client.getAsync(resourceGroupName, deploymentName, operationId)
.map(new Func1<<API key>, DeploymentOperation>() {
@Override
public DeploymentOperation call(<API key> inner) {
return new <API key>(inner, manager());
}
});
}
@Override
public Observable<DeploymentOperation> <API key>(final String resourceGroupName, final String deploymentName) {
<API key> client = this.inner();
return client.<API key>(resourceGroupName, deploymentName)
.flatMapIterable(new Func1<Page<<API key>>, Iterable<<API key>>>() {
@Override
public Iterable<<API key>> call(Page<<API key>> page) {
return page.items();
}
})
.map(new Func1<<API key>, DeploymentOperation>() {
@Override
public DeploymentOperation call(<API key> inner) {
return new <API key>(inner, manager());
}
});
}
@Override
public Observable<DeploymentOperation> <API key>(final String groupId, final String deploymentName) {
<API key> client = this.inner();
return client.<API key>(groupId, deploymentName)
.flatMapIterable(new Func1<Page<<API key>>, Iterable<<API key>>>() {
@Override
public Iterable<<API key>> call(Page<<API key>> page) {
return page.items();
}
})
.map(new Func1<<API key>, DeploymentOperation>() {
@Override
public DeploymentOperation call(<API key> inner) {
return wrapModel(inner);
}
});
}
@Override
public Observable<DeploymentOperation> <API key>(String groupId, String deploymentName, String operationId) {
<API key> client = this.inner();
return client.<API key>(groupId, deploymentName, operationId)
.flatMap(new Func1<<API key>, Observable<DeploymentOperation>>() {
@Override
public Observable<DeploymentOperation> call(<API key> inner) {
if (inner == null) {
return Observable.empty();
} else {
return Observable.just((DeploymentOperation)wrapModel(inner));
}
}
});
}
} |
import { Command } from '../command/command';
/**
* Property that controls grid edit unit.
*
* * `'cell'` data is editable through the grid cells.
* * `'row'` data is editable through the grid rows.
* * `'null'` data is not editable.
*/
export declare type EditStateMode = null | 'cell' | 'row';
/**
* Indicates if q-grid is in `'edit'` or in a `'view'` mode.
*/
export declare type EditStateStatus = 'edit' | 'view' | 'startBatch' | 'endBatch';
/**
* Property that controls grid edit behavior.
*
* * `'batch'` batch update.
*/
export declare type EditStateMethod = null | 'batch';
/**
* A class represent options to control q-grid edit mode.
*/
export declare class EditState {
/**
* Property that controls grid edit unit.
*/
mode: EditStateMode;
/**
* Indicates if q-grid is in `'edit'` or in a `'view'` mode.
*/
status: EditStateStatus;
/**
* Property that controls grid edit behavior.
*/
method: EditStateMethod;
/**
* Allows to the grid user to control if cell or row can be edited or not.
*/
enter: Command;
/**
* Allows to the grid user to control if new cell value can be stored in data source or not.
*/
commit: Command;
/**
* Allows to the grid user to control if cell can exit edit mode.
*/
cancel: Command;
/**
* Allows to the grid user to control if cell can exit edit mode.
*/
reset: Command;
/**
* Allows to the grid user to manage clear action behavior in edit mode.
*/
clear: Command;
/**
* Object that contains `{columnKey: keyboardKeys}` map, that is used by q-grid to manage
* when cancel command should be execute on key down event.
*/
cancelShortcuts: { [key: string]: string };
/**
* Object that contains `{columnKey: keyboardKeys}` map, that is used by q-grid to manage
* when enter command should be execute on key down event.
*/
enterShortcuts: { [key: string]: string };
/**
* Object that contains `{columnKey: keyboardKeys}` map, that is used by q-grid to manage
* when commit command should be execute on key down event.
*/
commitShortcuts: { [key: string]: string };
} |
// ServiceClient.h
// OCMapper
#import <Foundation/Foundation.h>
@interface ServiceClient : NSObject
- (void)fetchDataWithUrl:(NSString *)urlString returnType:(Class)returnType andCompletion:(void (^)(id result, NSError *error))completion;
@end |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ru">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About HoboNickels</source>
<translation>О HoboNickels</translation>
</message>
<message>
<location line="+39"/>
<source><b>HoboNickels</b> version</source>
<translation><b>HoboNickels</b> версия</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2012 The HoboNickels developers</source>
<translation>Все права защищены © 2009-2012 Разработчики HoboNickels</translation>
</message>
<message>
<location line="+13"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http:
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http:
<translation>
Это экспериментальная программа.
Распространяется на правах лицензии MIT/X11, см. файл license.txt или http:
Этот продукт включает ПО, разработанное OpenSSL Project для использования в OpenSSL Toolkit (http:
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Адресная книга</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Для того, чтобы изменить адрес или метку давжды кликните по изменяемому объекту</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Создать новый адрес</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копировать текущий выделенный адрес в буфер обмена</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Новый адрес</translation>
</message>
<message>
<location line="-46"/>
<source>These are your HoboNickels addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Это Ваши адреса для получения платежей. Вы можете дать разные адреса отправителям, чтобы отслеживать, кто именно вам платит.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Копировать адрес</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Показать &QR код</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a HoboNickels address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом HoboNickels</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Удалить выбранный адрес из списка</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified HoboNickels address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом HoboNickels</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Удалить</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Копировать &метку</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Правка</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Экспортировать адресную книгу</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+142"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>[нет метки]</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Диалог ввода пароля</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Введите пароль</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Новый пароль</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Повторите новый пароль</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Введите новый пароль для бумажника. <br/> Пожалуйста, используйте фразы из <b>10 или более случайных символов,</b> или <b>восьми и более слов.</b></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Зашифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Разблокировать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Для выполнения операции требуется пароль вашего бумажника.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Расшифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Сменить пароль</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Введите старый и новый пароль для бумажника.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Подтвердите шифрование бумажника</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>Внимание: если вы зашифруете бумажник и потеряете пароль, вы <b>ПОТЕРЯЕТЕ ВСЕ ВАШИ МОНЕТЫ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Вы уверены, что хотите зашифровать ваш бумажник?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ВАЖНО: все предыдущие резервные копии вашего кошелька должны быть заменены новым зашифрованным файлом. В целях безопасности предыдущие резервные копии нешифрованного кошелька станут бесполезны, как только вы начнёте использовать новый шифрованный кошелёк.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Внимание: Caps Lock включен!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Бумажник зашифрован</translation>
</message>
<message>
<location line="-56"/>
<source>HoboNickels will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>Сейчас программа закроется для завершения процесса шифрования. Помните, что шифрование вашего бумажника не может полностью защитить ваши монеты от кражи с помощью инфицирования вашего компьютера вредоносным ПО.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Не удалось зашифровать бумажник</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Шифрование бумажника не удалось из-за внутренней ошибки. Ваш бумажник не был зашифрован.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Введённые пароли не совпадают.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Разблокировка бумажника не удалась</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Указанный пароль не подходит.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Расшифрование бумажника не удалось</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Пароль бумажника успешно изменён.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+257"/>
<source>Sign &message...</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="+237"/>
<source>Synchronizing with network...</source>
<translation>Синхронизация с сетью...</translation>
</message>
<message>
<location line="-299"/>
<source>&Overview</source>
<translation>О&бзор</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Показать общий обзор действий с бумажником</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Показать историю транзакций</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Адресная книга</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Изменить список сохранённых адресов и меток к ним</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&Получение монет</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Показать список адресов для получения платежей</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>Отп&равка монет</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>В&ыход</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Закрыть приложение</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about HoboNickels</source>
<translation>Показать информацию о HoboNickels'е</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>О &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Показать информацию о Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>Оп&ции...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Зашифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Сделать резервную копию бумажника</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Изменить пароль</translation>
</message>
<message numerus="yes">
<location line="+241"/>
<source>~%n block(s) remaining</source>
<translation>
<numerusform>остался ~%n блок</numerusform>
<numerusform>осталось ~%n блоков</numerusform>
<numerusform>осталось ~%n блоков</numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>Загружено %1 из %2 блоков истории операций (%3% завершено).</translation>
</message>
<message>
<location line="-242"/>
<source>&Export...</source>
<translation>&Экспорт...</translation>
</message>
<message>
<location line="-58"/>
<source>Send coins to a HoboNickels address</source>
<translation>Отправить монеты на указанный адрес HoboNickels</translation>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for HoboNickels</source>
<translation>Изменить параметры конфигурации HoboNickels</translation>
</message>
<message>
<location line="+14"/>
<source>Export the data in the current tab to a file</source>
<translation>Экспортировать данные из вкладки в файл</translation>
</message>
<message>
<location line="-10"/>
<source>Encrypt or decrypt wallet</source>
<translation>Зашифровать или расшифровать бумажник</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Сделать резервную копию бумажника в другом месте</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Изменить пароль шифрования бумажника</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Окно отладки</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Открыть консоль отладки и диагностики</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Проверить сообщение...</translation>
</message>
<message>
<location line="-186"/>
<source>HoboNickels</source>
<translation>HoboNickels</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+168"/>
<source>&About HoboNickels</source>
<translation>&О HoboNickels</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Показать / Скрыть</translation>
</message>
<message>
<location line="+39"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Помощь</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Панель вкладок</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Панель действий</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[тестовая сеть]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>HoboNickels client</source>
<translation>HoboNickels клиент</translation>
</message>
<message numerus="yes">
<location line="+69"/>
<source>%n active connection(s) to HoboNickels network</source>
<translation>
<numerusform>%n активное соединение с сетью</numerusform>
<numerusform>%n активных соединений с сетью</numerusform>
<numerusform>%n активных соединений с сетью</numerusform>
</translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Загружено %1 блоков истории транзакций.</translation>
</message>
<message numerus="yes">
<location line="+22"/>
<source>%n second(s) ago</source>
<translation>
<numerusform>%n секунду назад</numerusform>
<numerusform>%n секунды назад</numerusform>
<numerusform>%n секунд назад</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation>
<numerusform>%n минуту назад</numerusform>
<numerusform>%n минуты назад</numerusform>
<numerusform>%n минут назад</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation>
<numerusform>%n час назад</numerusform>
<numerusform>%n часа назад</numerusform>
<numerusform>%n часов назад</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation>
<numerusform>%n день назад</numerusform>
<numerusform>%n дня назад</numerusform>
<numerusform>%n дней назад</numerusform>
</translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Синхронизированно</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Синхронизируется...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation>Последний полученный блок был сгенерирован %1.</translation>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Данная транзакция превышает предельно допустимый размер. Но Вы можете всё равно совершить её, добавив комиссию в %1, которая отправится тем узлам, которые обработают Вашу транзакцию, и поможет поддержать сеть. Вы хотите добавить комиссию?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>Подтвердите комиссию</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Исходящая транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Входящая транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Дата: %1
Количество: %2
Тип: %3
Адрес: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>Обработка URI</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid HoboNickels address or malformed URI parameters.</source>
<translation>Не удалось обработать URI! Это может быть связано с неверным адресом HoboNickels или неправильными параметрами URI.</translation>
</message>
<message>
<location line="+16"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>разблокирован</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Бумажник <b>зашифрован</b> и в настоящее время <b>заблокирован</b></translation>
</message>
<message>
<location line="+23"/>
<source>Backup Wallet</source>
<translation>Сделать резервную копию бумажника</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Данные бумажника (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Резервное копирование не удалось</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>При попытке сохранения данных бумажника в новое место произошла ошибка.</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. HoboNickels can no longer continue safely and will quit.</source>
<translation>Произошла неисправимая ошибка. HoboNickels не может безопасно продолжать работу и будет закрыт.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Сетевая Тревога</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../coincontroldialog.cpp" line="+36"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location line="+3"/>
<source>Copy transaction ID</source>
<translation type="unfinished">Скопировать ID транзакции</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Копировать количество</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Копировать комиссию</translation>
</message>
<message>
<location line="+2"/>
<source>Copy bytes</source>
<translation>Копировать объем</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Копировать приоритет</translation>
</message>
<message>
<location line="+319"/>
<source>highest</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished">[нет метки]</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-593"/>
<source>Copy after fee</source>
<translation>Копировать с комиссией</translation>
</message>
<message>
<location line="-29"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Копировать сумму</translation>
</message>
<message>
<location line="+5"/>
<source>Copy low output</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Копировать сдачу</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+395"/>
<source>(un)select all</source>
<translation>Выбрать все</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Дерево</translation>
</message>
<message>
<location line="-168"/>
<source>Low Output:</source>
<translation>Мелкие входы:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+481"/>
<source>yes</source>
<translation>да</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+22"/>
<location filename="../coincontroldialog.cpp" line="+0"/>
<source>no</source>
<translation>нет</translation>
</message>
<message>
<location line="+162"/>
<source>List mode</source>
<translation>Список</translation>
</message>
<message>
<location line="-410"/>
<source>Coin Control</source>
<translation>Выбор входов</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Количество:</translation>
</message>
<message>
<location line="+160"/>
<source>Fee:</source>
<translation>Комиссия:</translation>
</message>
<message>
<location line="-128"/>
<source>Bytes:</source>
<translation>Размер:</translation>
</message>
<message>
<location line="+249"/>
<source>Change:</source>
<translation>Сдача:</translation>
</message>
<message>
<location line="-169"/>
<source>Priority:</source>
<translation>Приоритет:</translation>
</message>
<message>
<location line="+340"/>
<source>Priority</source>
<translation>Приоритет</translation>
</message>
<message>
<location line="-23"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="-410"/>
<location line="+32"/>
<source>0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+48"/>
<location line="+80"/>
<location line="+86"/>
<location line="+38"/>
<source>0.00 HBN</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+131"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Подтверждения</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location line="-201"/>
<source>After Fee:</source>
<translation>С комиссией:</translation>
</message>
<message>
<location line="-166"/>
<source>Amount:</source>
<translation>Сумма:</translation>
</message>
<message>
<location line="+344"/>
<source>Amount</source>
<translation>Сумма</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Изменить адрес</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Метка</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Метка, связанная с данной записью</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адрес</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Адрес, связанный с данной записью.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Новый адрес для получения</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Новый адрес для отправки</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Изменение адреса для получения</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Изменение адреса для отправки</translation>
</message>
<message>
<location line="+60"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Введённый адрес «%1» уже находится в адресной книге.</translation>
</message>
<message>
<location line="+5"/>
<source>The entered address "%1" is not a valid HoboNickels address.</source>
<translation>Введённый адрес "%1" не является правильным HoboNickels-адресом.</translation>
</message>
<message>
<location line="+5"/>
<source>Could not unlock wallet.</source>
<translation>Не удается разблокировать бумажник.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Генерация нового ключа не удалась.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>HoboNickels-Qt</source>
<translation>HoboNickels-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>версия</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>параметры командной строки</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Опции интерфейса</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Выберите язык, например "de_DE" (по умолчанию: как в системе)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Запускать свёрнутым</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Показывать сплэш при запуске (по умолчанию: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Главная</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>Опциональная комиссия за каждый КБ транзакции, которая позволяет быть уверенным, что Ваша транзакция будет обработана быстро. Большинство транзакций занимают 1КБ. Рекомендуется комиссия 0.01.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Заплатить ко&миссию</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start HoboNickels after logging in to the system.</source>
<translation>Автоматически запускать HoboNickels после входа в систему</translation>
</message>
<message>
<location line="+3"/>
<source>&Start HoboNickels on system login</source>
<translation>&Запускать HoboNickels при входе в систему</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Отключить базы данных блоков и адресов при выходе. Это означает, что их можно будет переместить в другой каталог данных, но завершение работы будет медленнее. Бумажник всегда отключается.</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>&Отключать базы данных при выходе</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Сеть</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the HoboNickels client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматически открыть порт для HoboNickels-клиента на роутере. Работает только если Ваш роутер поддерживает UPnP, и данная функция включена.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Пробросить порт через &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the HoboNickels network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Подключаться к сети HoboNickels через прокси SOCKS (например, при подключении через Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Подключаться через SOCKS прокси:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP Прокси: </translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-адрес прокси (например 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>По&рт: </translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Порт прокси-сервера (например, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Версия SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Версия SOCKS-прокси (например, 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Окно</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Показывать только иконку в системном лотке после сворачивания окна.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Cворачивать в системный лоток вместо панели задач</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Сворачивать вместо закрытия. Если данная опция будет выбрана — приложение закроется только после выбора соответствующего пункта в меню.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>С&ворачивать при закрытии</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>О&тображение</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Язык интерфейса:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting HoboNickels.</source>
<translation>Здесь можно выбрать язык интерфейса. Настройки вступят в силу после перезапуска HoboNickels.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Отображать суммы в единицах: </translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Выберите единицу измерения монет при отображении и отправке.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show HoboNickels addresses in the transaction list or not.</source>
<translation>Показывать ли адреса HoboNickels в списке транзакций.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Показывать адреса в списке транзакций</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Выключает и включает отображение панели выбора входов.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Управление &входами (только для продвинутых пользователей!)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>О&К</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Отмена</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Применить</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>по умолчанию</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Внимание</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting HoboNickels.</source>
<translation>Эта настройка вступит в силу после перезапуска HoboNickels</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Адрес прокси неверен.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+33"/>
<location line="+212"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the HoboNickels network after a connection is established, but this process has not completed yet.</source>
<translation>Отображаемая информация может быть устаревшей. Ваш бумажник автоматически синхронизируется с сетью HoboNickels после подключения, но этот процесс пока не завершён.</translation>
</message>
<message>
<location line="-170"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+29"/>
<source>Stake:</source>
<translation>Доля:</translation>
</message>
<message>
<location line="+84"/>
<source>Number of transactions:</source>
<translation>Количество транзакций:</translation>
</message>
<message>
<location line="-55"/>
<source>Unconfirmed:</source>
<translation>Не подтверждено:</translation>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Бумажник</translation>
</message>
<message>
<location line="+136"/>
<source>Immature:</source>
<translation>Незрелые:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Баланс добытых монет, который ещё не созрел</translation>
</message>
<message>
<location line="+63"/>
<source><b>Recent transactions</b></source>
<translation><b>Последние транзакции</b></translation>
</message>
<message>
<location line="-147"/>
<source>Your current balance</source>
<translation>Ваш текущий баланс</translation>
</message>
<message>
<location line="+58"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Общая сумма всех транзакций, которые до сих пор не подтверждены, и до сих пор не учитываются в текущем балансе</translation>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Общая сумма всех монет, используемых для Proof-of-Stake, и не учитывающихся на балансе</translation>
</message>
<message>
<location line="+75"/>
<source>Total number of transactions in wallet</source>
<translation>Общее количество транзакций в Вашем бумажнике</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>не синхронизировано</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Диалог QR-кода</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Запросить платёж</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Количество:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Метка:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Сообщение:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Сохранить как...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Ошибка кодирования URI в QR-код</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Введено неверное количество, проверьте ещё раз.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Получившийся URI слишком длинный, попробуйте сократить текст метки / сообщения.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Сохранить QR-код</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Изображения (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Имя клиента</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Н/Д</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Версия клиента</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Информация</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Используется версия OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Время запуска</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Сеть</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Число подключений</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>В тестовой сети</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Цепь блоков</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Текущее число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Расчётное число блоков</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Время последнего блока</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Открыть</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Параметры командной строки</translation>
</message>
<message>
<location line="+7"/>
<source>Show the HoboNickels-Qt help message to get a list with possible HoboNickels command-line options.</source>
<translation>Показать помощь по HoboNickels-Qt, чтобы получить список доступных параметров командной строки.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Показать</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>Консоль</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Дата сборки</translation>
</message>
<message>
<location line="-104"/>
<source>HoboNickels - Debug window</source>
<translation>HoboNickels - Окно отладки</translation>
</message>
<message>
<location line="+25"/>
<source>HoboNickels Core</source>
<translation>Ядро HoboNickels</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Отладочный лог-файл</translation>
</message>
<message>
<location line="+7"/>
<source>Open the HoboNickels debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Открыть отладочный лог-файл HoboNickels из текущего каталога данных. Это может занять несколько секунд для больших лог-файлов.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Очистить консоль</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the HoboNickels RPC console.</source>
<translation>Добро пожаловать в RPC-консоль HoboNickels.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Используйте стрелки вверх и вниз для просмотра истории и <b>Ctrl-L</b> для очистки экрана.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Напишите <b>help</b> для просмотра доступных команд.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Отправка</translation>
</message>
<message>
<location line="+651"/>
<source>Send to multiple recipients at once</source>
<translation>Отправить нескольким получателям одновременно</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Добавить получателя</translation>
</message>
<message>
<location line="-578"/>
<source>Coin Control Features</source>
<translation>Выбор входов</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Входы...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>автоматический выбор</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Недостаточно средств!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished">Количество:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished">Размер:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BTC</source>
<translation type="unfinished">123.456 BTC {0.00 ?}</translation>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished">Приоритет:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished">Комиссия:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished">Мелкие входы:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished">нет</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished">С комиссией:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>адрес для сдачи</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a HoboNickels address (e.g. <API key>)</source>
<translation>Введите HoboNickels-адрес (например <API key>)</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+129"/>
<source>Remove all transaction fields</source>
<translation>Удалить все поля транзакции</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Подтвердить отправку</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Отправить</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished">Копировать количество</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished">Копировать комиссию</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished">Копировать с комиссией</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished">Копировать объем</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished">Копировать приоритет</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished">Копировать сдачу</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> адресату %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Подтвердите отправку монет</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Вы уверены, что хотите отправить %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> и </translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Адрес получателя неверный, пожалуйста, перепроверьте.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Количество монет для отправки должно быть больше 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Количество отправляемых монет превышает Ваш баланс</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Сумма превысит Ваш баланс, если комиссия в размере %1 будет добавлена к транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Обнаружен дублирующийся адрес. Отправка на один и тот же адрес возможна только один раз за одну операцию отправки</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation>Ошибка: не удалось создать транзакцию.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid Bitcoin address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished">[нет метки]</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ко&личество:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Полу&чатель:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Введите метку для данного адреса (для добавления в адресную книгу)</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Метка:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. <API key>)</source>
<translation>Адрес получателя платежа (например <API key>)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>Выберите адрес из адресной книги</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Удалить этого получателя</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a HoboNickels address (e.g. <API key>)</source>
<translation>Введите HoboNickels-адрес (например <API key>)</translation>
</message>
</context>
<context>
<name><API key></name>
<message>
<location filename="../forms/<API key>.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Подписи - подписать/проверить сообщение</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Подписать сообщение</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Вы можете подписывать сообщения своими адресами, чтобы доказать владение ими. Будьте осторожны, не подписывайте что-то неопределённое, так как фишинговые атаки могут обманным путём заставить вас подписать нежелательные сообщения. Подписывайте только те сообщения, с которыми вы согласны вплоть до мелочей.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. <API key>)</source>
<translation>Адрес, которым вы хотите подписать сообщение (напр. <API key>)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Выберите адрес из адресной книги</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Вставить адрес из буфера обмена</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Введите сообщение для подписи</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Скопировать текущую подпись в системный буфер обмена</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this HoboNickels address</source>
<translation>Подписать сообщение, чтобы доказать владение адресом HoboNickels</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Сбросить значения всех полей подписывания сообщений</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Очистить &всё</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Проверить сообщение</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Введите ниже адрес для подписи, сообщение (убедитесь, что переводы строк, пробелы, табы и т.п. в точности скопированы) и подпись, чтобы проверить сообщение. Убедитесь, что не скопировали лишнего в подпись, по сравнению с самим подписываемым сообщением, чтобы не стать жертвой атаки "man-in-the-middle".</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. <API key>)</source>
<translation>Адрес, которым было подписано сообщение (напр. <API key>)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified HoboNickels address</source>
<translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом HoboNickels</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Сбросить все поля проверки сообщения</translation>
</message>
<message>
<location filename="../<API key>.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a HoboNickels address (e.g. <API key>)</source>
<translation>Введите адрес HoboNickels (напр. <API key>)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Нажмите "Подписать сообщение" для создания подписи</translation>
</message>
<message>
<location line="+3"/>
<source>Enter HoboNickels signature</source>
<translation>Введите подпись HoboNickels</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Введённый адрес неверен</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Пожалуйста, проверьте адрес и попробуйте ещё раз.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Введённый адрес не связан с ключом</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Разблокировка бумажника была отменена.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Для введённого адреса недоступен закрытый ключ</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Не удалось подписать сообщение</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Сообщение подписано</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Подпись не может быть раскодирована.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Пожалуйста, проверьте подпись и попробуйте ещё раз.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Подпись не соответствует отпечатку сообщения.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Проверка сообщения не удалась.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Сообщение проверено.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation>
<numerusform>Открыто для %n блока</numerusform>
<numerusform>Открыто для %n блоков</numerusform>
<numerusform>Открыто для %n блоков</numerusform>
</translation>
</message>
<message>
<location line="+8"/>
<source>%1/offline</source>
<translation>%1/отключен</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/не подтверждено</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 подтверждений</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Статус</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, разослано через %n узел</numerusform>
<numerusform>, разослано через %n узла</numerusform>
<numerusform>, разослано через %n узлов</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Источник</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Сгенерированно</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>От</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Для</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>свой адрес</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>метка</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>будет доступно через %n блок</numerusform>
<numerusform>будет доступно через %n блока</numerusform>
<numerusform>будет доступно через %n блоков</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>не принято</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Дебет</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Комиссия</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Чистая сумма</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Сообщение</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Комментарий:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID транзакции</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 520 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Сгенерированные монеты должны подождать 520 блоков, прежде чем они могут быть потрачены. Когда Вы сгенерировали этот блок, он был отправлен в сеть для добавления в цепочку блоков. Если данная процедура не удастся, статус изменится на «не подтверждено», и монеты будут недействительны. Это иногда происходит в случае, если другой узел сгенерирует блок на несколько секунд раньше вас.</translation>
</message>
<message>
<source>Staked coins must wait 520 blocks before they can return to balance and be spent. When you generated this proof-of-stake block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to \"not accepted\" and not be a valid stake. This may occasionally happen if another node generates a proof-of-stake block within a few seconds of yours.</source>
<translation type="obsolete">Использованные в Proof-of-Stake монеты должны подождать 520 блоков, прежде чем они вернутся на баланс и смогут быть потрачены. Когда вы сгенерировали этот proof-of-stake блок, он был отправлен в сеть для добавления в цепочку блоков. Если данная процедура не удается, статус изменится на \"не подтверждени\" и блок будет недействителен. Это иногда происходит в случае, если другой узел сгенерирует блок на несколько секунд раньше вас.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Отладочная информация</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Транзакция</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Входы</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>истина</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>ложь</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ещё не было успешно разослано</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>неизвестно</translation>
</message>
</context>
<context>
<name><API key></name>
<message>
<location filename="../forms/<API key>.ui" line="+14"/>
<source>Transaction details</source>
<translation>Детали транзакции</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Данный диалог показывает детализированную статистику по выбранной транзакции</translation>
</message>
</context>
<context>
<name><API key></name>
<message>
<location filename="../<API key>.cpp" line="+226"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n block(s)</source>
<translation>
<numerusform>Открыто для %n блока</numerusform>
<numerusform>Открыто для %n блоков</numerusform>
<numerusform>Открыто для %n блоков</numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Открыто до %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Оффлайн (%1 подтверждений)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Не подтверждено (%1 из %2 подтверждений)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Подтверждено (%1 подтверждений)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation>
<numerusform>Добытыми монетами можно будет воспользоваться через %n блок</numerusform>
<numerusform>Добытыми монетами можно будет воспользоваться через %n блока</numerusform>
<numerusform>Добытыми монетами можно будет воспользоваться через %n блоков</numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Этот блок не был получен другими узлами и, возможно, не будет принят!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Сгенерированно, но не подтверждено</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Получено</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Получено от</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Отправлено</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Отправлено себе</translation>
</message>
<message>
<location line="+3"/>
<source>Mined</source>
<translation>Добыто</translation>
</message>
<message>
<location line="+39"/>
<source>(n/a)</source>
<translation>[не доступно]</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Статус транзакции. Подведите курсор к нужному полю для того, чтобы увидеть количество подтверждений.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата и время, когда транзакция была получена.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Тип транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Адрес назначения транзакции.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Сумма, добавленная, или снятая с баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Все</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Сегодня</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>На этой неделе</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>В этом месяце</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>За последний месяц</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>В этом году</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Промежуток...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Получено на</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Отправлено на</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Отправленные себе</translation>
</message>
<message>
<location line="+1"/>
<location line="+1"/>
<source>Mined</source>
<translation>Добытые</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Другое</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Введите адрес или метку для поиска</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Мин. сумма</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Копировать адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копировать метку</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Скопировать сумму</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Скопировать ID транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Изменить метку</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Показать подробности транзакции</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>Экспортировать данные транзакций</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Текст, разделённый запятыми (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Подтверждено</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Метка</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Количество</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Ошибка экспорта</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Невозможно записать в файл %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Промежуток от:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>Отправка....</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+124"/>
<source>HoboNickels version</source>
<translation>Версия</translation>
</message>
<message>
<location line="+39"/>
<source>Usage:</source>
<translation>Использование:</translation>
</message>
<message>
<source>Send command to -server or bitcoind</source>
<translation type="obsolete">Отправить команду на -server или bitcoind</translation>
</message>
<message>
<location line="-47"/>
<source>List commands</source>
<translation>Список команд
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Получить помощь по команде</translation>
</message>
<message>
<location line="+23"/>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<location line="+23"/>
<source>Specify configuration file (default: HoboNickels.conf)</source>
<translation>Указать конфигурационный файл (по умолчанию: HoboNickels.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: HoboNickelsd.pid)</source>
<translation>Указать pid-файл (по умолчанию: HoboNickels.pid)</translation>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation type="obsolete">Указать файл кошелька (в пределах DATA директории)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Укажите каталог данных</translation>
</message>
<message>
<location line="-8"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Установить размер кэша базы данных в мегабайтах (по умолчанию: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Установить размер лога базы данных в мегабайтах (по умолчанию: 100)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 7777 or testnet: 17777)</source>
<translation>Принимать входящие подключения на <port> (по умолчанию: 7777 или 17777 в тестовой сети)</translation>
</message>
<message>
<location line="+4"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Поддерживать не более <n> подключений к узлам (по умолчанию: 125)</translation>
</message>
<message>
<location line="-32"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Подключиться к узлу, чтобы получить список адресов других участников и отключиться</translation>
</message>
<message>
<location line="+65"/>
<source>Specify your own public address</source>
<translation>Укажите ваш собственный публичный адрес</translation>
</message>
<message>
<location line="-74"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Привязаться (bind) к указанному адресу. Используйте запись вида [хост]:порт для IPv6</translation>
</message>
<message>
<location line="+76"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Порог для отключения неправильно ведущих себя узлов (по умолчанию: 100)</translation>
</message>
<message>
<location line="-108"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Число секунд блокирования неправильно ведущих себя узлов (по умолчанию: 86400)</translation>
</message>
<message>
<location line="-27"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Произошла ошибка при открытии RPC-порта %u для прослушивания на IPv4: %s</translation>
</message>
<message>
<location line="+2"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Произошла ошибка при открытии на прослушивание IPv6 RCP-порта %u, возвращаемся к IPv4: %s</translation>
</message>
<message>
<location line="+6"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Отключить базы данных блоков и адресов. Увеличивает время завершения работы (по умолчанию: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Ошибка инициализации окружения БД %s! Для восстановления СДЕЛАЙТЕ РЕЗЕРВНУЮ КОПИЮ этой директории, затем удалите из нее все, кроме wallet.dat.</translation>
</message>
<message>
<location line="+10"/>
<source>Error: Wallet unlocked for block minting only, unable to create transaction.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+5"/>
<source>Listen for JSON-RPC connections on <port> (default: 8344 or testnet: 18344)</source>
<translation>Прослушивать подключения JSON-RPC на <порту> (по умолчанию: 8344 или для testnet: 18344)</translation>
</message>
<message>
<location line="+16"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Внимание: ошибка чтения wallet.dat! Все ключи восстановлены, но записи в адресной книге и истории транзакций могут быть некорректными.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Внимание: wallet.dat был поврежден, данные восстановлены! Оригинальный wallet.dat сохранен как wallet.{timestamp}.bak в %s;, если ваши транзакции или баланс отображаются неправильно, следует восстановить его из данной копии.</translation>
</message>
<message>
<location line="+9"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Принимать командную строку и команды JSON-RPC</translation>
</message>
<message>
<location line="+5"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Попытка восстановления ключей из поврежденного wallet.dat</translation>
</message>
<message>
<location line="+23"/>
<source>Find peers using DNS lookup (default: 0)</source>
<translation type="unfinished">Искать узлы с помощью DNS (по умолчанию: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Importing blockchain data file.</source>
<translation>Импортируется файл цепи блоков.</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Импортируется bootstrap-файл цепи блоков.</translation>
</message>
<message>
<location line="+26"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Запускаться в фоне как демон и принимать команды</translation>
</message>
<message>
<location line="+34"/>
<source>Use the test network</source>
<translation>Использовать тестовую сеть</translation>
</message>
<message>
<location line="-93"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Принимать подключения извне (по умолчанию: 1, если не используется -proxy или -connect)</translation>
</message>
<message>
<location line="-41"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Ошибка: эта транзакция требует комиссию в размере как минимум %s из-за её объёма, сложности или использования недавно полученных средств </translation>
</message>
<message>
<location line="+13"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Максимальный размер высокоприоритетных/низкокомиссионных транзакций в байтах (по умолчанию: 27000)</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Внимание: установлено очень большое значение -paytxfee. Это комиссия, которую вы заплатите при проведении транзакции.</translation>
</message>
<message>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="obsolete">Внимание: отображаемые транзакции могут быть некорректны! Вам или другим узлам, возможно, следует обновиться.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong HoboNickels will not work properly.</source>
<translation>Внимание: убедитесь, что дата и время на Вашем компьютере выставлены верно. Если Ваши часы идут неправильно, HoboNickels будет работать некорректно.</translation>
</message>
<message>
<location line="+22"/>
<source>Block creation options:</source>
<translation>Параметры создания блоков:</translation>
</message>
<message>
<location line="+6"/>
<source>Connect only to the specified node(s)</source>
<translation>Подключаться только к указанному узлу(ам)</translation>
</message>
<message>
<location line="+3"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Определить свой IP (по умолчанию: 1 при прослушивании и если не используется -externalip)</translation>
</message>
<message>
<location line="+7"/>
<source>Error: Transaction creation failed </source>
<translation>Ошибка: Создание транзакции не удалось </translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Ошибка: бумажник заблокирован, невозможно создать транзакцию </translation>
</message>
<message>
<location line="+2"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Не удалось начать прослушивание на порту. Используйте -listen=0 если вас это устраивает.</translation>
</message>
<message>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="obsolete">Искать узлы с помощью DNS (по умолчанию: 1)</translation>
</message>
<message>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="obsolete">Политика синхронизированных меток (по умолчанию: strict)</translation>
</message>
<message>
<source>Use pooled pubkeys for the last coinstake output (default: 0)</source>
<translation type="obsolete">Использовать для coinstake транзакций ключи из пула (по умолчанию: 0)</translation>
</message>
<message>
<source>Which key derivation method to use by default (default: sha512)</source>
<translation type="obsolete">Выбор функции для создания ключа шифрования (по умолчанию: sha512)</translation>
</message>
<message>
<location line="+12"/>
<source>Invalid -tor address: '%s'</source>
<translation>Неверный адрес -tor: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+8"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Максимальный размер буфера приёма на соединение, <n>*1000 байт (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Максимальный размер буфера отправки на соединение, <n>*1000 байт (по умолчанию: 1000)</translation>
</message>
<message>
<location line="+3"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Подключаться только к узлам из сети <net> (IPv4, IPv6 или Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Выводить больше отладочной информации. Включает все остальные опции -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Выводить дополнительную сетевую отладочную информацию</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Дописывать отметки времени к отладочному выводу</translation>
</message>
<message>
<location line="+4"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>
Параметры SSL: (см. Bitcoin Wiki для инструкций по настройке SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Выберите версию SOCKS-прокси (4-5, по умолчанию: 5)</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or HoboNickelsd</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+2"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Выводить информацию трассировки/отладки на консоль вместо файла debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Отправлять информацию трассировки/отладки в отладчик</translation>
</message>
<message>
<location line="+7"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Максимальный размер блока в байтах (по умолчанию: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Минимальный размер блока в байтах (по умолчанию: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Сжимать файл debug.log при запуске клиента (по умолчанию: 1, если нет -debug)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Таймаут соединения в миллисекундах (по умолчанию: 5000)</translation>
</message>
<message>
<location line="+8"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location line="+6"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Использовать UPnP для проброса порта (по умолчанию: 1, если используется прослушивание)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Использовать прокси для скрытых сервисов (по умолчанию: тот же, что и в -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Имя для подключений JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying database integrity...</source>
<translation>Проверка целостности базы данных...</translation>
</message>
<message>
<location line="+2"/>
<source>Warning: Disk space is low!</source>
<translation>Внимание: мало места на диске!</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Внимание: эта версия устарела, требуется обновление!</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat поврежден, восстановление не удалось</translation>
</message>
<message>
<location line="-44"/>
<source>Password for JSON-RPC connections</source>
<translation>Пароль для подключений JSON-RPC</translation>
</message>
<message>
<location line="-52"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Разрешить подключения JSON-RPC с указанного IP</translation>
</message>
<message>
<location line="+60"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Посылать команды узлу, запущенному на <ip> (по умолчанию: 127.0.0.1)</translation>
</message>
<message>
<location line="-95"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Выполнить команду, когда появляется новый блок (%s в команде заменяется на хэш блока)</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="obsolete">Выполнить команду, когда получена новая транзакция (%s в команде заменяется на ID транзакции)</translation>
</message>
<message>
<location line="+119"/>
<source>Upgrade wallet to latest format</source>
<translation>Обновить бумажник до последнего формата</translation>
</message>
<message>
<location line="-16"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Установить размер запаса ключей в <n> (по умолчанию: 100)</translation>
</message>
<message>
<location line="-14"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Перепроверить цепь блоков на предмет отсутствующих в бумажнике транзакций</translation>
</message>
<message>
<location line="-27"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Сколько блоков проверять при запуске (по умолчанию: 2500, 0 = все)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Насколько тщательно проверять блоки (0-6, по умолчанию: 1)</translation>
</message>
<message>
<location line="+3"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Импортировать блоки из внешнего файла blk000?.dat</translation>
</message>
<message>
<location line="+55"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Использовать OpenSSL (https) для подключений JSON-RPC</translation>
</message>
<message>
<location line="-22"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Файл серверного сертификата (по умолчанию: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Приватный ключ сервера (по умолчанию: server.pem)</translation>
</message>
<message>
<location line="-125"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Разрешённые алгоритмы (по умолчанию: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+137"/>
<source>This help message</source>
<translation>Эта справка</translation>
</message>
<message>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="obsolete">Кошелек %s находится вне рабочей директории %s.</translation>
</message>
<message>
<location line="-129"/>
<source>Cannot obtain a lock on data directory %s. HoboNickels is probably already running.</source>
<translation>Невозможно установить блокировку на рабочую директорию %s. Возможно, бумажник уже запущен.</translation>
</message>
<message>
<location line="+99"/>
<source>HoboNickels</source>
<translation>HoboNickels</translation>
</message>
<message>
<location line="+33"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Невозможно привязаться к %s на этом компьютере (bind вернул ошибку %d, %s)</translation>
</message>
<message>
<location line="-70"/>
<source>Connect through socks proxy</source>
<translation>Подключаться через socks прокси</translation>
</message>
<message>
<location line="-11"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Разрешить поиск в DNS для -addnode, -seednode и -connect</translation>
</message>
<message>
<location line="+41"/>
<source>Loading addresses...</source>
<translation>Загрузка адресов...</translation>
</message>
<message>
<location line="-26"/>
<source>Error loading blkindex.dat</source>
<translation>Ошибка чтения blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Ошибка загрузки wallet.dat: Бумажник поврежден</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of HoboNickels</source>
<translation>Ошибка загрузки wallet.dat: бумажник требует более новую версию HoboNickels</translation>
</message>
<message>
<location line="+76"/>
<source>Wallet needed to be rewritten: restart HoboNickels to complete</source>
<translation>Необходимо перезаписать бумажник, перезапустите HoboNickels для завершения операции.</translation>
</message>
<message>
<location line="-78"/>
<source>Error loading wallet.dat</source>
<translation>Ошибка при загрузке wallet.dat</translation>
</message>
<message>
<location line="+18"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Неверный адрес -proxy: '%s'</translation>
</message>
<message>
<location line="+50"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>В параметре -onlynet указана неизвестная сеть: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>В параметре -socks запрошена неизвестная версия: %i</translation>
</message>
<message>
<location line="-76"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Не удаётся разрешить адрес в параметре -externalip: '%s'</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Неверное количество в параметре -paytxfee=<кол-во>: '%s'</translation>
</message>
<message>
<location line="-14"/>
<source>Error: could not start node</source>
<translation>Ошибка: не удалось запустить узел</translation>
</message>
<message>
<location line="+42"/>
<source>Sending...</source>
<translation>Отправка...</translation>
</message>
<message>
<location line="-26"/>
<source>Invalid amount</source>
<translation>Неверное количество</translation>
</message>
<message>
<location line="-5"/>
<source>Insufficient funds</source>
<translation>Недостаточно монет</translation>
</message>
<message>
<location line="+9"/>
<source>Loading block index...</source>
<translation>Загрузка индекса блоков...</translation>
</message>
<message>
<location line="-43"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Добавить узел для подключения и пытаться поддерживать соединение открытым</translation>
</message>
<message>
<location line="-22"/>
<source>Unable to bind to %s on this computer. HoboNickels is probably already running.</source>
<translation>Невозможно привязаться к %s на этом компьютере. Возможно, HoboNickels уже работает.</translation>
</message>
<message>
<location line="+49"/>
<source>Find peers using internet relay chat (default: 1)</source>
<translation>Найти участников через IRC (по умолчанию: 1)</translation>
</message>
<message>
<location line="-2"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Комиссия на килобайт, добавляемая к вашим транзакциям</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Загрузка бумажника...</translation>
</message>
<message>
<location line="-38"/>
<source>Cannot downgrade wallet</source>
<translation>Не удаётся понизить версию бумажника</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Не удаётся инициализировать массив ключей</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Не удаётся записать адрес по умолчанию</translation>
</message>
<message>
<location line="+47"/>
<source>Rescanning...</source>
<translation>Сканирование...</translation>
</message>
<message>
<location line="-42"/>
<source>Done loading</source>
<translation>Загрузка завершена</translation>
</message>
<message>
<location line="+66"/>
<source>To use the %s option</source>
<translation>Чтобы использовать опцию %s</translation>
</message>
<message>
<location line="-148"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation>%s, вы должны установить опцию rpcpassword в конфигурационном файле:
%s
Рекомендуется использовать следующий случайный пароль:
rpcuser=bitcoinrpc
rpcpassword=%s
(вам не нужно запоминать этот пароль)
Если файл не существует, создайте его и установите права доступа только для владельца.
</translation>
</message>
<message>
<location line="+87"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location line="-27"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Вы должны установить rpcpassword=<password> в конфигурационном файле:
%s
Если файл не существует, создайте его и установите права доступа только для владельца.</translation>
</message>
</context>
</TS> |
package aimax.osm.data;
import java.util.Collection;
import java.util.List;
import aimax.osm.data.entities.MapEntity;
import aimax.osm.data.entities.MapNode;
import aimax.osm.data.entities.MapWay;
import aimax.osm.data.entities.WayRef;
/**
* Maintains a latitude longitude pair and provides some useful methods for
* distance calculations.
*
* @author Ruediger Lunde
*/
public class Position {
/** Earth's mean radius in km. */
public static double EARTH_RADIUS = 6371.0;
protected float lat;
protected float lon;
public Position(float lat, float lon) {
this.lat = lat;
this.lon = lon;
}
public Position(MapNode node) {
lat = node.getLat();
lon = node.getLon();
}
public float getLat() {
return lat;
}
public float getLon() {
return lon;
}
/**
* Computes the distance in kilometer from this position to a specified map
* node.
*/
public double getDistKM(MapEntity entity) {
if (entity instanceof MapNode) {
return getDistKM(lat, lon, ((MapNode) entity).getLat(),
((MapNode) entity).getLon());
} else if (entity instanceof MapWay) {
MapWay way = (MapWay) entity;
BoundingBox bb = way.computeBoundingBox();
float bbLat = (Math.abs(lat - bb.getLatMin()) < Math.abs(lat
- bb.getLatMax())) ? bb.getLatMin() : bb.getLatMax();
float bbLon = (Math.abs(lon - bb.getLonMin()) < Math.abs(lon
- bb.getLonMax())) ? bb.getLonMin() : bb.getLonMax();
return getDistKM(lat, lon, bbLat, bbLon);
}
return Double.NaN;
}
public boolean <API key>(List<MapEntity> nodes,
MapNode node) {
int pos = getInsertPosition(nodes, node);
if (pos != -1)
nodes.add(pos, node);
return pos != -1;
}
public boolean <API key>(List<MapEntity> ways,
MapWay way) {
int pos = getInsertPosition(ways, way);
if (pos != -1)
ways.add(pos, way);
return pos != -1;
}
private int getInsertPosition(List<?> entities, MapEntity entity) {
int pos1 = 0;
int pos2 = entities.size();
double newDistance = getDistKM(entity);
while (pos1 < pos2) {
int pos3 = (pos1 + pos2) / 2;
double dist3 = getDistKM((MapEntity) entities.get(pos3));
if (newDistance < dist3)
pos2 = pos3;
else if (newDistance > dist3)
pos1 = pos3 + 1;
else
pos1 = pos2 = pos3;
}
if (pos1 < entities.size()) {
for (int i = pos1; i >= 0
&& getDistKM((MapEntity) entities.get(i)) == newDistance; i
if (entities.get(i) == entity)
return -1;
for (int i = pos1 + 1; i < entities.size()
&& getDistKM((MapEntity) entities.get(i)) == newDistance; i++)
if (entities.get(i) == entity)
return -1;
}
return pos1;
}
/**
* Returns the node from <code>nodes</code> which is nearest to this
* position. If a filter is given, only those nodes are inspected, which are
* part of a way accepted by the filter.
*
* @param filter
* possibly null
* @return A node or null
*/
public MapNode selectNearest(Collection<MapNode> nodes, MapWayFilter filter) {
MapNode result = null;
double dist = Double.MAX_VALUE;
double newDist;
for (MapNode node : nodes) {
newDist = getDistKM(node);
boolean found = (newDist < dist);
if (found && filter != null) {
found = false;
for (WayRef ref : node.getWayRefs()) {
if (filter.isAccepted(ref.getWay()))
found = true;
}
}
if (found) {
result = node;
dist = newDist;
}
}
return result;
}
/**
* Computes a simple approximation of the compass course from this position
* to the specified node.
*
* @return Number between 1 and 360
*/
public int getCourseTo(MapNode node) {
double lonCorr = Math.cos(Math.PI / 360.0 * (lat + node.getLat()));
double latDist = node.getLat() - lat;
double lonDist = lonCorr * (node.getLon() - lon);
int course = (int) (180.0 / Math.PI * Math.atan2(lonDist, latDist));
if (course <= 0)
course += 360;
return course;
}
/** Computes the total length of a track in kilometers. */
public static double getTrackLengthKM(List<MapNode> nodes) {
double result = 0.0;
for (int i = 1; i < nodes.size(); i++) {
MapNode n1 = nodes.get(i - 1);
MapNode n2 = nodes.get(i);
result += getDistKM(n1.getLat(), n1.getLon(), n2.getLat(), n2
.getLon());
}
return result;
}
/**
* Computes the distance between two positions on the earth surface using
* the haversine formula.
*/
public static double getDistKM(float lat1, float lon1, float lat2,
float lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return EARTH_RADIUS * c;
}
} |
(function() {
"use strict";
var co = require('co');
var assert = require('assert');
describe("Ceramic Core", function() {
var Author, BlogPost;
var authorSchema, postSchema;
var Ceramic;
before(function() {
return co(function*() {
Ceramic = require("../lib/ceramic");
Author = function(params) {
if (params) {
for(var key in params) {
this[key] = params[key];
}
}
};
authorSchema = {
ctor: Author,
schema: {
id: 'author',
type: 'object',
properties: {
name: { type: 'string' },
location: { type: 'string' },
age: { type: 'number' }
},
required: ['name', 'location']
}
};
BlogPost = function(params) {
if (params) {
for(var key in params) {
this[key] = params[key];
}
}
};
postSchema = {
ctor: BlogPost,
schema: {
id: 'post',
type: 'object',
properties: {
title: { type: 'string' },
content: { type: 'string' },
published: { type: 'string' },
author: { $ref: 'author' }
},
required: ['title', 'content', 'author']
}
};
});
});
it("<API key> must complete the entitySchema", function() {
return co(function*() {
var songSchema = {
schema: {
id: 'song',
type: 'object',
properties: {
title: { type: 'string' },
artist: { type: 'string' },
price: { type: 'number' }
},
required: ['title', 'artist']
}
};
var ceramic = new Ceramic();
var entitySchema = yield* ceramic.<API key>(songSchema);
assert.notEqual(entitySchema, null);
assert.equal(entitySchema.schema.required.length, 2);
});
});
it("<API key> must complete the virtualEntitySchema", function() {
return co(function*() {
var songSchema = {
schema: {
id: 'song',
type: 'object',
properties: {
title: { type: 'string' },
artist: { type: 'string' },
price: { type: 'number' }
},
required: ['title', 'artist']
}
};
var mp3Schema = {
schema: {
id: 'mp3',
properties: {
bitrate: { type: 'number' }
},
required: ['bitrate']
}
};
var ceramic = new Ceramic();
var entitySchema = yield* ceramic.<API key>(mp3Schema, songSchema);
assert.equal(entitySchema.schema.required.length, 3);
});
});
it("init must create a schema cache", function() {
return co(function*() {
var ceramic = new Ceramic();
var schemaCache = yield* ceramic.init([authorSchema, postSchema]);
assert.equal(Object.keys(schemaCache).length, 2);
});
});
it("constructEntity must construct a model", function() {
return co(function*() {
var ceramic = new Ceramic();
var schemaCache = yield* ceramic.init([authorSchema, postSchema]);
var blogPostJSON = {
title: "Busy Being Born",
content: "The days keep dragging on, Those rats keep pushing on, The slowest race around, We all just race around ...",
published: "yes",
author: {
name: "Middle Class Rut",
location: "USA",
}
};
var blogPost = yield* ceramic.constructEntity(blogPostJSON, postSchema);
assert.equal(blogPost instanceof BlogPost, true, "blogPost must be an instanceof BlogPost");
assert.equal(blogPost.author instanceof Author, true, "blogPost must be an instanceof Author");
});
});
it("constructEntity must construct a model with virtual-schema", function() {
return co(function*() {
var songSchema = {
discriminator: function*(obj, ceramic) {
return yield* ceramic.getEntitySchema(obj.type);
},
schema: {
id: 'song',
type: 'object',
properties: {
title: { type: 'string' },
artist: { type: 'string' },
price: { type: 'number' },
type: { type: 'string' }
},
required: ['title', 'artist']
}
};
var mp3Schema = {
schema: {
id: "mp3",
properties: {
bitrate: { type: 'number' }
},
required: ['bitrate']
}
};
var youtubeVideoSchema = {
schema: {
id: "youtube",
properties: {
url: { type: 'string' },
highDef: { type: 'boolean' }
},
required: ['url', 'highDef']
}
};
var ceramic = new Ceramic();
var schemaCache = yield* ceramic.init(
[songSchema], //schemas
[
{
entitySchemas: [mp3Schema, youtubeVideoSchema],
baseEntitySchema: songSchema
}
] //virtual-schemas
);
var mp3JSON = {
"type": "mp3",
"title": "Busy Being Born",
"artist": "Middle Class Rut",
"bitrate": 320
};
var mp3 = yield* ceramic.constructEntity(mp3JSON, songSchema, { validate: true });
assert.equal(mp3.bitrate, 320);
});
});
it("updateEntity must update a model", function() {
return co(function*() {
var blogPost = new BlogPost({
title: "
content: "
});
var ceramic = new Ceramic();
var schemaCache = yield* ceramic.init([authorSchema, postSchema]);
var blogPostJSON = {
title: "Busy Being Born",
content: "The days keep dragging on, Those rats keep pushing on, The slowest race around, We all just race around ...",
published: "yes",
author: {
name: "Middle Class Rut",
location: "USA",
}
};
yield* ceramic.updateEntity(blogPost, blogPostJSON, postSchema);
assert.equal(blogPost instanceof BlogPost, true, "blogPost must be an instanceof BlogPost");
assert.equal(blogPost.author instanceof Author, true, "blogPost must be an instanceof Author");
assert.equal(blogPost.title, "Busy Being Born", "blogPost.title must be Busy Being Born");
});
});
it("validate must return an error for the missing author field", function() {
return co(function*() {
var ceramic = new Ceramic();
var typeCache = yield* ceramic.init([authorSchema, postSchema]);
var blogPost = new BlogPost({
title: "
content: "
});
var errors = yield* ceramic.validate(blogPost, postSchema);
//Missing author
assert.equal(errors[0].constraintName, 'required');
});
});
it("validate must return an error for the mismatched author field type", function() {
return co(function*() {
var ceramic = new Ceramic();
var typeCache = yield* ceramic.init([authorSchema, postSchema]);
var blogPost = new BlogPost({
title: "Ceramic Documentation",
content: "See README.MD...",
author: "jeswin"
});
var errors = yield* ceramic.validate(blogPost, postSchema);
//author field breaks the type constraint
assert.equal(errors[0].constraintName, 'type');
});
});
it("validate must return no errors for correct schema", function() {
return co(function*() {
var ceramic = new Ceramic();
var typeCache = yield* ceramic.init([authorSchema, postSchema]);
var blogPost = new BlogPost({
title: "Busy Being Born",
content: "The days keep dragging on, Those rats keep pushing on, The slowest race around, We all just race around ...",
published: "yes",
author: new Author({
name: "jeswin",
location: "bangalore"
})
});
var errors = yield* ceramic.validate(blogPost, postSchema);
assert.equal(errors, undefined);
});
});
it("load a dynamic schema", function() {
return co(function*() {
var songSchema = {
schema: {
id: "song",
type: 'object',
properties: {
title: { type: 'string' },
artist: { type: 'string' },
price: { type: 'number' },
torrent: { $ref: 'torrent' }
},
required: ['title', 'artist']
}
};
var torrentSchema = {
schema: {
id: "torrent",
type: "object",
properties: {
fileName: { type: 'string' },
seeds: { type: 'number' },
leeches: { type: 'number' }
},
required: ['fileName', 'seeds', 'leeches']
}
};
var dynamicLoader = function*(name, <API key>) {
switch(name) {
case "torrent":
return yield* ceramic.<API key>(torrentSchema);
}
};
var ceramic = new Ceramic({
fn: { <API key>: dynamicLoader }
});
//song schema references torrent schema, but is not provided during init.
var schemaCache = yield* ceramic.init([songSchema]);
var songJSON = {
title: "Busy Being Born",
artist: "Middle Class Rut",
price: 10,
torrent: {
fileName: "busy-being-born.mp3",
seeds: 1000,
leeches: 1100
}
};
var mp3 = yield* ceramic.constructEntity(songJSON, songSchema, { validate: true });
assert.equal(mp3.torrent.fileName, "busy-being-born.mp3");
});
});
});
})(); |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Prototype Window Class : Documentation</title>
<!-- Prototype Window Class Part -->
<script type="text/javascript" src="javascripts/prototype.js"> </script>
<script type="text/javascript" src="javascripts/effects.js"> </script>
<script type="text/javascript" src="javascripts/window.js"> </script>
<script type="text/javascript" src="javascripts/debug.js"> </script>
<link href="themes/default.css" rel="stylesheet" type="text/css" > </link>
<!-- Doc Part-->
<link href="stylesheets/style.css" rel="stylesheet" type="text/css" > </link>
<script type="text/javascript" src="js/application.js"> </script>
</head>
<body onload="Application.insertDocOverview()">
<script>Application.insertNavigation('documentation')</script>
<div class="content">
<h2 class="first"> Overview</h2>
<div id="Overview"></div>
<h2>Window Class</h2>
Main class to handle windows<br/><br/>
<div class="function window" title="initialize"><a name="initialize"></a>
<p class="title"><span class="function">initialize(id, options)</span> Window constructor used when creating new window (new Window(id, options))</p>
<!
<p class="parameter_header">
<span class="field">Argument</span>
<span class="explanation">Description</span>
</p>
<p class="parameter">
<span class="field">id</span>
<span class="explanation">DOM id of the window must be unique</span>
</p>
<p class="parameter">
<span class="field">options</span>
<span class="explanation">
Hash map of window options, here is the key list:
<table>
<tr><th>Key</th> <th>Default</th> <th>Description </th></tr>
<tr><td class="key">className</td> <td class="default">dialog</td> <td class="detail">Class name prefix </td></tr>
<tr><td class="key">title</td> <td class="default">none</td> <td class="detail">Window's title </td></tr>
<tr><td class="key">url</td> <td class="default">none</td> <td class="detail">URL of window content (use an iframe)</td></tr>
<tr><td class="key">parent</td> <td class="default">body</td> <td class="detail">Parent node of the window </td></tr>
<tr><td class="key">top | bottom</td> <td class="default">top:0</td> <td class="detail">Top or bottom position of the window in pixels </td></tr>
<tr><td class="key">right | left</td> <td class="default">left:0</td> <td class="detail">Right or left position of the window in pixels</td></tr>
<tr><td class="key">width / height</td> <td class="default">100</td> <td class="detail">width and height of the window </td></tr>
<tr><td class="key">maxWidth / maxHeight</td> <td class="default">none</td> <td class="detail">Maximum width and height of the window</td></tr>
<tr><td class="key">minWidth / minHeight</td> <td class="default">100/20</td> <td class="detail">Minimum width and height of the window </td></tr>
<tr><td class="key">resizable</td> <td class="default">true</td> <td class="detail">Specify if the window can be resized </td></tr>
<tr><td class="key">closable</td> <td class="default">true</td> <td class="detail">Specify if the window can be closed </td></tr>
<tr><td class="key">minimizable</td> <td class="default">true</td> <td class="detail">Specify if the window can be minimized </td></tr>
<tr><td class="key">maximizable</td> <td class="default">true</td> <td class="detail">Specify if the window can be maximized</td></tr>
<tr><td class="key">draggable</td> <td class="default">true</td> <td class="detail">Specify if the window can be moved </td></tr>
<tr><td class="key">showEffect</td> <td class="default">Effect.Appear or<br> Element.show</td> <td class="detail">Show effect function. The default value depends if effect.js of script.aculo.us is included </td></tr>
<tr><td class="key">hideEffect</td> <td class="default">Effect.Fade or<br> Element.hide</td> <td class="detail">Hide effect function. The default value depends if effect.js of script.aculo.us is included </td></tr>
<tr><td class="key">showEffectOptions</td> <td class="default">none</td> <td class="detail">Show effect options (see script.aculo.us documentation).</td></tr>
<tr><td class="key">hideEffectOptions</td> <td class="default">none</td> <td class="detail">Hid effect options (see script.aculo.us documentation).</td></tr>
<tr><td class="key">effectOptions</td> <td class="default">none</td> <td class="detail">Show and hide effect options (see script.aculo.us documentation).</td></tr>
<tr><td class="key">onload</td> <td class="default">none</td> <td class="detail">Onload function of the main window div or iframe</td></tr>
<tr><td class="key">opacity</td> <td class="default">1</td> <td class="detail">Window opacity </td></tr>
</table>
</span>
</p>
</div>
<div class="function window" title="destroy"><a name="destroy"></a>
<p class="title"><span class="function">destroy()</span> Window destructor</p>
</div>
<div class="function window" title="getId"><a name="getId"></a>
<p class="title"><span class="function">getId()</span> Returns current window id</p>
</div>
<div class="function window" title="setDestroyOnClose"><a name="setDestroyOnClose"></a>
<p class="title"><span class="function">setDestroyOnClose()</span> The window will be destroy by clicking on close button instead of being hidden</p>
</div>
<div class="function window" title="setDelegate"><a name="setDelegate"></a>
<p class="title"><span class="function">setDelegate(delegate)</span> Sets window delegate</p>
<p class="parameter">
<span class="field">delegate</span>
<span class="explanation">Window delegate, should have canClose(window) function</span>
</p>
</div>
<div class="function window" title="getDelegate"><a name="getDelegate"></a>
<p class="title"><span class="function">getDelegate()</span> Returns current window delegate</p>
</div>
<div class="function window" title="setContent"><a name="setContent"></a>
<p class="title"><span class="function">setContent(id, autoresize, autoposition)</span> Sets window content using an existing element (does not work woth url/iframe)</p>
<p class="parameter">
<span class="field">id</span>
<span class="explanation">Element id to insert in the window</span>
</p>
<p class="parameter">
<span class="field">autoresize (default false)</span>
<span class="explanation">Resizes the window to fit with its content</span>
</p>
<p class="parameter">
<span class="field">autoposition (default false)</span>
<span class="explanation">Sets the current window position to the specified input element</span>
</p>
</div>
<div class="function window" title="setAjaxContent"><a name="setAjaxContent"></a>
<p class="title"><span class="function">setAjaxContent(url, options, showCentered, showModal)</span> Sets window content using an Ajax request. The request must return HTML code. See script.aculo.us <a href="http://wiki.script.aculo.us/scriptaculous/show/Ajax.Request">Ajax.request </a>documentation for details. When the response is received, the window is shown.</p>
<p class="parameter">
<span class="field">url</span>
<span class="explanation">Ajax request URL</span>
</p>
<p class="parameter">
<span class="field">options</span>
<span class="explanation">Ajax request options</span>
</p>
<p class="parameter">
<span class="field">showCentered (default false)</span>
<span class="explanation">Displays window centered when response is received</span>
</p>
<p class="parameter">
<span class="field">showModal (default false)</span>
<span class="explanation">Displays window in modal mode when response is received</span>
</p>
</div>
<div class="function window" title="getContent"><a name="getContent"></a>
<p class="title"><span class="function">getContent()</span> Returns current window content (a div or an iframe)</p>
</div>
<div class="function window" title="setCookie"><a name="setCookie"></a>
<p class="title"><span class="function">setCookie(name, expires, path, domain, secure)</span> Sets cookie informations to store window size and position</p>
<p class="parameter">
<span class="field">name (default window's id)</span>
<span class="explanation">Cookie name</span>
</p>
<p class="parameter">
<span class="field">expires, path, domain, secure</span>
<span class="explanation">Cookie attributes</span>
</p>
</div>
<div class="function window" title="setLocation"><a name="setLocation"></a>
<p class="title"><span class="function">setLocation(top, left)</span> Sets window top-left position</p>
<p class="parameter">
<span class="field">top</span>
<span class="explanation">Top position in pixels</span>
</p>
<p class="parameter">
<span class="field">bottom</span>
<span class="explanation">Bottom position in pixels</span>
</p>
</div>
<div class="function window" title="getSize"><a name="getSize"></a>
<p class="title"><span class="function">getSize()</span> Gets window content size. Return an hash with width and height as keys</p>
</div>
<div class="function window" title="setSize"><a name="setSize"></a>
<p class="title"><span class="function">setSize(width, height)</span> Sets window content size</p>
<p class="parameter">
<span class="field">width</span>
<span class="explanation">Width in pixels</span>
</p>
<p class="parameter">
<span class="field">height</span>
<span class="explanation">Height in pixels</span>
</p>
</div>
<div class="function window" title="updateWidth"><a name="updateWidth"></a>
<p class="title"><span class="function">updateWidth()</span> Recompute window width, useful when you change window content and do not want scrolling</p>
</div>
<div class="function window" title="updateHeight"><a name="updateHeight"></a>
<p class="title"><span class="function">updateHeight()</span> Recompute window height, useful when you change window content and do not want scrolling</p>
</div>
<div class="function window" title="toFront"><a name="toFront"></a>
<p class="title"><span class="function">toFront()</span> Brings current window in front of all others</p>
</div>
<div class="function window" title="toFront"><a name="toFront"></a>
<p class="title"><span class="function">toFront()</span> Brings current window in front of all others</p>
</div>
<div class="function window" title="show"><a name="show"></a>
<p class="title"><span class="function">show(modal)</span> Shows window at its current position</p>
<p class="parameter">
<span class="field">modal (default false)</span>
<span class="explanation">Modal mode</span>
</p>
</div>
<div class="function window" title="showCenter"><a name="showCenter"></a>
<p class="title"><span class="function">showCenter(modal, top, left)</span> Shows window in page's center. You can set top (or left) if you want to center only left (or top) value</p>
<p class="parameter">
<span class="field">modal (default false)</span>
<span class="field">top (default null)</span>
<span class="field">left (default null)</span>
<span class="explanation">Modal mode</span>
</p>
</div>
<div class="function window" title="minimize"><a name="minimize"></a>
<p class="title"><span class="function">minimize()</span> Minimizes the window, only top bar will be displayed</p>
</div>
<div class="function window" title="maximize"><a name="maximize"></a>
<p class="title"><span class="function">maximize()</span> Maximizes the window, the window will fit the viewable area of the page</p>
</div>
<div class="function window" title="isMinimized"><a name="isMinimized"></a>
<p class="title"><span class="function">isMinimized()</span> Returns true if the window is minimized</p>
</div>
<div class="function window" title="isMaximized"><a name="isMaximized"></a>
<p class="title"><span class="function">isMaximized()</span> Returns true if the window is maximized</p>
</div>
<div class="function window" title="setOpacity"><a name="setOpacity"></a>
<p class="title"><span class="function">setOpacity(opacity)</span> Sets window opacity</p>
<p class="parameter">
<span class="field">opacity</span>
<span class="explanation">Float value between 0 and 1</span>
</p>
</div>
<div class="function window" title="setZIndex"><a name="setZIndex"></a>
<p class="title"><span class="function">setZIndex(zindex)</span> Sets window zindex</p>
<p class="parameter">
<span class="field">zindex</span>
<span class="explanation">Int value</span>
</p>
</div>
<div class="function window" title="setTitle"><a name="setTitle"></a>
<p class="title"><span class="function">setTitle(title)</span> Sets window title</p>
<p class="parameter">
<span class="field">title</span>
<span class="explanation">Window title (can be null)</span>
</p>
</div>
<div class="function window" title="setStatusBar"><a name="setStatusBar"></a>
<p class="title"><span class="function">setStatusBar(element)</span> Sets window status bar</p>
<p class="parameter">
<span class="field">element</span>
<span class="explanation">Can be HTML code or an element</span>
</p>
</div>
<h2> Dialog module</h2>
Dialog factory to open alert/confirm/info modal panels<br/><br/>
<div class="function dialogmodule" title="confirm"><a name="confirm"></a>
<p class="title"><span class="function">confirm(content, options)</span> Opens a modal dialog with two buttons (ok/cancel for example)</p>
<p class="parameter">
<span class="field">content</span>
<span class="explanation">
- If the content is a string, it will be the message displayed in the dialog (HTML code)<br>
- If the content is an hash map, it will be used for setting content with an AJAX request. The hashmap must have url key and an optional options key (ajax options request)
</span>
</p>
<p class="parameter">
<span class="field">options</span>
<span class="explanation">
Hash map of dialog options, here is the key list:
<table>
<tr><th>Key</th> <th>Default</th> <th>Description </th></tr>
<tr><td class="key">top</td> <td class="default">null</td> <td class="detail">Top position </td></tr>
<tr><td class="key">left</td> <td class="default">null</td> <td class="detail">Left position </td></tr>
<tr><td class="key">okLabel</td> <td class="default">Ok</td> <td class="detail">Ok button label </td></tr>
<tr><td class="key">cancelLabel</td> <td class="default">Cancel</td> <td class="detail">Cancel button label </td></tr>
<tr><td class="key">okCallback</td> <td class="default">none</td> <td class="detail">Ok callback function called on ok button</td></tr>
<tr><td class="key">cancelCallback</td> <td class="default">none</td> <td class="detail">Cancel callback function called on ok button </td></tr>
<tr><td class="key">buttonClass</td> <td class="default">none</td> <td class="detail">Ok/Cancel button css class name </td></tr>
<tr><td class="key">windowParameters (hash map)</td> <td class="default">none</td> <td class="detail">Window constructor options </td></tr>
</table>
</span>
</p>
</div>
<div class="function dialogmodule" title="alert"><a name="alert"></a>
<p class="title"><span class="function">alert(content, options)</span> Opens a modal alert with one button (ok for example)</p>
<p class="parameter">
<span class="field">content</span>
<span class="explanation">
- If the content is a string, it will be the message displayed in the dialog (HTML code)<br>
- If the content is an hash map, it will be used for setting content with an AJAX request. The hashmap must have url key and an optional options key (ajax options request)
</span>
</p>
<p class="parameter">
<span class="field">options</span>
<span class="explanation">
Hash map of dialog options, here is the key list:
<table>
<tr><th>Key</th> <th>Default</th> <th>Description </th></tr>
<tr><td class="key">top</td> <td class="default">null</td> <td class="detail">Top position </td></tr>
<tr><td class="key">left</td> <td class="default">null</td> <td class="detail">Left position </td></tr>
<tr><td class="key">okLabel</td> <td class="default">Ok</td> <td class="detail">Ok button label </td></tr>
<tr><td class="key">okCallback</td> <td class="default">none</td> <td class="detail">Ok callback function called on ok button</td></tr>
<tr><td class="key">buttonClass</td> <td class="default">none</td> <td class="detail">Ok/Cancel button css class name </td></tr>
<tr><td class="key">windowParameters (hash map)</td> <td class="default">none</td> <td class="detail">Window constructor options </td></tr>
</table>
</span>
</p>
</div>
<div class="function dialogmodule" title="info"><a name="info"></a>
<p class="title"><span class="function">info(content, options)</span> Opens a modal info panel without any button. It can have a progress image (Used to display submit waiting message for example)</p>
<p class="parameter">
<span class="field">content</span>
<span class="explanation">
- If the content is a string, it will be the message displayed in the dialog (HTML code)<br>
- If the content is an hash map, it will be used for setting content with an AJAX request. The hashmap must have url key and an optional options key (ajax options request)
</span>
</p>
<p class="parameter">
<span class="field">options</span>
<span class="explanation">
Hash map of dialog options, here is the key list:
<table>
<tr><th>Key</th> <th>Default</th> <th>Description </th></tr>
<tr><td class="key">top</td> <td class="default">null</td> <td class="detail">Top position </td></tr>
<tr><td class="key">left</td> <td class="default">null</td> <td class="detail">Left position </td></tr>
<tr><td class="key">showProgress</td> <td class="default">false</td> <td class="detail">Add a progress image (info found in the css file) </td></tr>
<tr><td class="key">windowParameters (hash map)</td> <td class="default">none</td> <td class="detail">Window constructor options </td></tr>
</table>
</span>
</p>
</div>
<div class="function dialogmodule" title="setInfoMessage"><a name="setInfoMessage"></a>
<p class="title"><span class="function">setInfoMessage(message)</span> Sets info message (Used to display waiting information like 32% done for example)</p>
<p class="parameter">
<span class="field">message</span>
<span class="explanation">New info message</span>
</p>
</div>
<div class="function dialogmodule" title="closeInfo"><a name="closeInfo"></a>
<p class="title"><span class="function">closeInfo()</span> Closes the current modal dialog</p>
</div>
<div style="clear:both"></div>
<h2> Windows</h2>
Windows factory. Handles created windows, and windows observers<br/><br/>
<div class="function windows" title="addObserver"><a name="addObserver"></a>
<p class="title"><span class="function">addObserver(observer)</span> Registers a new windows observer. Should be able to respond to onStartResize(), onEndResize(), onStartMove(), onEndMove(), onClose(), onDestroy(), onMaximize(), onMinimize(), onFocus(), onHide(), onShow() functions</p>
<p class="parameter">
<span class="field">observer</span>
<span class="explanation">Observer object</span>
</p>
</div>
<div class="function windows" title="removeObserver"><a name="removeObserver"></a>
<p class="title"><span class="function">removeObserver(observer)</span> Unregisters a windows observer. </p>
<p class="parameter">
<span class="field">observer</span>
<span class="explanation">Observer object</span>
</p>
</div>
<div class="function windows" title="closeAll"><a name="closeAll"></a>
<p class="title"><span class="function">closeAll()</span> Closes all closeable windows. </p>
</div>
<div class="function windows" title="getFocusedWindow"><a name="getFocusedWindow"></a>
<p class="title"><span class="function">getFocusedWindow()</span> Returns the last focused window. </p>
</div>
</div>
</body>
</html> |
<?php
namespace Symfony\CS\Fixer\Symfony;
use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
final class <API key> extends AbstractFixer
{
/**
* {@inheritdoc}
*/
public function isCandidate(Tokens $tokens)
{
return $tokens->isTokenKindFound(';');
}
/**
* {@inheritdoc}
*/
public function fix(\SplFileInfo $file, Tokens $tokens)
{
$limit = $tokens->count();
for ($index = 0; $index < $limit; ++$index) {
$token = $tokens[$index];
// skip T_FOR parenthesis to ignore duplicated `;` like `for ($i = 1; ; ++$i) {...}`
if ($token->isGivenKind(T_FOR)) {
$index = $tokens-><API key>($index);
$index = $tokens->findBlockEnd(Tokens::<API key>, $index);
continue;
}
if (!$token->equals(';')) {
continue;
}
$prevIndex = $tokens-><API key>($index);
if (!$tokens[$prevIndex]->equals(';')) {
continue;
}
$tokens-><API key>($index);
$token->clear();
}
}
/**
* {@inheritdoc}
*/
public function getDescription()
{
return 'Remove duplicated semicolons.';
}
/**
* {@inheritdoc}
*/
public function getPriority()
{
// should be run before the BracesFixer, <API key> and <API key>
return 10;
}
} |
require 'test_helper'
class <API key> < ActionController::TestCase
# test "the truth" do
# assert true
# end
end |
import Helper, { states } from './_helper';
import { module, test } from 'qunit';
module('Integration | ORM | Has Many | Basic | accessor', {
beforeEach() {
this.helper = new Helper();
}
});
/*
The reference to a belongs-to association is correct, for all states
*/
states.forEach((state) => {
test(`the references of a ${state} are correct`, function(assert) {
let [ user, posts ] = this.helper[state]();
assert.equal(user.posts.models.length, posts.length, 'the parent has the correct number of children');
assert.equal(user.postIds.length, posts.length, 'the parent has the correct number of children ids');
posts.forEach((post, i) => {
assert.deepEqual(user.posts.models[i], posts[i], 'each child is in parent.children array');
if (post.isSaved()) {
assert.ok(user.postIds.indexOf(post.id) > -1, 'each saved child id is in parent.childrenIds array');
}
});
});
}); |
<?php
namespace Oro\Bundle\ConfigBundle\Tests\Behat\Element;
use Behat\Mink\Element\NodeElement;
use Oro\Bundle\TestFrameworkBundle\Behat\Element\Element;
class SidebarConfigMenu extends Element
{
public function clickLink($locator)
{
$this->find('css', 'a[data-action="accordion:expand-all"]')->click();
$link = $this->findLink($locator);
$link->waitFor(60, function (NodeElement $link) {
return $link->isVisible();
});
$link->click();
}
} |
#!/bin/bash
# this script downloads the reference genome of Plasmodium falciparum from the Sanger centre
wget -O ../data/Pf3D7_v2.1.5.fasta ftp://ftp.sanger.ac.uk/pub/project/pathogens/Plasmodium/falciparum/3D7/3D7.version2.1.5/Pf3D7_v2.1.5.fasta |
var <API key> =
[
[ "RollAttributes", "<API key>.html#<API key>", null ],
[ "RollAttributes", "<API key>.html#<API key>", null ],
[ "ToString", "<API key>.html#<API key>", null ],
[ "ToString", "<API key>.html#<API key>", null ],
[ "Roll1", "<API key>.html#<API key>", null ],
[ "Roll2", "<API key>.html#<API key>", null ],
[ "Roll3", "<API key>.html#<API key>", null ]
]; |
# NOTICE: THIS FILE IS AUTOGENERATED
# MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
# PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/chassis/<API key>.iff"
result.<API key> = 8
result.stfName("space_crafting_n","tieinterceptor_deed")
return result |
code[class*="language-"],
pre[class*="language-"] {
font-family: Consolas, Menlo, Monaco, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", "Courier New", Courier, monospace;
font-size: 14px;
line-height: 1.375;
direction: ltr;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
background: #fafaf9;
color: #499fbc;
}
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
text-shadow: none;
background: #fafaf9;
}
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
text-shadow: none;
background: #fafaf9;
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: #c2c1b7;
}
.token.punctuation {
color: #c2c1b7;
}
.token.namespace {
opacity: .7;
}
.token.tag,
.token.operator,
.token.number {
color: #2f7289;
}
.token.property,
.token.function {
color: #b7a21a;
}
.token.tag-id,
.token.selector,
.token.atrule-id {
color: #84740b;
}
code.language-javascript,
.token.attr-name {
color: #b7a21a;
}
code.language-css,
code.language-scss,
.token.boolean,
.token.string,
.token.entity,
.token.url,
.language-css .token.string,
.language-scss .token.string,
.style .token.string,
.token.attr-value,
.token.keyword,
.token.control,
.token.directive,
.token.unit,
.token.statement,
.token.regex,
.token.atrule {
color: #3e91ac;
}
.token.placeholder,
.token.variable {
color: #7dc2d9;
}
.token.deleted {
text-decoration: line-through;
}
.token.inserted {
border-bottom: 1px dotted #84740b;
text-decoration: none;
}
.token.italic {
font-style: italic;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.important {
color: #b7a21a;
}
.token.entity {
cursor: help;
}
pre > code.highlight {
outline: .4em solid #b7a21a;
outline-offset: .4em;
}
.line-numbers .line-numbers-rows {
border-right-color: #e8e7e3;
}
.line-numbers-rows > span:before {
color: #d5d4cd;
}
.line-highlight {
background: #84740b33;
background: linear-gradient(to right, #84740b33 70%, #84740b00);
} |
const babel = require('rollup-plugin-babel');
const commonjs = require('<API key>');
const createBanner = require('create-banner');
const nodeResolve = require('<API key>');
const pkg = require('./package');
pkg.name = pkg.name.replace(/^.+\
const banner = createBanner({
case: 'PascalCase',
data: {
year: '2014-present',
},
});
module.exports = {
input: 'src/index.js',
output: [
{
banner,
file: `dist/${pkg.name}.js`,
format: 'umd',
globals: {
jquery: 'jQuery',
},
},
{
banner,
file: `dist/${pkg.name}.common.js`,
format: 'cjs',
},
{
banner,
file: `dist/${pkg.name}.esm.js`,
format: 'esm',
},
{
banner,
file: `docs/js/${pkg.name}.js`,
format: 'umd',
globals: {
jquery: 'jQuery',
},
},
],
external: ['jquery'],
plugins: [
nodeResolve(),
commonjs(),
babel(),
],
}; |
(function($) {
FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
'en_US': {
lessThan: {
'default': 'Please enter a value less than or equal to %s',
notInclusive: 'Please enter a value less than %s'
}
}
});
FormValidation.Validator.lessThan = {
html5Attributes: {
message: 'message',
value: 'value',
inclusive: 'inclusive'
},
enableByHtml5: function($field) {
var type = $field.attr('type'),
max = $field.attr('max');
if (max && type !== 'date') {
return {
value: max
};
}
return false;
},
/**
* Return true if the input value is less than or equal to given number
*
* @param {FormValidation.Base} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following keys:
* - value: The number used to compare to. It can be
* - A number
* - Name of field which its value defines the number
* - Name of callback function that returns the number
* - A callback function that returns the number
*
* - inclusive [optional]: Can be true or false. Default is true
* - message: The invalid message
* @returns {Boolean|Object}
*/
validate: function(validator, $field, options) {
var value = validator.getFieldValue($field, 'lessThan');
if (value === '') {
return true;
}
value = this._format(value);
if (!$.isNumeric(value)) {
return false;
}
var locale = validator.getLocale(),
compareTo = $.isNumeric(options.value) ? options.value : validator.getDynamicOption($field, options.value),
compareToValue = this._format(compareTo);
value = parseFloat(value);
return (options.inclusive === true || options.inclusive === undefined)
? {
valid: value <= compareToValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan['default'], compareTo)
}
: {
valid: value < compareToValue,
message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan.notInclusive, compareTo)
};
},
_format: function(value) {
return (value + '').replace(',', '.');
}
};
}(jQuery)); |
/**
* @file SmallBox.java
* @author Valery Samovich
* @version 1.0.0
* @date 11/22/2014
*/
package org.samovich.technologies.basics.concepts.classes.constructors.box;
public class SmallBox {
int length;
int width;
/*
* Constructor Method:
* 1. constructor is a method that has the same name as the class.
* 2. It is executed when an object is created.
* 3. It is used to set default values.
* 4. does not return anything including void.
*/
SmallBox(){
this.length = 5;
this.width = 6;
System.out.println("Constructor fired!");
}
// Constructor Method with parameters.
SmallBox(int length, int width){
this.length = length;
this.width = width;
}
void calculateArea(){
System.out.println("Area = " + (length * width));
}
} |
package main
import (
"log"
"net/http"
"os"
"github.com/go-sql-driver/mysql"
"github.com/murder-hobos/murder-hobos/routes"
)
func main() {
// setup DB
dbconfig := mysql.Config{
User: os.Getenv("MYSQL_USER"),
Passwd: os.Getenv("MYSQL_PASS"),
DBName: os.Getenv("MYSQL_DB_NAME"),
Net: "tcp",
Addr: os.Getenv("MYSQL_ADDR"),
MultiStatements: false,
}
log.Println(dbconfig.FormatDSN())
r := routes.New(dbconfig.FormatDSN())
port := os.Getenv("PORT")
log.Fatal(http.ListenAndServe(":"+port, r))
} |
class CreateContacts < ActiveRecord::Migration
def self.up
create_table :contacts do |t|
t.string :first_name
t.string :last_name
t.string :email_address
t.string :phone_number
t.integer :client_id
t.timestamps
end
end
def self.down
drop_table :contacts
end
end |
<?php
namespace Oro\Bundle\ApiBundle\Processor\Config\Shared\MergeConfig;
use Oro\Bundle\ApiBundle\Util\ConfigUtil;
class <API key>
{
/**
* @param array $config
* @param array $filtersConfig
*
* @return array
*/
public function mergeFiltersConfig(array $config, array $filtersConfig)
{
if (ConfigUtil::isExcludeAll($filtersConfig) || !array_key_exists(ConfigUtil::FILTERS, $config)) {
$config[ConfigUtil::FILTERS] = $filtersConfig;
} elseif (!empty($filtersConfig[ConfigUtil::FIELDS])) {
if (!array_key_exists(ConfigUtil::FIELDS, $config[ConfigUtil::FILTERS])) {
$config[ConfigUtil::FILTERS][ConfigUtil::FIELDS] = $filtersConfig[ConfigUtil::FIELDS];
} else {
$config[ConfigUtil::FILTERS][ConfigUtil::FIELDS] = array_merge(
$config[ConfigUtil::FILTERS][ConfigUtil::FIELDS],
$filtersConfig[ConfigUtil::FIELDS]
);
}
}
return $config;
}
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>CodeMirror: Compression Helper</title>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
<link rel="stylesheet" type="text/css" href="docs.css"/>
</head>
<body>
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
<div class="grey">
<img src="baboon.png" class="logo" alt="logo"/>
<pre>
/* Script compression
helper */
</pre>
</div>
<p>To optimize loading CodeMirror, especially when including a
bunch of different modes, it is recommended that you combine and
minify (and preferably also gzip) the scripts. This page makes
those first two steps very easy. Simply select the version and
scripts you need in the form below, and
click <strong>Compress</strong> to download the minified script
file.</p>
<form id="form" action="http://marijnhaverbeke.nl/uglifyjs" method="post">
<input type="hidden" id="download" name="download" value="<API key>.js"/>
<p>Version: <select id="version" onchange="setVersion(this);" style="padding: 1px">
<option value="http://codemirror.net/">HEAD</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.02;f=">3.02</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.01;f=">3.01</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v3.0;f=">3.0</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.38;f=">2.38</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.37;f=">2.37</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.36;f=">2.36</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.35;f=">2.35</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.34;f=">2.34</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.33;f=">2.33</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.32;f=">2.32</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.31;f=">2.31</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.3;f=">2.3</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.25;f=">2.25</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.24;f=">2.24</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.23;f=">2.23</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.22;f=">2.22</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.21;f=">2.21</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.2;f=">2.2</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.18;f=">2.18</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.16;f=">2.16</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.15;f=">2.15</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.13;f=">2.13</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.12;f=">2.12</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.11;f=">2.11</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.1;f=">2.1</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.02;f=">2.02</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.01;f=">2.01</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=v2.0;f=">2.0</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta2;f=">beta2</option>
<option value="http://marijnhaverbeke.nl/git/codemirror?a=blob_plain;hb=beta1;f=">beta1</option>
</select></p>
<select multiple="multiple" size="20" name="code_url" style="width: 40em;" class="field" id="files">
<optgroup label="CodeMirror Library">
<option value="http://codemirror.net/lib/codemirror.js" selected>codemirror.js</option>
</optgroup>
<optgroup label="Modes">
<option value="http://codemirror.net/mode/apl/apl.js">apl.js</option>
<option value="http://codemirror.net/mode/clike/clike.js">clike.js</option>
<option value="http://codemirror.net/mode/clojure/clojure.js">clojure.js</option>
<option value="http://codemirror.net/mode/coffeescript/coffeescript.js">coffeescript.js</option>
<option value="http://codemirror.net/mode/commonlisp/commonlisp.js">commonlisp.js</option>
<option value="http://codemirror.net/mode/css/css.js">css.js</option>
<option value="http://codemirror.net/mode/d/d.js">d.js</option>
<option value="http://codemirror.net/mode/diff/diff.js">diff.js</option>
<option value="http://codemirror.net/mode/ecl/ecl.js">ecl.js</option>
<option value="http://codemirror.net/mode/erlang/erlang.js">erlang.js</option>
<option value="http://codemirror.net/mode/gfm/gfm.js">gfm.js</option>
<option value="http://codemirror.net/mode/go/go.js">go.js</option>
<option value="http://codemirror.net/mode/groovy/groovy.js">groovy.js</option>
<option value="http://codemirror.net/mode/haskell/haskell.js">haskell.js</option>
<option value="http://codemirror.net/mode/haxe/haxe.js">haxe.js</option>
<option value="http://codemirror.net/mode/htmlembedded/htmlembedded.js">htmlembedded.js</option>
<option value="http://codemirror.net/mode/htmlmixed/htmlmixed.js">htmlmixed.js</option>
<option value="http://codemirror.net/mode/http/http.js">http.js</option>
<option value="http://codemirror.net/mode/javascript/javascript.js">javascript.js</option>
<option value="http://codemirror.net/mode/jinja2/jinja2.js">jinja2.js</option>
<option value="http://codemirror.net/mode/less/less.js">less.js</option>
<option value="http://codemirror.net/mode/lua/lua.js">lua.js</option>
<option value="http://codemirror.net/mode/markdown/markdown.js">markdown.js</option>
<option value="http://codemirror.net/mode/mysql/mysql.js">mysql.js</option>
<option value="http://codemirror.net/mode/ntriples/ntriples.js">ntriples.js</option>
<option value="http://codemirror.net/mode/ocaml/ocaml.js">ocaml.js</option>
<option value="http://codemirror.net/mode/pascal/pascal.js">pascal.js</option>
<option value="http://codemirror.net/mode/perl/perl.js">perl.js</option>
<option value="http://codemirror.net/mode/php/php.js">php.js</option>
<option value="http://codemirror.net/mode/pig/pig.js">pig.js</option>
<option value="http://codemirror.net/mode/plsql/plsql.js">plsql.js</option>
<option value="http://codemirror.net/mode/properties/properties.js">properties.js</option>
<option value="http://codemirror.net/mode/python/python.js">python.js</option>
<option value="http://codemirror.net/mode/r/r.js">r.js</option>
<option value="http://codemirror.net/mode/rpm/changes/changes.js">rpm/changes.js</option>
<option value="http://codemirror.net/mode/rpm/spec/spec.js">rpm/spec.js</option>
<option value="http://codemirror.net/mode/rst/rst.js">rst.js</option>
<option value="http://codemirror.net/mode/ruby/ruby.js">ruby.js</option>
<option value="http://codemirror.net/mode/rust/rust.js">rust.js</option>
<option value="http://codemirror.net/mode/sass/sass.js">sass.js</option>
<option value="http://codemirror.net/mode/scala/scala.js">scala.js</option>
<option value="http://codemirror.net/mode/scheme/scheme.js">scheme.js</option>
<option value="http://codemirror.net/mode/shell/shell.js">shell.js</option>
<option value="http://codemirror.net/mode/sieve/sieve.js">sieve.js</option>
<option value="http://codemirror.net/mode/smalltalk/smalltalk.js">smalltalk.js</option>
<option value="http://codemirror.net/mode/smarty/smarty.js">smarty.js</option>
<option value="http://codemirror.net/mode/sql/sql.js">sql.js</option>
<option value="http://codemirror.net/mode/sparql/sparql.js">sparql.js</option>
<option value="http://codemirror.net/mode/stex/stex.js">stex.js</option>
<option value="http://codemirror.net/mode/tiddlywiki/tiddlywiki.js">tiddlywiki.js</option>
<option value="http://codemirror.net/mode/tiki/tiki.js">tiki.js</option>
<option value="http://codemirror.net/mode/turtle/turtle.js">turtle.js</option>
<option value="http://codemirror.net/mode/vb/vb.js">vb.js</option>
<option value="http://codemirror.net/mode/vbscript/vbscript.js">vbscript.js</option>
<option value="http://codemirror.net/mode/velocity/velocity.js">velocity.js</option>
<option value="http://codemirror.net/mode/verilog/verilog.js">verilog.js</option>
<option value="http://codemirror.net/mode/xml/xml.js">xml.js</option>
<option value="http://codemirror.net/mode/xquery/xquery.js">xquery.js</option>
<option value="http://codemirror.net/mode/yaml/yaml.js">yaml.js</option>
<option value="http://codemirror.net/mode/z80/z80.js">z80.js</option>
</optgroup>
<optgroup label="Add-ons">
<option value="http://codemirror.net/addon/dialog/dialog.js">dialog.js</option>
<option value="http://codemirror.net/addon/edit/closetag.js">closetag.js</option>
<option value="http://codemirror.net/addon/edit/continuecomment.js">continuecomment.js</option>
<option value="http://codemirror.net/addon/edit/continuelist.js">continuelist.js</option>
<option value="http://codemirror.net/addon/edit/matchbrackets.js">matchbrackets.js</option>
<option value="http://codemirror.net/addon/fold/foldcode.js">foldcode.js</option>
<option value="http://codemirror.net/addon/fold/collapserange.js">collapserange.js</option>
<option value="http://codemirror.net/addon/format/formatting.js">formatting.js</option>
<option value="http://codemirror.net/addon/hint/simple-hint.js">simple-hint.js</option>
<option value="http://codemirror.net/addon/hint/javascript-hint.js">javascript-hint.js</option>
<option value="http://codemirror.net/addon/hint/xml-hint.js">xml-hint.js</option>
<option value="http://codemirror.net/addon/hint/pig-hint.js">pig-hint.js</option>
<option value="http://codemirror.net/addon/hint/python-hint.js">python-hint.js</option>
<option value="http://codemirror.net/addon/mode/loadmode.js">loadmode.js</option>
<option value="http://codemirror.net/addon/mode/overlay.js">overlay.js</option>
<option value="http://codemirror.net/addon/mode/multiplex.js">multiplex.js</option>
<option value="http://codemirror.net/addon/runmode/colorize.js">colorize.js</option>
<option value="http://codemirror.net/addon/runmode/runmode.js">runmode.js</option>
<option value="http://codemirror.net/addon/runmode/runmode-standalone.js">runmode-standalone.js</option>
<option value="http://codemirror.net/addon/runmode/runmode.node.js">runmode.node.js</option>
<option value="http://codemirror.net/addon/search/search.js">search.js</option>
<option value="http://codemirror.net/addon/search/searchcursor.js">searchcursor.js</option>
<option value="http://codemirror.net/addon/search/match-highlighter.js">match-highlighter.js</option>
<option value="http://codemirror.net/addon/selection/mark-selection.js">mark-selection.js</option>
<option value="http://codemirror.net/addon/selection/active-line.js">active-line.js</option>
</optgroup>
<optgroup label="Keymaps">
<option value="http://codemirror.net/keymap/emacs.js">emacs.js</option>
<option value="http://codemirror.net/keymap/vim.js">vim.js</option>
</optgroup>
</select></p>
<p>
<button type="submit">Compress</button> with <a href="http://github.com/mishoo/UglifyJS/">UglifyJS</a>
</p>
<p>Custom code to add to the compressed file:<textarea name="js_code" style="width: 100%; height: 15em;" class="field"></textarea></p>
</form>
<script type="text/javascript">
function setVersion(ver) {
var urlprefix = ver.options[ver.selectedIndex].value;
var select = document.getElementById("files"), m;
for (var optgr = select.firstChild; optgr; optgr = optgr.nextSibling)
for (var opt = optgr.firstChild; opt; opt = opt.nextSibling) {
if (opt.nodeName != "OPTION")
continue;
else if (m = opt.value.match(/^http:\/\/codemirror.net\/(.*)$/))
opt.value = urlprefix + m[1];
else if (m = opt.value.match(/http:\/\/marijnhaverbeke.nl\/git\/codemirror\?a=blob_plain;hb=[^;]+;f=(.*)$/))
opt.value = urlprefix + m[1];
}
}
</script>
</body>
</html> |
<!DOCTYPE html>
<html>
<head>
<title>webpack Example</title>
<script src="main.js"></script>
</head>
<body>
</body>
</html> |
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
}
/* .esri-legend {
bottom: 20px;
left: 20px;
right: 20px;
height: 150px;
} */
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.7/esri/css/main.css">
<script src="https://js.arcgis.com/4.7"></script>
<script type="text/javascript">
require([
"esri/Map",
"esri/views/MapView"
], function (Map, MapView) {
const view = new MapView({
ui: {
// padding: {
// top: 100,
// left: 100,
// right: 100,
components: ["zoom", "compass", "attribution"]
},
container: "viewDiv",
map: new Map({
basemap: "topo"
}),
center: [-116.5, 33.80],
scale: 50000
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html> |
package com.mb3364.twitch.api.models;
import com.fasterxml.jackson.annotation.<API key>;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
@<API key>(ignoreUnknown = true)
public class Team {
@JsonProperty("_id")
private long id;
private String name;
private String info;
private String displayName;
private Date createdAt;
private Date updatedAt;
private String logo;
private String banner;
private String background;
public static boolean isNullOrEmpty(Team team) {
return team == null || team.equals(new Team());
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBanner() {
return banner;
}
public void setBanner(String banner) {
this.banner = banner;
}
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Team team = (Team) o;
return id == team.id;
}
@Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", info='" + info + '\'' +
", displayName='" + displayName + '\'' +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt +
", logo='" + logo + '\'' +
", banner='" + banner + '\'' +
", background='" + background + '\'' +
'}';
}
} |
Given(/^I am looking for a puppy to adopt$/) do
@browser.goto 'http://puppies.herokuapp.com'
end
And(/^I adopt puppy (\d+)$/) do |puppy_number|
index = (puppy_number.to_i)-1
@browser.button(:value => 'View Details', :index => index).click
@browser.button(:value => 'Adopt Me!').click
end
And(/^I complete the adoption$/) do
@browser.button(:value => 'Complete the Adoption').click
end
And(/^I adopt another puppy$/) do
@browser.button(:value => 'Adopt Another Puppy').click
end
Then(/^I should see the message "([^"]*)"$/) do |expected_message|
expect(@browser.text).to include expected_message
end
And(/^I checkout with:$/) do |checkout_data_table|
checkout_data = checkout_data_table.hashes.first
@browser.text_field(:id => 'order_name').set(checkout_data["name"])
@browser.textarea(:id => 'order_address').set(checkout_data["address"])
@browser.text_field(:id => 'order_email').set(checkout_data["email"])
@browser.select(:id => 'order_pay_type').select(checkout_data["payment type"])
@browser.button(:value => 'Place Order').click
end
Then(/^I should see "([^"]*)" as the name for line item (\d+)$/) do |expected_name, line_item|
<API key> = (line_item.to_i - 1) * 6
line_item_first_row = @browser.table(:index => 0)[<API key>]
expect(line_item_first_row.text).to include expected_name
end
Then(/^I should see "([^"]*)" as the subtotal for line item (\d+)$/) do |expected_subtotal, line_item|
<API key> = (line_item.to_i - 1) * 6
item_price_cell = @browser.table[<API key>][3]
expect(item_price_cell.text).to eql expected_subtotal
end
Then(/^I should see "([^"]*)" as the total for the cart$/) do |expected_total|
total_cell = @browser.td(:class => 'total_cell')
expect(total_cell.text).to eql expected_total
end |
/* style_box.cpp */
/* This file is part of: */
/* GODOT ENGINE */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* included in all copies or substantial portions of the Software. */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "style_box.h"
#include <limits.h>
bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
return true;
}
void StyleBox::set_default_margin(Margin p_margin, float p_value) {
margin[p_margin] = p_value;
emit_changed();
}
float StyleBox::get_default_margin(Margin p_margin) const {
return margin[p_margin];
}
float StyleBox::get_margin(Margin p_margin) const {
if (margin[p_margin] < 0)
return get_style_margin(p_margin);
else
return margin[p_margin];
}
Size2 StyleBox::get_minimum_size() const {
return Size2(get_margin(MARGIN_LEFT) + get_margin(MARGIN_RIGHT), get_margin(MARGIN_TOP) + get_margin(MARGIN_BOTTOM));
}
Point2 StyleBox::get_offset() const {
return Point2(get_margin(MARGIN_LEFT), get_margin(MARGIN_TOP));
}
Size2 StyleBox::get_center_size() const {
return Size2();
}
void StyleBox::_bind_methods() {
ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask);
ClassDB::bind_method(D_METHOD("set_default_margin", "margin", "offset"), &StyleBox::set_default_margin);
ClassDB::bind_method(D_METHOD("get_default_margin", "margin"), &StyleBox::get_default_margin);
//ClassDB::bind_method(D_METHOD("set_default_margin"),&StyleBox::set_default_margin);
//ClassDB::bind_method(D_METHOD("get_default_margin"),&StyleBox::get_default_margin);
ClassDB::bind_method(D_METHOD("get_margin", "margin"), &StyleBox::get_margin);
ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size);
ClassDB::bind_method(D_METHOD("get_center_size"), &StyleBox::get_center_size);
ClassDB::bind_method(D_METHOD("get_offset"), &StyleBox::get_offset);
ClassDB::bind_method(D_METHOD("draw", "canvas_item", "rect"), &StyleBox::draw);
ADD_GROUP("Content Margin", "content_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "<API key>", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_TOP);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "<API key>", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_BOTTOM);
}
StyleBox::StyleBox() {
for (int i = 0; i < 4; i++) {
margin[i] = -1;
}
}
void StyleBoxTexture::set_texture(RES p_texture) {
if (texture == p_texture)
return;
texture = p_texture;
region_rect = Rect2(Point2(), texture->get_size());
emit_signal("texture_changed");
emit_changed();
_change_notify("texture");
}
RES StyleBoxTexture::get_texture() const {
return texture;
}
void StyleBoxTexture::set_normal_map(RES p_normal_map) {
if (normal_map == p_normal_map)
return;
normal_map = p_normal_map;
emit_changed();
}
RES StyleBoxTexture::get_normal_map() const {
return normal_map;
}
void StyleBoxTexture::set_margin_size(Margin p_margin, float p_size) {
margin[p_margin] = p_size;
emit_changed();
}
float StyleBoxTexture::get_margin_size(Margin p_margin) const {
return margin[p_margin];
}
float StyleBoxTexture::get_style_margin(Margin p_margin) const {
return margin[p_margin];
}
void StyleBoxTexture::draw(RID p_canvas_item, const Rect2 &p_rect) const {
if (texture.is_null())
return;
Rect2 rect = p_rect;
Rect2 src_rect = region_rect;
texture->get_rect_region(rect, src_rect, rect, src_rect);
rect.position.x -= expand_margin[MARGIN_LEFT];
rect.position.y -= expand_margin[MARGIN_TOP];
rect.size.x += expand_margin[MARGIN_LEFT] + expand_margin[MARGIN_RIGHT];
rect.size.y += expand_margin[MARGIN_TOP] + expand_margin[MARGIN_BOTTOM];
RID normal_rid;
if (normal_map.is_valid())
normal_rid = normal_map->get_rid();
VisualServer::get_singleton()-><API key>(p_canvas_item, rect, src_rect, texture->get_rid(), Vector2(margin[MARGIN_LEFT], margin[MARGIN_TOP]), Vector2(margin[MARGIN_RIGHT], margin[MARGIN_BOTTOM]), VS::NinePatchAxisMode(axis_h), VS::NinePatchAxisMode(axis_v), draw_center, modulate, normal_rid);
}
void StyleBoxTexture::set_draw_center(bool p_enabled) {
draw_center = p_enabled;
emit_changed();
}
bool StyleBoxTexture::<API key>() const {
return draw_center;
}
Size2 StyleBoxTexture::get_center_size() const {
if (texture.is_null())
return Size2();
return texture->get_size() - get_minimum_size();
}
void StyleBoxTexture::<API key>(Margin p_expand_margin, float p_size) {
ERR_FAIL_INDEX(p_expand_margin, 4);
expand_margin[p_expand_margin] = p_size;
emit_changed();
}
void StyleBoxTexture::<API key>(float p_left, float p_top, float p_right, float p_bottom) {
expand_margin[MARGIN_LEFT] = p_left;
expand_margin[MARGIN_TOP] = p_top;
expand_margin[MARGIN_RIGHT] = p_right;
expand_margin[MARGIN_BOTTOM] = p_bottom;
emit_changed();
}
void StyleBoxTexture::<API key>(float <API key>) {
for (int i = 0; i < 4; i++) {
expand_margin[i] = <API key>;
}
emit_changed();
}
float StyleBoxTexture::<API key>(Margin p_expand_margin) const {
ERR_FAIL_INDEX_V(p_expand_margin, 4, 0);
return expand_margin[p_expand_margin];
}
void StyleBoxTexture::set_region_rect(const Rect2 &p_region_rect) {
if (region_rect == p_region_rect)
return;
region_rect = p_region_rect;
emit_changed();
}
Rect2 StyleBoxTexture::get_region_rect() const {
return region_rect;
}
void StyleBoxTexture::<API key>(AxisStretchMode p_mode) {
axis_h = p_mode;
emit_changed();
}
StyleBoxTexture::AxisStretchMode StyleBoxTexture::<API key>() const {
return axis_h;
}
void StyleBoxTexture::<API key>(AxisStretchMode p_mode) {
axis_v = p_mode;
emit_changed();
}
StyleBoxTexture::AxisStretchMode StyleBoxTexture::<API key>() const {
return axis_v;
}
void StyleBoxTexture::set_modulate(const Color &p_modulate) {
if (modulate == p_modulate)
return;
modulate = p_modulate;
emit_changed();
}
Color StyleBoxTexture::get_modulate() const {
return modulate;
}
void StyleBoxTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &StyleBoxTexture::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &StyleBoxTexture::get_texture);
ClassDB::bind_method(D_METHOD("set_normal_map", "normal_map"), &StyleBoxTexture::set_normal_map);
ClassDB::bind_method(D_METHOD("get_normal_map"), &StyleBoxTexture::get_normal_map);
ClassDB::bind_method(D_METHOD("set_margin_size", "margin", "size"), &StyleBoxTexture::set_margin_size);
ClassDB::bind_method(D_METHOD("get_margin_size", "margin"), &StyleBoxTexture::get_margin_size);
ClassDB::bind_method(D_METHOD("<API key>", "margin", "size"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "size"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "size_left", "size_top", "size_right", "size_bottom"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "margin"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("set_region_rect", "region"), &StyleBoxTexture::set_region_rect);
ClassDB::bind_method(D_METHOD("get_region_rect"), &StyleBoxTexture::get_region_rect);
ClassDB::bind_method(D_METHOD("set_draw_center", "enable"), &StyleBoxTexture::set_draw_center);
ClassDB::bind_method(D_METHOD("<API key>"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("set_modulate", "color"), &StyleBoxTexture::set_modulate);
ClassDB::bind_method(D_METHOD("get_modulate"), &StyleBoxTexture::get_modulate);
ClassDB::bind_method(D_METHOD("<API key>", "mode"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "mode"), &StyleBoxTexture::<API key>);
ClassDB::bind_method(D_METHOD("<API key>"), &StyleBoxTexture::<API key>);
ADD_SIGNAL(MethodInfo("texture_changed"));
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", <API key>, "Texture"), "set_texture", "get_texture");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal_map", <API key>, "Texture"), "set_normal_map", "get_normal_map");
ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
ADD_GROUP("Margin", "margin_");
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_TOP);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_BOTTOM);
ADD_GROUP("Expand Margin", "expand_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "<API key>", "<API key>", MARGIN_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "<API key>", "<API key>", MARGIN_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "<API key>", "<API key>", MARGIN_TOP);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "<API key>", PROPERTY_HINT_RANGE, "0,2048,1"), "<API key>", "<API key>", MARGIN_BOTTOM);
ADD_GROUP("Axis Stretch", "axis_stretch_");
ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "<API key>", "<API key>");
ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "<API key>", "<API key>");
ADD_GROUP("Modulate", "modulate_");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate_color"), "set_modulate", "get_modulate");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "<API key>");
BIND_ENUM_CONSTANT(<API key>);
BIND_ENUM_CONSTANT(<API key>);
BIND_ENUM_CONSTANT(<API key>);
}
StyleBoxTexture::StyleBoxTexture() {
for (int i = 0; i < 4; i++) {
margin[i] = 0;
expand_margin[i] = 0;
}
draw_center = true;
modulate = Color(1, 1, 1, 1);
axis_h = <API key>;
axis_v = <API key>;
}
StyleBoxTexture::~StyleBoxTexture() {
}
void StyleBoxFlat::set_bg_color(const Color &p_color) {
bg_color = p_color;
emit_changed();
}
Color StyleBoxFlat::get_bg_color() const {
return bg_color;
}
void StyleBoxFlat::<API key>(const Color &p_color) {
for (int i = 0; i < 4; i++) {
border_color.write()[i] = p_color;
}
emit_changed();
}
Color StyleBoxFlat::<API key>() const {
return border_color[MARGIN_TOP];
}
void StyleBoxFlat::set_border_color(Margin p_border, const Color &p_color) {
border_color.write()[p_border] = p_color;
emit_changed();
}
Color StyleBoxFlat::get_border_color(Margin p_border) const {
return border_color[p_border];
}
void StyleBoxFlat::<API key>(int p_size) {
border_width[0] = p_size;
border_width[1] = p_size;
border_width[2] = p_size;
border_width[3] = p_size;
emit_changed();
}
int StyleBoxFlat::<API key>() const {
return MIN(MIN(border_width[0], border_width[1]), MIN(border_width[2], border_width[3]));
}
void StyleBoxFlat::set_border_width(Margin p_margin, int p_width) {
border_width[p_margin] = p_width;
emit_changed();
}
int StyleBoxFlat::get_border_width(Margin p_margin) const {
return border_width[p_margin];
}
void StyleBoxFlat::set_border_blend(bool p_blend) {
blend_border = p_blend;
emit_changed();
}
bool StyleBoxFlat::get_border_blend() const {
return blend_border;
}
void StyleBoxFlat::<API key>(int radius) {
for (int i = 0; i < 4; i++) {
corner_radius[i] = radius;
}
emit_changed();
}
void StyleBoxFlat::<API key>(const int radius_top_left, const int radius_top_right, const int radius_botton_right, const int radius_bottom_left) {
corner_radius[0] = radius_top_left;
corner_radius[1] = radius_top_right;
corner_radius[2] = radius_botton_right;
corner_radius[3] = radius_bottom_left;
emit_changed();
}
int StyleBoxFlat::<API key>() const {
int smallest = corner_radius[0];
for (int i = 1; i < 4; i++) {
if (smallest > corner_radius[i]) {
smallest = corner_radius[i];
}
}
return smallest;
}
void StyleBoxFlat::set_corner_radius(const Corner p_corner, const int radius) {
corner_radius[p_corner] = radius;
emit_changed();
}
int StyleBoxFlat::get_corner_radius(const Corner p_corner) const {
return corner_radius[p_corner];
}
void StyleBoxFlat::<API key>(Margin p_expand_margin, float p_size) {
expand_margin[p_expand_margin] = p_size;
emit_changed();
}
void StyleBoxFlat::<API key>(float p_left, float p_top, float p_right, float p_bottom) {
expand_margin[MARGIN_LEFT] = p_left;
expand_margin[MARGIN_TOP] = p_top;
expand_margin[MARGIN_RIGHT] = p_right;
expand_margin[MARGIN_BOTTOM] = p_bottom;
emit_changed();
}
void StyleBoxFlat::<API key>(float <API key>) {
for (int i = 0; i < 4; i++) {
expand_margin[i] = <API key>;
}
emit_changed();
}
float StyleBoxFlat::<API key>(Margin p_expand_margin) const {
return expand_margin[p_expand_margin];
}
void StyleBoxFlat::set_draw_center(bool p_enabled) {
draw_center = p_enabled;
emit_changed();
}
bool StyleBoxFlat::<API key>() const {
return draw_center;
}
void StyleBoxFlat::set_shadow_color(const Color &p_color) {
shadow_color = p_color;
emit_changed();
}
Color StyleBoxFlat::get_shadow_color() const {
return shadow_color;
}
void StyleBoxFlat::set_shadow_size(const int &p_size) {
shadow_size = p_size;
emit_changed();
}
int StyleBoxFlat::get_shadow_size() const {
return shadow_size;
}
void StyleBoxFlat::set_anti_aliased(const bool &p_anti_aliased) {
anti_aliased = p_anti_aliased;
emit_changed();
}
bool StyleBoxFlat::is_anti_aliased() const {
return anti_aliased;
}
void StyleBoxFlat::set_aa_size(const int &p_aa_size) {
aa_size = CLAMP(p_aa_size, 1, 5);
emit_changed();
}
int StyleBoxFlat::get_aa_size() const {
return aa_size;
}
void StyleBoxFlat::set_corner_detail(const int &p_corner_detail) {
corner_detail = CLAMP(p_corner_detail, 1, 128);
emit_changed();
}
int StyleBoxFlat::get_corner_detail() const {
return corner_detail;
}
Size2 StyleBoxFlat::get_center_size() const {
return Size2();
}
inline void <API key>(const Rect2 style_rect, const Rect2 inner_rect, const int corner_radius[4], int *inner_corner_radius) {
int border_left = inner_rect.position.x - style_rect.position.x;
int border_top = inner_rect.position.y - style_rect.position.y;
int border_right = style_rect.size.width - inner_rect.size.width - border_left;
int border_bottom = style_rect.size.height - inner_rect.size.height - border_top;
int rad;
rad = MIN(border_top, border_left);
inner_corner_radius[0] = MAX(corner_radius[0] - rad, 0);
rad = MIN(border_top, border_bottom);
inner_corner_radius[1] = MAX(corner_radius[1] - rad, 0);
rad = MIN(border_bottom, border_right);
inner_corner_radius[2] = MAX(corner_radius[2] - rad, 0);
rad = MIN(border_bottom, border_left);
inner_corner_radius[3] = MAX(corner_radius[3] - rad, 0);
}
inline void draw_ring(Vector<Vector2> &verts, Vector<int> &indices, Vector<Color> &colors, const Rect2 style_rect, const int corner_radius[4],
const Rect2 ring_rect, const int border_width[4], const Color inner_color[4], const Color outer_color[4], const int corner_detail) {
int vert_offset = verts.size();
if (!vert_offset) {
vert_offset = 0;
}
int <API key> = (corner_radius[0] == 0 && corner_radius[1] == 0 && corner_radius[2] == 0 && corner_radius[3] == 0) ? 1 : corner_detail;
int rings = (border_width[0] == 0 && border_width[1] == 0 && border_width[2] == 0 && border_width[3] == 0) ? 1 : 2;
rings = 2;
int ring_corner_radius[4];
<API key>(style_rect, ring_rect, corner_radius, ring_corner_radius);
//corner radius center points
Vector<Point2> outer_points;
outer_points.push_back(ring_rect.position + Vector2(ring_corner_radius[0], ring_corner_radius[0]));
outer_points.push_back(Point2(ring_rect.position.x + ring_rect.size.x - ring_corner_radius[1], ring_rect.position.y + ring_corner_radius[1]));
outer_points.push_back(ring_rect.position + ring_rect.size - Vector2(ring_corner_radius[2], ring_corner_radius[2]));
outer_points.push_back(Point2(ring_rect.position.x + ring_corner_radius[3], ring_rect.position.y + ring_rect.size.y - ring_corner_radius[3]));
Rect2 inner_rect;
inner_rect = ring_rect.grow_individual(-border_width[MARGIN_LEFT], -border_width[MARGIN_TOP], -border_width[MARGIN_RIGHT], -border_width[MARGIN_BOTTOM]);
int inner_corner_radius[4];
Vector<Point2> inner_points;
<API key>(style_rect, inner_rect, corner_radius, inner_corner_radius);
inner_points.push_back(inner_rect.position + Vector2(inner_corner_radius[0], inner_corner_radius[0]));
inner_points.push_back(Point2(inner_rect.position.x + inner_rect.size.x - inner_corner_radius[1], inner_rect.position.y + inner_corner_radius[1]));
inner_points.push_back(inner_rect.position + inner_rect.size - Vector2(inner_corner_radius[2], inner_corner_radius[2]));
inner_points.push_back(Point2(inner_rect.position.x + inner_corner_radius[3], inner_rect.position.y + inner_rect.size.y - inner_corner_radius[3]));
//calculate the vert array
for (int corner_index = 0; corner_index < 4; corner_index++) {
for (int detail = 0; detail <= <API key>; detail++) {
for (int inner_outer = (2 - rings); inner_outer < 2; inner_outer++) {
float radius;
Color color;
Point2 corner_point;
if (inner_outer == 0) {
radius = inner_corner_radius[corner_index];
color = *inner_color;
corner_point = inner_points[corner_index];
} else {
radius = ring_corner_radius[corner_index];
color = *outer_color;
corner_point = outer_points[corner_index];
}
float x = radius * (float)cos((double)corner_index * Math_PI / 2.0 + (double)detail / (double)<API key> * Math_PI / 2.0 + Math_PI) + corner_point.x;
float y = radius * (float)sin((double)corner_index * Math_PI / 2.0 + (double)detail / (double)<API key> * Math_PI / 2.0 + Math_PI) + corner_point.y;
verts.push_back(Vector2(x, y));
colors.push_back(color);
}
}
}
if (rings == 2) {
int vert_count = (<API key> + 1) * 4 * rings;
//fill the indices and the colors for the border
for (int i = 0; i < vert_count; i++) {
//poly 1
indices.push_back(vert_offset + ((i + 0) % vert_count));
indices.push_back(vert_offset + ((i + 2) % vert_count));
indices.push_back(vert_offset + ((i + 1) % vert_count));
//poly 2
indices.push_back(vert_offset + ((i + 1) % vert_count));
indices.push_back(vert_offset + ((i + 2) % vert_count));
indices.push_back(vert_offset + ((i + 3) % vert_count));
}
}
}
inline void adapt_values(int p_index_a, int p_index_b, int *adapted_values, const int *p_values, const real_t p_width, const int p_max_a, const int p_max_b) {
if (p_values[p_index_a] + p_values[p_index_b] > p_width) {
float factor;
int newValue;
factor = (float)p_width / (float)(p_values[p_index_a] + p_values[p_index_b]);
newValue = (int)(p_values[p_index_a] * factor);
if (newValue < adapted_values[p_index_a]) {
adapted_values[p_index_a] = newValue;
}
newValue = (int)(p_values[p_index_b] * factor);
if (newValue < adapted_values[p_index_b]) {
adapted_values[p_index_b] = newValue;
}
} else {
adapted_values[p_index_a] = MIN(p_values[p_index_a], adapted_values[p_index_a]);
adapted_values[p_index_b] = MIN(p_values[p_index_b], adapted_values[p_index_b]);
}
adapted_values[p_index_a] = MIN(p_max_a, adapted_values[p_index_a]);
adapted_values[p_index_b] = MIN(p_max_b, adapted_values[p_index_b]);
}
void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
//PREPARATIONS
bool rounded_corners = (corner_radius[0] > 0) || (corner_radius[1] > 0) || (corner_radius[2] > 0) || (corner_radius[3] > 0);
bool aa_on = rounded_corners && anti_aliased;
Rect2 style_rect = p_rect.grow_individual(expand_margin[MARGIN_LEFT], expand_margin[MARGIN_TOP], expand_margin[MARGIN_RIGHT], expand_margin[MARGIN_BOTTOM]);
if (aa_on) {
style_rect = style_rect.grow(-((aa_size + 1) / 2));
}
//adapt borders (prevent weired overlapping/glitchy drawings)
int width = style_rect.size.width;
int height = style_rect.size.height;
int adapted_border[4] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX };
adapt_values(MARGIN_TOP, MARGIN_BOTTOM, adapted_border, border_width, height, height, height);
adapt_values(MARGIN_LEFT, MARGIN_RIGHT, adapted_border, border_width, width, width, width);
//adapt corners (prevent weired overlapping/glitchy drawings)
int adapted_corner[4] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX };
adapt_values(CORNER_TOP_RIGHT, CORNER_BOTTOM_RIGHT, adapted_corner, corner_radius, height, height - adapted_border[MARGIN_BOTTOM], height - adapted_border[MARGIN_TOP]);
adapt_values(CORNER_TOP_LEFT, CORNER_BOTTOM_LEFT, adapted_corner, corner_radius, height, height - adapted_border[MARGIN_BOTTOM], height - adapted_border[MARGIN_TOP]);
adapt_values(CORNER_TOP_LEFT, CORNER_TOP_RIGHT, adapted_corner, corner_radius, width, width - adapted_border[MARGIN_RIGHT], width - adapted_border[MARGIN_LEFT]);
adapt_values(CORNER_BOTTOM_LEFT, CORNER_BOTTOM_RIGHT, adapted_corner, corner_radius, width, width - adapted_border[MARGIN_RIGHT], width - adapted_border[MARGIN_LEFT]);
Rect2 infill_rect = style_rect.grow_individual(-adapted_border[MARGIN_LEFT], -adapted_border[MARGIN_TOP], -adapted_border[MARGIN_RIGHT], -adapted_border[MARGIN_BOTTOM]);
Vector<Point2> verts;
Vector<int> indices;
Vector<Color> colors;
//DRAWING
VisualServer *vs = VisualServer::get_singleton();
//DRAW SHADOW
if (shadow_size > 0) {
int shadow_width[4] = { shadow_size, shadow_size, shadow_size, shadow_size };
Color shadow_colors[4] = { shadow_color, shadow_color, shadow_color, shadow_color };
Color <API key>[4];
for (int i = 0; i < 4; i++) {
<API key>[i] = Color(shadow_color.r, shadow_color.g, shadow_color.b, 0);
}
draw_ring(verts, indices, colors, style_rect, adapted_corner,
style_rect.grow(shadow_size), shadow_width, shadow_colors, <API key>, corner_detail);
}
//DRAW border
Color bg_color_array[4] = { bg_color, bg_color, bg_color, bg_color };
const Color *inner_color = ((blend_border) ? bg_color_array : border_color.read().ptr());
draw_ring(verts, indices, colors, style_rect, adapted_corner,
style_rect, adapted_border, inner_color, border_color.read().ptr(), corner_detail);
//DRAW INFILL
if (draw_center) {
int temp_vert_offset = verts.size();
int no_border[4] = { 0, 0, 0, 0 };
draw_ring(verts, indices, colors, style_rect, adapted_corner,
infill_rect, no_border, &bg_color, &bg_color, corner_detail);
int added_vert_count = verts.size() - temp_vert_offset;
//fill the indices and the colors for the center
for (int index = 0; index <= added_vert_count / 2; index += 2) {
int i = index;
//poly 1
indices.push_back(temp_vert_offset + i);
indices.push_back(temp_vert_offset + added_vert_count - 4 - i);
indices.push_back(temp_vert_offset + i + 2);
//poly 1
indices.push_back(temp_vert_offset + i);
indices.push_back(temp_vert_offset + added_vert_count - 2 - i);
indices.push_back(temp_vert_offset + added_vert_count - 4 - i);
}
}
if (aa_on) {
//HELPER ARRAYS
Color border_color_alpha[4];
for (int i = 0; i < 4; i++) {
Color c = border_color.read().ptr()[i];
border_color_alpha[i] = Color(c.r, c.g, c.b, 0);
}
Color alpha_bg = Color(bg_color.r, bg_color.g, bg_color.b, 0);
Color <API key>[4] = { alpha_bg, alpha_bg, alpha_bg, alpha_bg };
int aa_border_width[4] = { aa_size, aa_size, aa_size, aa_size };
if (draw_center) {
if (!blend_border) {
//INFILL AA
draw_ring(verts, indices, colors, style_rect, adapted_corner,
infill_rect.grow(aa_size), aa_border_width, bg_color_array, <API key>, corner_detail);
}
} else if (!(border_width[0] == 0 && border_width[1] == 0 && border_width[2] == 0 && border_width[3] == 0)) {
//DRAW INNER BORDER AA
draw_ring(verts, indices, colors, style_rect, adapted_corner,
infill_rect, aa_border_width, border_color_alpha, border_color.read().ptr(), corner_detail);
}
//DRAW OUTER BORDER AA
if (!(border_width[0] == 0 && border_width[1] == 0 && border_width[2] == 0 && border_width[3] == 0)) {
draw_ring(verts, indices, colors, style_rect, adapted_corner,
style_rect.grow(aa_size), aa_border_width, border_color.read().ptr(), border_color_alpha, corner_detail);
}
}
vs-><API key>(p_canvas_item, indices, verts, colors);
}
float StyleBoxFlat::get_style_margin(Margin p_margin) const {
return border_width[p_margin];
}
void StyleBoxFlat::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bg_color", "color"), &StyleBoxFlat::set_bg_color);
ClassDB::bind_method(D_METHOD("get_bg_color"), &StyleBoxFlat::get_bg_color);
ClassDB::bind_method(D_METHOD("set_border_color", "color"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("get_border_color"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "width"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("<API key>"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("set_border_width", "margin", "width"), &StyleBoxFlat::set_border_width);
ClassDB::bind_method(D_METHOD("get_border_width", "margin"), &StyleBoxFlat::get_border_width);
ClassDB::bind_method(D_METHOD("set_border_blend", "blend"), &StyleBoxFlat::set_border_blend);
ClassDB::bind_method(D_METHOD("get_border_blend"), &StyleBoxFlat::get_border_blend);
ClassDB::bind_method(D_METHOD("<API key>", "radius_top_left", "radius_top_right", "radius_botton_right", "radius_bottom_left"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "radius"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("set_corner_radius", "corner", "radius"), &StyleBoxFlat::set_corner_radius);
ClassDB::bind_method(D_METHOD("get_corner_radius", "corner"), &StyleBoxFlat::get_corner_radius);
ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "size"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("<API key>", "size_left", "size_top", "size_right", "size_bottom"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("set_draw_center", "draw_center"), &StyleBoxFlat::set_draw_center);
ClassDB::bind_method(D_METHOD("<API key>"), &StyleBoxFlat::<API key>);
ClassDB::bind_method(D_METHOD("set_shadow_color", "color"), &StyleBoxFlat::set_shadow_color);
ClassDB::bind_method(D_METHOD("get_shadow_color"), &StyleBoxFlat::get_shadow_color);
ClassDB::bind_method(D_METHOD("set_shadow_size", "size"), &StyleBoxFlat::set_shadow_size);
ClassDB::bind_method(D_METHOD("get_shadow_size"), &StyleBoxFlat::get_shadow_size);
ClassDB::bind_method(D_METHOD("set_anti_aliased", "anti_aliased"), &StyleBoxFlat::set_anti_aliased);
ClassDB::bind_method(D_METHOD("is_anti_aliased"), &StyleBoxFlat::is_anti_aliased);
ClassDB::bind_method(D_METHOD("set_aa_size", "size"), &StyleBoxFlat::set_aa_size);
ClassDB::bind_method(D_METHOD("get_aa_size"), &StyleBoxFlat::get_aa_size);
ClassDB::bind_method(D_METHOD("set_corner_detail", "detail"), &StyleBoxFlat::set_corner_detail);
ClassDB::bind_method(D_METHOD("get_corner_detail"), &StyleBoxFlat::get_corner_detail);
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "bg_color"), "set_bg_color", "get_bg_color");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "<API key>");
ADD_GROUP("Border Width", "border_width_");
ADD_PROPERTYI(PropertyInfo(Variant::INT, "border_width_left", PROPERTY_HINT_RANGE, "0,1024,1"), "set_border_width", "get_border_width", MARGIN_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "border_width_top", PROPERTY_HINT_RANGE, "0,1024,1"), "set_border_width", "get_border_width", MARGIN_TOP);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "border_width_right", PROPERTY_HINT_RANGE, "0,1024,1"), "set_border_width", "get_border_width", MARGIN_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "border_width_bottom", PROPERTY_HINT_RANGE, "0,1024,1"), "set_border_width", "get_border_width", MARGIN_BOTTOM);
ADD_GROUP("Border", "border_");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "border_color"), "set_border_color", "get_border_color");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "border_blend"), "set_border_blend", "get_border_blend");
ADD_GROUP("Corner Radius", "corner_radius_");
ADD_PROPERTYI(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_RANGE, "0,1024,1"), "set_corner_radius", "get_corner_radius", CORNER_TOP_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_RANGE, "0,1024,1"), "set_corner_radius", "get_corner_radius", CORNER_TOP_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_RANGE, "0,1024,1"), "set_corner_radius", "get_corner_radius", CORNER_BOTTOM_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "<API key>", PROPERTY_HINT_RANGE, "0,1024,1"), "set_corner_radius", "get_corner_radius", CORNER_BOTTOM_LEFT);
ADD_PROPERTY(PropertyInfo(Variant::INT, "corner_detail", PROPERTY_HINT_RANGE, "1,128,1"), "set_corner_detail", "get_corner_detail");
ADD_GROUP("Expand Margin", "expand_margin_");
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", MARGIN_LEFT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", MARGIN_RIGHT);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", MARGIN_TOP);
ADD_PROPERTYI(PropertyInfo(Variant::REAL, "<API key>", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin", "get_expand_margin", MARGIN_BOTTOM);
ADD_GROUP("Shadow", "shadow_");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color"), "set_shadow_color", "get_shadow_color");
ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_size"), "set_shadow_size", "get_shadow_size");
ADD_GROUP("Anti Aliasing", "anti_aliasing_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "anti_aliasing"), "set_anti_aliased", "is_anti_aliased");
ADD_PROPERTY(PropertyInfo(Variant::INT, "anti_aliasing_size", PROPERTY_HINT_RANGE, "1,5,1"), "set_aa_size", "get_aa_size");
}
StyleBoxFlat::StyleBoxFlat() {
bg_color = Color(0.6, 0.6, 0.6);
shadow_color = Color(0, 0, 0, 0.6);
border_color.append(Color(0.8, 0.8, 0.8));
border_color.append(Color(0.8, 0.8, 0.8));
border_color.append(Color(0.8, 0.8, 0.8));
border_color.append(Color(0.8, 0.8, 0.8));
blend_border = false;
draw_center = true;
anti_aliased = true;
shadow_size = 0;
corner_detail = 8;
aa_size = 1;
border_width[0] = 0;
border_width[1] = 0;
border_width[2] = 0;
border_width[3] = 0;
expand_margin[0] = 0;
expand_margin[1] = 0;
expand_margin[2] = 0;
expand_margin[3] = 0;
corner_radius[0] = 0;
corner_radius[1] = 0;
corner_radius[2] = 0;
corner_radius[3] = 0;
}
StyleBoxFlat::~StyleBoxFlat() {
}
void StyleBoxLine::set_color(const Color &p_color) {
color = p_color;
emit_changed();
}
Color StyleBoxLine::get_color() const {
return color;
}
void StyleBoxLine::set_thickness(int p_thickness) {
thickness = p_thickness;
emit_changed();
}
int StyleBoxLine::get_thickness() const {
return thickness;
}
void StyleBoxLine::set_vertical(bool p_vertical) {
vertical = p_vertical;
}
bool StyleBoxLine::is_vertical() const {
return vertical;
}
void StyleBoxLine::set_grow(float p_grow) {
grow = p_grow;
emit_changed();
}
float StyleBoxLine::get_grow() const {
return grow;
}
void StyleBoxLine::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_color", "color"), &StyleBoxLine::set_color);
ClassDB::bind_method(D_METHOD("get_color"), &StyleBoxLine::get_color);
ClassDB::bind_method(D_METHOD("set_thickness", "thickness"), &StyleBoxLine::set_thickness);
ClassDB::bind_method(D_METHOD("get_thickness"), &StyleBoxLine::get_thickness);
ClassDB::bind_method(D_METHOD("set_grow", "grow"), &StyleBoxLine::set_grow);
ClassDB::bind_method(D_METHOD("get_grow"), &StyleBoxLine::get_grow);
ClassDB::bind_method(D_METHOD("set_vertical", "vertical"), &StyleBoxLine::set_vertical);
ClassDB::bind_method(D_METHOD("is_vertical"), &StyleBoxLine::is_vertical);
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
ADD_PROPERTY(PropertyInfo(Variant::INT, "thickness", PROPERTY_HINT_RANGE, "0,10"), "set_thickness", "get_thickness");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "vertical"), "set_vertical", "is_vertical");
}
float StyleBoxLine::get_style_margin(Margin p_margin) const {
return thickness;
}
Size2 StyleBoxLine::get_center_size() const {
return Size2();
}
void StyleBoxLine::draw(RID p_canvas_item, const Rect2 &p_rect) const {
VisualServer *vs = VisualServer::get_singleton();
Rect2i r = p_rect;
if (vertical) {
r.position.y -= grow;
r.size.y += grow * 2;
r.size.x = thickness;
} else {
r.position.x -= grow;
r.size.x += grow * 2;
r.size.y = thickness;
}
vs-><API key>(p_canvas_item, r, color);
}
StyleBoxLine::StyleBoxLine() {
grow = 1.0;
thickness = 1;
color = Color(0.0, 0.0, 0.0);
vertical = false;
}
StyleBoxLine::~StyleBoxLine() {} |
# <API key>: true
require 'spec_helper'
RSpec.describe Projects::LfsPointers::<API key> do
let(:import_url) { 'http:
let(:lfs_endpoint) { "#{import_url}/info/lfs/objects/batch" }
let!(:project) { create(:project, import_url: import_url) }
let(:new_oids) { { 'oid1' => 123, 'oid2' => 125 } }
let(:remote_uri) { URI.parse(lfs_endpoint) }
let(:request_object) { HTTParty::Request.new(Net::HTTP::Post, '/') }
let(:parsed_block) { lambda {} }
let(:<API key>) { Net::HTTPOK.new('', '', '') }
let(:response) { Gitlab::HTTP::Response.new(request_object, net_response, parsed_block) }
def objects_response(oids)
body = oids.map do |oid, size|
{
'oid' => oid, 'size' => size,
'actions' => {
'download' => { 'href' => "#{import_url}/gitlab-lfs/objects/#{oid}" }
}
}
end
Struct.new(:success?, :objects).new(true, body).to_json
end
def custom_response(net_response, body = nil)
allow(net_response).to receive(:body).and_return(body)
Gitlab::HTTP::Response.new(request_object, net_response, parsed_block)
end
let(:<API key>) do
[
'oid' => 'whatever',
'size' => 123
]
end
subject { described_class.new(project, remote_uri: remote_uri) }
before do
allow(project).to receive(:lfs_enabled?).and_return(true)
response = custom_response(<API key>, objects_response(new_oids))
allow(Gitlab::HTTP).to receive(:post).and_return(response)
end
describe '#execute' do
it 'retrieves each download link of every non existent lfs object' do
subject.execute(new_oids).each do |lfs_download_object|
expect(lfs_download_object.link).to eq "#{import_url}/gitlab-lfs/objects/#{lfs_download_object.oid}"
end
end
context 'when lfs objects size is larger than the batch size' do
def <API key>(batch)
response = custom_response(<API key>, objects_response(batch))
stub_request(batch, response)
end
def <API key>(batch)
<API key> = Net::<API key>.new('', '', '')
response = custom_response(<API key>)
stub_request(batch, response)
end
def stub_request(batch, response)
expect(Gitlab::HTTP).to receive(:post).with(
remote_uri,
{
body: { operation: 'download', objects: batch.map { |k, v| { oid: k, size: v } } }.to_json,
headers: subject.send(:headers)
}
).and_return(response)
end
let(:new_oids) { { 'oid1' => 123, 'oid2' => 125, 'oid3' => 126, 'oid4' => 127, 'oid5' => 128 } }
context 'when batch size' do
before do
stub_const("#{described_class.name}::REQUEST_BATCH_SIZE", 2)
data = new_oids.to_a
<API key>([data[0], data[1]])
<API key>([data[2], data[3]])
<API key>([data[4]])
end
it 'retreives them in batches' do
subject.execute(new_oids).each do |lfs_download_object|
expect(lfs_download_object.link).to eq "#{import_url}/gitlab-lfs/objects/#{lfs_download_object.oid}"
end
end
end
context 'when request fails with PayloadTooLarge error' do
let(:error_class) { described_class::<API key> }
context 'when the smaller batch eventually works' do
before do
stub_const("#{described_class.name}::REQUEST_BATCH_SIZE", 5)
data = new_oids.to_a
# with the batch size of 5
<API key>(data)
# with the batch size of 2
<API key>([data[0], data[1]])
<API key>([data[2], data[3]])
<API key>([data[4]])
end
it 'retreives them eventually and logs exceptions' do
expect(Gitlab::ErrorTracking).to receive(:track_exception).with(
an_instance_of(error_class), project_id: project.id, batch_size: 5, oids_count: 5
)
subject.execute(new_oids).each do |lfs_download_object|
expect(lfs_download_object.link).to eq "#{import_url}/gitlab-lfs/objects/#{lfs_download_object.oid}"
end
end
end
context 'when batch size cannot be any smaller' do
before do
stub_const("#{described_class.name}::REQUEST_BATCH_SIZE", 5)
data = new_oids.to_a
# with the batch size of 5
<API key>(data)
# with the batch size of 2
<API key>([data[0], data[1]])
end
it 'raises an error and logs exceptions' do
expect(Gitlab::ErrorTracking).to receive(:track_exception).with(
an_instance_of(error_class), project_id: project.id, batch_size: 5, oids_count: 5
)
expect(Gitlab::ErrorTracking).to receive(:track_exception).with(
an_instance_of(error_class), project_id: project.id, batch_size: 2, oids_count: 5
)
expect { subject.execute(new_oids) }.to raise_error(described_class::DownloadLinksError)
end
end
end
end
context 'credentials' do
context 'when the download link and the lfs_endpoint have the same host' do
context 'when lfs_endpoint has credentials' do
let(:import_url) { 'http:
it 'adds credentials to the download_link' do
result = subject.execute(new_oids)
result.each do |lfs_download_object|
expect(lfs_download_object.link.starts_with?('http://user:password@')).to be_truthy
end
end
end
context 'when lfs_endpoint does not have any credentials' do
it 'does not add any credentials' do
result = subject.execute(new_oids)
result.each do |lfs_download_object|
expect(lfs_download_object.link.starts_with?('http://user:password@')).to be_falsey
end
end
end
end
context 'when the download link and the lfs_endpoint have different hosts' do
let(:<API key>) { 'http:
let(:lfs_endpoint) { "#{<API key>}/info/lfs/objects/batch" }
it 'downloads without any credentials' do
result = subject.execute(new_oids)
result.each do |lfs_download_object|
expect(lfs_download_object.link.starts_with?('http://user:password@')).to be_falsey
end
end
end
end
end
describe '#get_download_links' do
context 'if request fails' do
before do
<API key> = Net::HTTPRequestTimeout.new('', '', '')
response = custom_response(<API key>)
allow(Gitlab::HTTP).to receive(:post).and_return(response)
end
it 'raises an error' do
expect { subject.send(:get_download_links, new_oids) }.to raise_error(described_class::DownloadLinksError)
end
end
shared_examples 'JSON parse errors' do |body|
it 'raises an error' do
response = custom_response(<API key>)
allow(response).to receive(:body).and_return(body)
allow(Gitlab::HTTP).to receive(:post).and_return(response)
expect { subject.send(:get_download_links, new_oids) }.to raise_error(described_class::DownloadLinksError)
end
end
it_behaves_like 'JSON parse errors', '{'
it_behaves_like 'JSON parse errors', '{}'
it_behaves_like 'JSON parse errors', '{ foo: 123 }'
end
describe '#<API key>' do
it 'does not add oid entry if href not found' do
expect(subject).to receive(:log_error).with("Link for Lfs Object with oid whatever not found or invalid.")
result = subject.send(:<API key>, <API key>)
expect(result).to be_empty
end
end
end |
var express = require('express');
var bodyParser = require('body-parser');
var cons = require('consolidate');
var routes = require('./server/routes.js'); //requesting my module routes
var app = express();
app.use(bodyParser());
app.use(express.static(__dirname + '/'));
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/');
routes.routes(app);
app.listen(3300, function(req, res) {
console.log("Server is running on port 3300");
}); |
var config = require('../config');
var imagemin = require('gulp-imagemin');
var runSequence = require('run-sequence');
var spritesmith = require('gulp.spritesmith');
gulp.task('sprites' ,function () {
runSequence('generateSpriteFiles', 'sass');
});
gulp.task('generateSpriteFiles', function() {
var spriteData = gulp.src(config.sprites_sources).pipe(spritesmith({
imgName: 'sprite.png',
cssName: '_sprite.scss'
}));
// Pipe image stream through image optimizer and onto disk
spriteData.img
.pipe(imagemin())
.pipe(gulp.dest(config.build));
// Pipe CSS stream through CSS optimizer and onto disk
spriteData.css
.pipe(gulp.dest(config.sass_dir));
}); |
/*
* <API key>
*
*
*/
package co.iamdata.api.models;
import java.util.*;
public class NutrientInfoBuilder {
//the instance to build
private NutrientInfo nutrientInfo;
/**
* Default constructor to initialize the instance
*/
public NutrientInfoBuilder() {
nutrientInfo = new NutrientInfo();
}
public NutrientInfoBuilder description(String description) {
nutrientInfo.setDescription(description);
return this;
}
public NutrientInfoBuilder id(Integer id) {
nutrientInfo.setId(id);
return this;
}
public NutrientInfoBuilder name(String name) {
nutrientInfo.setName(name);
return this;
}
public NutrientInfoBuilder <API key>(String <API key>) {
nutrientInfo.<API key>(<API key>);
return this;
}
public NutrientInfoBuilder <API key>(Double <API key>) {
nutrientInfo.<API key>(<API key>);
return this;
}
public NutrientInfoBuilder unitOfMeasurement(String unitOfMeasurement) {
nutrientInfo.<API key>(unitOfMeasurement);
return this;
}
/**
* Build the instance with the given values
*/
public NutrientInfo build() {
return nutrientInfo;
}
} |
type TextEncodeOptions = { options?: boolean, ... };
declare class TextEncoder {
encode(buffer: string, options?: TextEncodeOptions): Uint8Array,
}
declare class <API key> {
constructor(
stream: ReadableStream,
underlyingSource: UnderlyingSource,
size: number,
highWaterMark: number,
): void,
desiredSize: number,
close(): void,
enqueue(chunk: any): void,
error(error: Error): void,
}
declare class <API key> {
constructor(controller: <API key>, view: $TypedArray): void,
view: $TypedArray,
respond(bytesWritten: number): ?any,
respondWithNewView(view: $TypedArray): ?any,
}
declare class <API key> extends <API key> {
constructor(
stream: ReadableStream,
underlyingSource: UnderlyingSource,
highWaterMark: number,
): void,
byobRequest: <API key>,
}
declare class <API key> {
constructor(stream: ReadableStream): void,
closed: boolean,
cancel(reason: string): void,
read(): Promise<{
value: ?any,
done: boolean,
}>,
releaseLock(): void,
}
declare interface UnderlyingSource {
<API key>?: number,
type?: string,
start?: (controller: <API key>) => ?Promise<void>,
pull?: (controller: <API key>) => ?Promise<void>,
cancel?: (reason: string) => ?Promise<void>,
}
declare class TransformStream {
readable: ReadableStream,
writable: WritableStream,
};
type PipeToOptions = {
preventClose?: boolean,
preventAbort?: boolean,
preventCancel?: boolean,
};
type QueuingStrategy = {
highWaterMark: number,
size(chunk: ?any): number,
};
declare class ReadableStream {
constructor(
underlyingSource: ?UnderlyingSource,
queuingStrategy: ?QueuingStrategy,
): void,
locked: boolean,
cancel(reason: string): void,
getReader(): <API key>,
pipeThrough(transform: TransformStream, options: ?any): void,
pipeTo(dest: WritableStream, options: ?PipeToOptions): Promise<void>,
tee(): [ReadableStream, ReadableStream],
};
declare interface <API key> {
error(error: Error): void,
}
declare interface UnderlyingSink {
<API key>?: number,
type?: string,
abort?: (reason: string) => ?Promise<void>,
close?: (controller: <API key>) => ?Promise<void>,
start?: (controller: <API key>) => ?Promise<void>,
write?: (chunk: any, controller: <API key>) => ?Promise<void>,
}
declare interface <API key> {
closed: Promise<any>,
desiredSize?: number,
ready: Promise<any>,
abort(reason: string): ?Promise<any>,
close(): Promise<any>,
releaseLock(): void,
write(chunk: any): Promise<any>,
}
declare class WritableStream {
constructor(
underlyingSink: ?UnderlyingSink,
queuingStrategy: QueuingStrategy,
): void,
locked: boolean,
abort(reason: string): void,
getWriter(): <API key>,
} |
# Cacman Jacman
[README](/README.md)
Jacman [Hexo](http:
[](http:
[ Jacman ](http://wuchong.me/blog/2014/11/20/how-to-use-jacman/)
$ git clone https://github.com/wuchong/jacman.git themes/jacman
**Jacman Hexo 2.7 **
`_config.yml``theme` `jacman`.
cd themes/jacman
git pull origin master
** `_config.yml` **
`/themes/jacman/_config.yml` [wiki](https://github.com/wuchong/jacman/wiki/%E9%85%8D%E7%BD%AE%E6%8C%87%E5%8D%97)
- ** menu**
- ** widget**
RSS
- ** Image**
logo`img-logo`,`img-topic`,`img-center`
- ** index**
[](http:
- ** author**
GitHubStackOverflowTwitterFacebookLinkedinGoogle+
- ** toc**
- ** comments**
[](http:
- ** jiathis**
[](http:
- ** Analytiscs**
[](http:
- **Search**
[](https:
- **totop**
- **rss**
RSS
- **fancybox**
[Fancybox](http://fancyapps.com/fancybox/)
[](https://github.com/wuchong/jacman/wiki/)
- [Jacman Theme](http://wuchong.me/jacman) - The demo site of Jacman Theme
- [Jark's Blog](http://wuchong.me) - The author's blog of Jacman
- [PhiloSky's Blog](http://philosky.ml/) -
- [hiluSdream](http://hiluluke.cn) -
- [Melface](http://melface.tk) -
- [heamon7's Utopia](http://heamon7.com) -
- [PegasusWang's Blog](http://ningning.today) -
- [](http:
- [Vigorass](http://cscao.com) - Learn to record dripping growth
- [MoqiZhan](http://moqizhan.com) -
- [Think Differently](http://think-diff.me/) - If You Can Think Differently, You Can Act Differently.
- [ylf](http://wangyangyang.gitcafe.com) -
- [keychar](http://keychar.com) - A technology blog, design & programming.
- [peng](http://chenpengdsp.com) -
- [More and More](http://aeesky.github.io) -
- [](http://dpast.org) - Julian Zhu
Jacman[wiki](https://github.com/wuchong/jacman/wiki/Sites)
[MIT](/LICENSE) |
import { NgModule } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { <API key> } from './image-viewer.directive';
import { <API key> } from './image-viewer.component';
import { <API key> } from './image-viewer.controller';
var <API key> = (function () {
function <API key>() {
}
<API key>.decorators = [
{ type: NgModule, args: [{
imports: [IonicModule],
declarations: [
<API key>,
<API key>
],
providers: [<API key>],
exports: [<API key>],
entryComponents: [<API key>]
},] },
];
/** @nocollapse */
<API key>.ctorParameters = function () { return []; };
return <API key>;
}());
export { <API key> };
//# sourceMappingURL=module.js.map |
import Economy from './economy';
export default tour;
/**
* Gets the name of users
*
* @param {Array} users
* @return {String} name
*/
function usersToNames(users) {
return users.map((user) => user.name);
}
/**
* Determines the amount of earnings from tournaments
*
* @param {Number} sizeRequiredToEarn
* @param {Color} color (color for annoucements of tournament winner and runnerUp if runnerUp exists)
*/
function tour(sizeRequiredToEarn=3, color='#088cc7') {
let Tournament = Tournaments.Tournament;
if (!Tournament.prototype.<API key>) {
Tournament.prototype.<API key> = Tournament.prototype.onTournamentEnd;
}
Tournament.prototype.onTournamentEnd = function() {
this.<API key>();
let data = this.generator.getResults().map(usersToNames).toString();
let winner, runnerUp;
if (data.indexOf(',') >= 0) {
data = data.split(',');
winner = data[0];
if (data[1]) {
runnerUp = data[1];
}
} else {
winner = data;
}
let wid = toId(winner);
let rid = toId(runnerUp);
let tourSize = this.generator.users.size;
let currency_name = Wulu.Economy.currency_name;
if (this.room.isOfficial && tourSize >= sizeRequiredToEarn) {
let firstMoney = Math.round(tourSize);
let secondMoney = Math.round(firstMoney / 2);
let firstCurrencyName = firstMoney >= 2 ? currency_name + 's' : currency_name;
let secondCurrencyName = secondMoney >= 2 ? currency_name + 's' : currency_name;
// annouces the winner and runnerUp if runnerUp exists
this.room.add(`|raw|<b><font color="${color}">${Tools.escapeHTML(winner)}</font> has won <font color="${color}">${firstMoney}</font> ${firstCurrencyName} for winning the tournament!</b>`);
if (runnerUp) this.room.add(`|raw|<b><font color="${color}">${Tools.escapeHTML(runnerUp)}</font> has also won <font color="${color}">${secondMoney}</font> ${secondCurrencyName} for being getting runner up of the tournament!</b>`);
Economy.give(wid, firstMoney);
Economy.give(rid, secondMoney);
}
};
} |
/**
* @file
* Provides javascript methods for manage the visual help.
*/
(function ($, Drupal) {
// Global variable base_path.
var drupalBasePath = "";
// Hide the visual help for document ready
$('.vcl-visual-help').hide();
$('.vcl-btn').text('Enable Visual Content Layout');
/**
* Manage the display of the visual help.
*
* Methods that are responsible for show and hide the visual help according on the textFormat
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.vclDisplay = {
attach: function (context, settings) {
// Set the base path global.
if (settings.vcl.base_path) {
drupalBasePath = settings.vcl.base_path;
}
// Validate all the filter select for enable the button on it textArea.
var filter = $('.filter-list');
for (var i = 0; i < filter.length; i++) {
// Get the parent of the actual select, if is undefined it send and error and stop de cycle.
var filterParent = $(filter[i]).parents()[2];
if(settings.vcl.enable_formats){
// Show the enable/disable button for the visual help according the textFormat.
if (settings.vcl.enable_formats[$(filter[i]).val()]) {
$(filterParent).children('.vcl-btn').show();
}
else {
$(filterParent).children('.vcl-btn').hide();
}
}
}
// Event change the text format
$('.filter-list', context).change(function () {
// Get the parent of the filter select.
var selectParent = $(this).parents('.text-format-wrapper');
// Validate if the textFormat use the visual help.
if (settings.vcl.enable_formats[$(this).val()]) {
selectParent.find('.vcl-btn').show();
}
else {
selectParent.find('.vcl-btn').hide();
selectParent.find('.vcl-visual-help').hide();
$('.vcl-element').remove();
selectParent.find('.vcl-btn').data('state', 'disable');
selectParent.find('.vcl-btn').text('Enable Visual Content Layout');
$(this).parents('.text-format-wrapper').find('.form-textarea').show();
selectParent.children('#<API key>').show();
}
});
// Event click enable/disable visual help button
$('.vcl-btn', context).click(function () {
// Get id of the respective textArea.
var textArea = $(this).data('id');
// Validate if the visual help is disable.
if ($(this).data('state') === 'disable') {
handleVisualHelp(this, textArea, true);
}
else {
handleVisualHelp(this, textArea, false);
}
});
// Show and hide the visual help
function handleVisualHelp(button, textArea, enable) {
// Show the visual help section of the respective textArea.
var buttonParent = $(button).parents()[0];
if (enable) {
$(buttonParent).children('.vcl-visual-help').show();
$('#' + textArea).hide();
$(buttonParent).find('.filter-guidelines').hide();
$(button).data('state', 'enable');
$(button).text('Disable Visual Content Layout');
$(button).removeClass('fa-square-o');
$(button).addClass('fa-check-square-o');
}
else {
$(buttonParent).children('.vcl-visual-help').hide();
$('#' + textArea).show();
$(buttonParent).find('.filter-guidelines').show();
$(button).data('state', 'disable');
$(button).text('Enable Visual Content Layout');
$(button).removeClass('fa-check-square-o');
$(button).addClass('fa-square-o');
}
}
// Event click display swap select form
$('.vcl-form-button', context).click(function () {
var textArea = $(this).data('textarea'),
element = document.createElement('input'),
id = $(this).parent().attr('id'),
position = $('.<API key>');
$('<input>').attr("id", "vcl-actual-textarea")
.attr("type", "hidden")
.val(textArea)
.appendTo($(".vcl-visual-help"));
if(position.length === 0){
position = $('<input>').attr("id", "<API key>").attr("type", "hidden");
}
if (id === 'vcl-top-link'){
position.val('top');
}
else{
position.val('bottom');
}
position.appendTo($(".vcl-visual-help"));
// Delete the target class.
$('.vcl-target').removeClass('vcl-target');
});
}
};
/**
* Manage the information send by each swap attributes form.
*
* Methods that are responsible for take the information save the attributes and create the visual element.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.vclForm = {
attach: function (context, settings) {
var attributes = settings.vcl.attributes;
if (attributes) {
var textArea = $('#vcl-actual-textarea').val(),
textAreaElement = $('#' + textArea),
textAreaParent = textAreaElement.parents()[2],
visualHelpArea = $(textAreaParent).children('.vcl-visual-help')
.find('.vcl-elements-area'),
position = $('#<API key>').val();
// Create the html element for the new swap.
var element = document.createElement('div');
$(element).addClass('vcl-element panel panel-default');
// Create the icon for handle the drag.
var dragIcon = $('<span/>').attr({class: 'fa fa-arrows dragIcon'});
dragIcon.html(attributes.swapName);
// Create the delete button for this element.
var deleteButton = $('<i/>').attr({class: 'fa fa-trash-o fa-3 iconButton'})
.on('click', deleteVisualElement);
// Create the edit button for this element.
var editButton = $('<i/>').attr({class: 'fa fa-pencil-square-o fa-3 iconButton'})
.on('click', editVisualElement)
.data('swapName', attributes.swapName);
// Create the button for copy the element.
var copyButton = $('<span/>').attr({class: 'fa fa-clone iconButton'})
.on('click', copyVisualElement);
dragIcon.appendTo(element);
deleteButton.appendTo(element);
editButton.appendTo(element);
copyButton.appendTo(element);
// Validate the swap can contain others swaps.
if (attributes.container) {
// Create the button for add swaps if have container.
var addButton = $('<a>', {
href: drupalBasePath + 'vcl/swap_select_form/' + attributes.swapId,
class: 'fa fa-plus-square iconButton addButton'});
// Add event to button.
addButton.on('click', <API key>);
// Settings for create drupal ajax link.
var element_settings = {};
element_settings.url = addButton.attr('href');
element_settings.event = 'click';
element_settings.progress = {
type: 'throbber',
message: ''
};
var base = 'addButton';
Drupal.ajax[base] = new Drupal.Ajax(base, addButton, element_settings);
addButton.appendTo(element);
$('<div>').addClass('vcl-container').appendTo($(element));
}
delete (attributes.container);
var attrKeys = Object.keys(attributes);
for (var i = 0; i < attrKeys.length; i++) {
if (attrKeys[i] === 'swapId') {
$(element).data(attrKeys[i], attributes[attrKeys[i]].replace('swap_', ''));
continue;
}
if (attrKeys[i] !== '' && attrKeys[i] !== 'swapName') {
$(element).data(attrKeys[i], attributes[attrKeys[i]]);
}
}
var target = $('.vcl-target');
if (position === 'top'){
$(element).prependTo(visualHelpArea);
}
else{
if (target[0]){
$(element).prependTo(target);
}
else {
$(element).appendTo(visualHelpArea);
}
}
$('#' + textArea).val(getTextFromVisual(visualHelpArea));
makeDragAndDrop();
$('#<API key>').val("");
$('#vcl-actual-textarea').remove();
$('.vcl-target').removeClass('vcl-target');
delete (settings.vcl.attributes);
}
}
};
/**
* Manage the visual elements.
*
* Methods that are responsible for transform text in visual element and visual element in text
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.vclElements = {
attach: function (context, settings) {
// Event click enable/disable visual help button
$('.vcl-btn', context).click(function () {
// Get id of the respective textArea.
var textArea = $(this).data('id');
// Validate if the visual help is enable.
if ($(this).data('state') === 'enable') {
var swaps = settings.vcl.enable_swaps,
swapNames = settings.vcl.swap_names;
// Make the visual element with the text.
getVisualElements(textArea, swaps, swapNames);
makeDragAndDrop();
}
else {
var buttonParent = $(this).parents()[0],
visualHelpArea = $(buttonParent).children('.vcl-visual-help'),
elementsContainer = visualHelpArea.children('.vcl-elements-area'),
elements = elementsContainer.children('.vcl-element');
// Delete elements.
elements.remove();
}
});
// Transform text in visual elements
function getVisualElements(textArea, enableSwaps, swapNames) {
var text = $('#' + textArea).val(),
textAreaParent = $('#' + textArea).parents()[2],
visualHelpArea = $(textAreaParent).children('.vcl-visual-help')
.find('.vcl-elements-area'),
chunks = text.split(/(\[{1,2}.*?\]{1,2})/),
elements = [],
father = [],
count = 0,
swap = null,
swapText = false;
for (var i = 0; i < chunks.length; i++) {
// Save the original text in case of error in the swap pattern.
var originalText = chunks[i],
c = chunks[i].trim();
if (c === '') {
continue;
}
// Validate the chunk is a swap head.
if (c[0] === '[') {
// Delete the first and last character
c = c.substring(1, c.length - 1).trim();
// Validate if the swap have the close character in the head.
if (c[c.length - 1] === '/') {
// Validate the swap is a valid swap.
if (typeof enableSwaps[c.split(" ")[0]] === "undefined") {
// Create a simple text swap.
div = createHTMLDiv(originalText, null, swapNames);
// Validate if the storage swap is a father of the created div.
if (swap !== null) {
elements.push(swap);
father.push(elements.length - 1);
}
// Validate if that swap have a father.
if (father.length > 0) {
elements.push(div);
swap = null;
swapText = false;
continue;
}
else {
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
}
c = c.substring(0, c.length - 1);
// Validate if the new swap is a father.
if (count > 0 && swap != null) {
elements.push(swap);
father.push(elements.length - 1);
}
// Get cssStyle.
var startIndex = c.indexOf("cssStyles"),
middle_index = c.indexOf('"', startIndex),
lastIndex = c.indexOf('"', middle_index + 1),
cssStyle = c.substring(startIndex, lastIndex);
// Save the attributes of the swaps.
c = c.replace(" " + cssStyle, "");
swap = c.trim().split(" ");
swap.push(cssStyle);
div = createHTMLDiv(originalText, swap, swapNames);
// Validate if the swap can contain others swaps.
if (enableSwaps[c.split(" ")[0]]) {
// Insert addButton.
var addButton = createAddButton(div.data('swapId'));
addButton.appendTo($(div));
$('<div>').addClass('vcl-container').appendTo($(div));
}
// Validate if that swap have a father.
if (father.length > 0) {
elements.push(div);
swap = null;
swapText = false;
continue;
}
else {
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
}
// Validate the chunk is a swap close.
if (c[0] === '/') {
c = c.substring(1, c.length);
// Validate if the close character is for a father.
if (swap === null) {
var lastFather = father.pop(), fatherSwap = elements[lastFather];
// Validate if exist a father.
if (!fatherSwap) {
var div = createHTMLDiv(originalText, null, swapNames);
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
// Validate the swap and close character are the same.
if (fatherSwap[0] === c) {
// Create the father and add the child.
div = createHTMLDiv(originalText, fatherSwap, swapNames);
// Insert addButton.
addButton = createAddButton(div.data('swapId'));
addButton.appendTo($(div));
var ele = $('<div>').addClass('vcl-container').appendTo($(div));
while (elements[lastFather + 1]) {
$(elements[lastFather + 1]).appendTo(ele);
elements.splice(lastFather + 1, 1);
}
// Validate if the father have a father.
if (father.length === 0) {
$(div).appendTo($(visualHelpArea));
elements.splice(0, 1);
} else {
elements[lastFather] = div;
}
count = lastFather;
swapText = false;
continue;
}
else {
div = createHTMLDiv(originalText, null);
father.push(lastFather);
elements.push(div);
swap = null;
swapText = false;
continue;
}
}
// Validate if the child swap and close character are the same.
if (swap[0] === c) {
div = createHTMLDiv(originalText, swap, swapNames);
// Validate if the swap can contain others swaps.
if (enableSwaps[c.split(" ")[0]]) {
// Insert addButton.
addButton = createAddButton(div.data('swapId'));
addButton.appendTo($(div));
$('<div>').addClass('vcl-container').appendTo($(div));
}
swap = null;
swapText = false;
//validate if that swap have a father
if (father.length > 0) {
elements.push(div);
continue;
}
else {
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
}
}
// Validate the swap is a valid swap.
if (typeof enableSwaps[c.split(" ")[0]] === "undefined") {
// Create a simple text swap.
div = createHTMLDiv(originalText, null, swapNames);
// Validate is the storage swap is a father of the created div.
if (swap !== null) {
elements.push(swap);
father.push(elements.length - 1);
}
// Validate if that swap have a father.
if (father.length > 0) {
elements.push(div);
swap = null;
swapText = false;
continue;
}
else {
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
}
// Validate if the new swap is a father.
if (count > 0 && swap !== null) {
elements.push(swap);
father.push(elements.length - 1);
}
// Get cssStyle.
startIndex = c.indexOf("cssStyles");
if(startIndex !== -1){
lastIndex = c.indexOf('"', startIndex);
lastIndex = c.indexOf('"', lastIndex + 1);
cssStyle = c.substring(startIndex, lastIndex);
c = c.replace(" " + cssStyle, "");
}
// Save the attributes of the swaps.
swap = c.trim().split(" ");
if (cssStyle) {swap.push(cssStyle); }
swapText = true;
count++;
continue;
}
// Validate if the chunk is only text and is the first.
if (swapText) {
swap.push('text="' + originalText + '"');
}
else {
div = createHTMLDiv(originalText, null, swapNames);
// Validate if that swap have a father.
if (father.length > 0) {
elements.push(div);
swap = null;
swapText = false;
continue;
}
else {
$(div).appendTo($(visualHelpArea));
count = 0;
continue;
}
}
}
// Validate if are fathers in the array.
if (father.length !== 0) {
var remain_father = fatherSwap;
lastFather = father.pop();
fatherSwap = elements[lastFather];
var fatherOriginalText = "[ " + fatherSwap.toString().replace(/,/gi, ' ') + " ]",
errorFather = createHTMLDiv(fatherOriginalText, null, swapNames);
elements.push(div);
$(errorFather).appendTo($(visualHelpArea));
while (elements[lastFather + 1]) {
$(elements[lastFather + 1]).appendTo($(visualHelpArea));
elements.splice(lastFather + 1, 1);
}
}
}
// Create html object for the swap
function createHTMLDiv(originalText, swap, swapNames) {
// Create the element and set the class.
var element = $('<div>').addClass('vcl-element panel panel-default');
// Create the delete button for this element.
var deleteButton = $('<i/>').attr({class: 'fa fa-trash-o iconButton'})
.on('click', deleteVisualElement);
// Create the icon for handle the drag.
var dragIcon = $('<span/>').attr({class: 'fa fa-arrows dragIcon'});
// Validate if the swap is a valid swap.
if (swap !== null) {
var swapName = swapNames[swap[0]];
// Create the edit button for this element.
var editButton = $('<i/>').attr({class: 'fa fa-pencil-square-o fa-3 iconButton'})
.on('click', editVisualElement)
.data('swapName', swapName);
// Set the name in data attributes.
element.data('swapId', swap[0]);
delete (swap[0]);
// Set all other attributes.
for (var idx = 1; idx < swap.length; idx++) {
var attr = swap[idx].trim().replace(/\"/gi, '').split('=');
if (attr.length < 3){
element.data(attr[0], attr[1]);
}
else{
element.data(attr[0], attr[1] + "=" + attr[2]);
}
}
dragIcon.html(swapName);
// Create the button for copy the element.
var copyButton = $('<span/>').attr({class: 'fa fa-clone iconButton'})
.on('click', copyVisualElement);
} else {
dragIcon.html("Text: " + originalText);
element.data('swapId', "string");
element.data('text', originalText);
}
dragIcon.appendTo(element);
deleteButton.appendTo(element);
if (editButton) {editButton.appendTo(element); }
copyButton.appendTo(element);
return element;
}
// Create button to display swap select form inside visual element
function createAddButton(swapId) {
// Create the button for add swaps if have container.
var addButton = $('<a>', {
href: drupalBasePath + 'vcl/swap_select_form/' + swapId,
class: 'fa fa-plus-square iconButton addButton'});
// Add event to button.
addButton.on('click', <API key>);
makeAjaxLink(addButton, 'addButton');
return addButton;
}
}
};
// Transform visual elements in text
function getTextFromVisual(visualHelpArea) {
var children = $(visualHelpArea).children('.vcl-element'),
text = '';
// Process all children.
for (var i = 0; i < children.length; i++) {
text += createText($(children[i]));
}
return text;
}
// Create the text based on one swap
function createText(element) {
// Get all attributes from the data.
var data = $(element).data(),
swapId = data.swapId,
swapText = data.text,
text = "[" + swapId,
container = element.children('.vcl-container');
if (swapId === "string") {
return swapText;
}
// Process all the data.
for (var attr in data) {
// Validate the attr have a single value.
if (typeof data[attr] === "string" && attr !== "swapId" && attr !== "text") {
text += ' ' + attr + '="' + data[attr] + '"';
}
}
text += " ]" + (swapText ? swapText : '');
// Validate if the swap can contain others swaps.
if (container.length > 0) {
// Get the children of the swap.
var containerChildren = $(container[0]).children('.vcl-element');
// Validate the swap have children.
if (containerChildren.length > 0) {
// Process all children of the swap.
for (var i = 0; i < containerChildren.length; i++) {
text += createText($(containerChildren[i]));
}
}
}
text += "[/" + swapId + "]";
return text;
}
// Make the visual element able to drag and drop
function makeDragAndDrop() {
$(".vcl-container").sortable({
placeholder: "ui-state-highlight",
connectWith: ".vcl-container",
items: "div.vcl-element",
axis: "y",
opacity: 0.5,
cursor: "move",
handle: "span.dragIcon",
stop: function (event, ui) {
var elementsContainer = $(ui.item[0]).parents('.vcl-elements-area'),
visualHelpArea = elementsContainer.parent(),
addButton = $(visualHelpArea).find('a'),
textArea = $(addButton[0]).data('textarea'),
text = getTextFromVisual(elementsContainer);
$("#" + textArea).val(text);
}
});
}
// Event click edit visual element
function editVisualElement() {
// Get the swap name of the swap to fin the respective form.
var swapName = $(this).data().swapName,
url = drupalBasePath + 'vcl/<API key>/' + swapName.replace(" ", ""),
swapAttributes = $(this).parent().data(),
dWidth = $(window).width() * 0.7;
// Set a class in the div to identify which div actualize.
$(this).parent().addClass("swap-actualize-div");
// Place the progress icon.
$('<i class="fa fa-clock-o dragIcon"></i>').insertAfter($(this));
// Create a div for display the modal.
$('<div id="vcl-update-modal"></div>').appendTo("body");
// Execute ajax call.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
success: function (data) {
// Place the for in the special div for update dialogs.
$("#vcl-update-modal").html(data);
$('.fa-clock-o').remove();
// Call set attributes.
setAttributesInForm(swapAttributes);
// Execute verticalTab behaviors to theme the vertical tabs.
Drupal.behaviors.verticalTabs.attach($('#vcl-update-modal'));
// Display modal dialog.
$("#vcl-update-modal").dialog({
title: "Swap Atributes",
modal: true,
draggable: false,
resizable: false,
minWidth: dWidth
});
$(".<API key>").on("click", cancelVisualElement);
Drupal.behaviors.vclElementsInit.attach($('#vcl-update-modal'));
}
});
}
// Place the actual attributes in update form modal
function setAttributesInForm(attributes) {
// Iterate all attributes of the div.
for(var attr in attributes) {
var expresion = /([^a-zA-Z0-9-_])+/g;
// Validate is a key value position.
if(typeof attributes[attr] !== 'object'){
// Set default attributes.
var input = '#edit-swaps-' + attr;
input = $(input.toLowerCase());
input.val(attributes[attr]);
var inputType = $(input).attr('type');
// Set attribute for checkbox.
if(inputType === 'checkbox'){
var checked = (attributes[attr] === '1') ? true : false;
$(input).prop('checked', checked);
}
// Set own attributes.
input = '#edit-swaps-' + attributes.swapId + '-' + attr;
input = $(input.toLowerCase());
input.val(attributes[attr]);
inputType = $(input).attr('type');
// Set attribute for checkbox.
if(inputType === 'checkbox'){
checked = (attributes[attr] === '1') ? true : false;
$(input).prop('checked', checked);
}
if (!attributes[attr].match(expresion)){
input = '#edit-swaps-' + attributes.swapId + '-' + attr + '-' + attributes[attr];
input = $(input.toLowerCase());
inputType = $(input).attr('type');
if(inputType === 'radios' || inputType === 'radio'){
$(input).prop('checked', true);
}
}
}
}
// Validate exist the image manager
var imageManager = $('.vcl-image-manager');
if(imageManager.length > 0){
$("[name = swaps_img_fid]").val(attributes.fid);
$('.image_preview').attr('src', attributes.url);
imageManager.attr('href', drupalBasePath + 'vcl/swap_image_manager/' + attributes.fid);
makeAjaxLink(imageManager, 'vcl-image-manager');
}
// Define the function of accept button, negate submit form.
$("#edit-swaps-accept").on("click", updateVisualElement);
$("#edit-swaps-cancel").on("click", cancelVisualElement);
$("#vcl-update-modal form").submit(function () {
return false;
});
}
// Close update visual element modal
function cancelVisualElement() {
// Close modal dialog
$(".ui-dialog-content").dialog("close");
$("#vcl-update-modal").remove();
return false;
}
// Take the attributes in the update form modal and set in respective
function updateVisualElement() {
// Get the div to actualize and all inputs of the form.
var div = $('.swap-actualize-div'),
elements = $(".ui-dialog-content :input"),
swap = div.data("swapId");
// Clean all data from the swap
div.removeData();
div.data("swapId", swap);
// Iterate all inputs.
for (var i = 0; i < elements.length; i++) {
// Get the value of the input and the id.
var value = $(elements[i]).val(),
data = $(elements[i]).attr('id'),
inputType = $(elements[i]).attr('type');
// Validate the input have id and is not the submit button.
if (!data || data === "edit-swaps-accept" || data === "edit-swaps-cancel") {
continue;
}
// Set value for checkbox.
if(inputType === 'checkbox'){
value = $(elements[i]).prop('checked') ? '1' : '0';
}
// Create the data name based in the id.
data = data.replace("edit-swaps-", "");
data = data.replace(swap + '-', "");
// Set value for checkbox.
if(inputType === 'radio'){
if(!$(elements[i]).prop('checked')){
continue;
}else{
data = $(elements[i]).attr('id');
data = data.replace("edit-swaps-", "");
data = data.split("-")[1];
}
}
// Set the data.
div.data(data, value);
}
// Get the parents to find the textarea.
var elementsContainer = div.parents('.vcl-elements-area'),
visualHelpArea = elementsContainer.parent(),
addButton = $(visualHelpArea).find('a'),
textArea = $(addButton[0]).data('textarea');
// Recreate the text in textarea.
var text = getTextFromVisual(elementsContainer);
$("#" + textArea).val(text);
// Remove the class that identify which div actualize.
div.removeClass("swap-actualize-div");
// Close modal dialog
$(".ui-dialog-content").dialog("close");
$("#vcl-update-modal").remove();
return false;
}
// Event click delete visual element
function deleteVisualElement() {
var parent = $(this).parent('.vcl-element'),
elementsContainer = parent.parents('.vcl-elements-area'),
visualHelpArea = elementsContainer.parent(),
addButton = $(visualHelpArea).find('a'),
textArea = $(addButton[0]).data('textarea');
// Delete the element
$(parent).remove();
// Recreate the text in textarea
var text = getTextFromVisual(elementsContainer);
$("#" + textArea).val(text);
}
// Event click copy visual element
function copyVisualElement() {
var parent = $(this).parent('.vcl-element'),
elementsContainer = parent.parents('.vcl-elements-area'),
visualHelpArea = elementsContainer.parent(),
addButton = $(visualHelpArea).find('a'),
textArea = $(addButton[0]).data('textarea');
// Clone the element.
parent.clone(true).insertAfter(parent);
// Recreate the text in textarea.
var text = getTextFromVisual(elementsContainer);
$("#" + textArea).val(text);
}
// Event click add visual element in container
function <API key>() {
// Delete the target class.
$('.vcl-target').removeClass('vcl-target');
var parent = $(this).parents('.vcl-element');
if (parent.length > 1) {
var element = parent.children('.vcl-container:first');
element.addClass('vcl-target');
}
else{
element = parent.children('.vcl-container');
element.addClass('vcl-target');
}
// Set the actual textarea.
var visualHelpArea = $(this).parents('.vcl-visual-help'),
textArea = visualHelpArea.find('.vcl-form-button'),
textAreaId = textArea.data('textarea');
$('<input>').attr("id", "vcl-actual-textarea")
.attr("type", "hidden")
.val(textAreaId)
.appendTo($(".vcl-visual-help"));
}
// Create button to display swap select form inside visual element
function makeAjaxLink(link, LinkClass) {
// Settings for create drupal ajax link.
var element_settings = {};
element_settings.url = link.attr('href');
element_settings.event = 'click';
element_settings.progress = {
type: 'throbber',
message: ''
};
var base = LinkClass;
Drupal.ajax[base] = new Drupal.Ajax(base, link, element_settings);
}
}(jQuery, Drupal)); |
local skynet = require "skynet"
local skymgr = require "skynet.manager"
skynet.start(function()
-- master-service MASTER[]
-- uniqueservice newservice
local svc = assert(skynet.uniqueservice(true, "master-service"))
skymgr.name("MASTER", svc)
skynet.exit()
end) |
// DataLogger.h
#ifndef _DATALOGGER_h
#define _DATALOGGER_h
#include <SdFat.h>
#include "MuleDefines.h"
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
typedef struct __attribute__ ((packed)) {
// Floats are 32-bit on Teensy 3.x with Teensyduino 1.6.x
// Doubles are 64-bit on Teensy 3.x with Teensyduino 1.6.x
uint8_t dataVersion = 1; // Increment every time this struct changes
uint32_t time;
uint16_t throttle;
int16_t left;
int16_t right;
float steer;
uint16_t speed;
} mule_data_t;
class DataLogger
{
private:
char* fileName;
uint8_t spiSpeed;
uint8_t chipSelect;
uint32_t numEntries;
mule_data_t* buffer;
public:
DataLogger();
void init();
void logData();
void addEntry(uint32_t time, uint16_t throttle, int16_t left, int16_t right, float steering, uint16_t speed);
void writeHeader();
void startBinLogger();
void fastLog();
};
#endif |
package tutorial.custom_icon_demo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* CustomIconDemo.java (based on ButtonDemo.java) requires the following files:
* ArrowIcon.java
* images/middle.gif
*/
public class CustomIconDemo extends JPanel
implements ActionListener {
protected JButton b1;
protected JButton b2;
protected JButton b3;
public CustomIconDemo() {
Icon leftButtonIcon = new ArrowIcon(SwingConstants.RIGHT);
Icon middleButtonIcon = createImageIcon("images/middle.gif",
"the middle button");
Icon rightButtonIcon = new ArrowIcon(SwingConstants.LEFT);
b1 = new JButton("Disable middle button", leftButtonIcon);
b1.<API key>(AbstractButton.CENTER);
b1.<API key>(AbstractButton.LEADING);
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("Middle button", middleButtonIcon);
b2.<API key>(AbstractButton.BOTTOM);
b2.<API key>(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("Enable middle button", rightButtonIcon);
//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
//Add Components to this container, using the default FlowLayout.
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path,
String description) {
/* TODO: .class returns the reference to java.lang.Class object
java.net.URL imgURL = CustomIconDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
*/
return null;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CustomIconDemo");
frame.<API key>(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
JComponent newContentPane = new CustomIconDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main() {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
} |
import React from 'react';
import { Form, Button } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import './styles.scss';
function formatDate(date) {
const d = new Date(date);
const monthStr = (d.getMonth() + 1).toString();
const dayStr = d.getDate().toString();
const yearStr = d.getFullYear();
return `${dayStr}/${monthStr}/${yearStr}`;
}
const DisplayPost = ({
internshipDetails,
}) => (
<div className="<API key>">
<Form >
<Form.Field>
<label htmlFor="<API key>">Position</label>
<input
name="position"
value={internshipDetails.position}
readOnly
// onChange={onChange}
id="<API key>"
placeholder="Enter the internship position..."
/>
</Form.Field>
<Form.Field>
<label htmlFor="submit-post-company">Company</label>
<input
name="company"
value={internshipDetails.company}
readOnly
// onChange={onChange}
id="submit-post-company"
placeholder="Enter the company..."
/>
</Form.Field>
<Form.Field>
<label htmlFor="<API key>">Location</label>
<input
name="location"
value={internshipDetails.location}
readOnly
// onChange={onChange}
id="<API key>"
placeholder="Enter the location..."
/>
</Form.Field>
<Form.Group>
<Form.Field>
<label htmlFor="<API key>">Start Date</label>
<input
name="start-date"
value={formatDate(internshipDetails.startDate)}
readOnly
// onChange={onChange}
id="<API key>"
placeholder="Enter the starting date.."
/>
</Form.Field>
<Form.Field>
<label htmlFor="<API key>">Duration (in months)</label>
<input
name="duration"
value={internshipDetails.duration}
readOnly
// onChange={onChange}
id="<API key>"
placeholder="Enter the number of months..."
/>
</Form.Field>
<Form.Field>
<label htmlFor="submit-post-stipend">Stipend (₹)</label>
<input
name="stipend"
value={internshipDetails.stipend}
readOnly
// onChange={onChange}
id="submit-post-stipend"
type="number"
placeholder="Enter the stipend..."
/>
</Form.Field>
<Form.Field>
<label htmlFor="<API key>">Apply by</label>
<input
name="apply-by"
value={formatDate(internshipDetails.applyBy)}
readOnly
// onChange={onChange}
id="<API key>"
placeholder="Enter the last date of application..."
/>
</Form.Field>
</Form.Group>
<Form.Field>
<label htmlFor="<API key>">About</label>
<textarea
name="description-about"
value={internshipDetails.description.about}
readOnly
// onChange={onChange}
rows="5"
id="<API key>"
placeholder="Enter internship details..."
/>
</Form.Field>
<Form.Field>
<label htmlFor="<API key>">Who can apply</label>
<textarea
readOnly
name="<API key>"
value={internshipDetails.description.whoCanApply}
// onChange={onChange}
rows="5"
id="<API key>"
placeholder="Who can apply for this internship?"
/>
</Form.Field>
<Form.Field>
<label htmlFor="<API key>">Perks</label>
<textarea
name="description-perks"
readOnly
value={internshipDetails.description.perks}
// onChange={onChange}
rows="5"
id="<API key>"
placeholder="Enter internship perks details..."
/>
</Form.Field>
</Form>
</div>
);
DisplayPost.propTypes = {
internshipDetails: PropTypes.shape({
position: PropTypes.string.isRequired,
company: PropTypes.string.isRequired,
location: PropTypes.string.isRequired,
startDate: PropTypes.string.isRequired,
duration: PropTypes.string.isRequired,
stipend: PropTypes.string.isRequired,
applyBy: PropTypes.string.isRequired,
description: PropTypes.object.isRequired,
}).isRequired,
};
export default DisplayPost; |
name: CentOS 6.4 x86_64 [notes]
description: CentOS 6.4 x86_64 [<a href="https://github.com/2creatives/vagrant-centos/releases/tag/v0.1.0">notes</a>]
provider: VirtualBox
link: https://github.com/2creatives/vagrant-centos/releases/download/v0.1.0/<API key>.box
size: 301.5 MB
category: boxes
note: Retrived from vagrantbox.es
arch: x86_64
tags:
- centos
date: '2014-02-16' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.