code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
import scala.reflect.macros.blackbox.Context import language.experimental.macros object Macros { def impl1_0_0(c: Context)() = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl1_1_1(c: Context)(x: c.Expr[Int]) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl1_2_2(c: Context)(x: c.Expr[Int], y: c.Expr[Int]) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def m1_0_0() = macro impl1_0_0 def m1_1_1(x: Int) = macro impl1_1_1 def m1_2_2(x: Int, y: Int) = macro impl1_2_2 def impl1_0_inf(c: Context)(x: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl1_1_inf(c: Context)(x: c.Expr[Int], y: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl1_2_inf(c: Context)(x: c.Expr[Int], y: c.Expr[Int], z: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def m1_0_inf(x: Int*) = macro impl1_0_inf def m1_1_inf(x: Int, y: Int*) = macro impl1_1_inf def m1_2_inf(x: Int, y: Int, z: Int*) = macro impl1_2_inf def impl2_0_0(c: Context)()() = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl2_1_1(c: Context)()(x: c.Expr[Int]) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl2_2_2(c: Context)()(x: c.Expr[Int], y: c.Expr[Int]) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def m2_0_0()() = macro impl2_0_0 def m2_1_1()(x: Int) = macro impl2_1_1 def m2_2_2()(x: Int, y: Int) = macro impl2_2_2 def impl2_0_inf(c: Context)()(x: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl2_1_inf(c: Context)()(x: c.Expr[Int], y: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def impl2_2_inf(c: Context)()(x: c.Expr[Int], y: c.Expr[Int], z: c.Expr[Int]*) = { import c.universe._; c.Expr[Unit](q"""println("hello world")""") } def m2_0_inf()(x: Int*) = macro impl2_0_inf def m2_1_inf()(x: Int, y: Int*) = macro impl2_1_inf def m2_2_inf()(x: Int, y: Int, z: Int*) = macro impl2_2_inf }
felixmulder/scala
test/files/neg/t7157/Impls_Macros_1.scala
Scala
bsd-3-clause
2,174
#ifdef COMPILE_EXAMPLE1_CODE_MODSERIAL /* * To run this test program, link p9 to p10 so the Serial loops * back and receives characters it sends. */ #include "mbed.h" #include "MODSERIAL.h" DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); DigitalOut led4(LED4); MODSERIAL pc(USBTX, USBRX); /* * As experiement, you can define MODSERIAL as show here and see what * effects it has on the LEDs. * * MODSERIAL uart(TX_PIN, RX_PIN, 512); * With this, the 512 characters sent can straight into the buffer * vary quickly. This means LED1 is only on briefly as the TX buffer * fills. * * MODSERIAL uart(TX_PIN, RX_PIN, 32); * With this, the buffer is smaller than the default 256 bytes and * therefore LED1 stays on much longer while the system waits for * room in the TX buffer. */ MODSERIAL uart(TX_PIN, RX_PIN); // This function is called when a character goes from the TX buffer // to the Uart THR FIFO register. void txCallback(MODSERIAL_IRQ_INFO *q) { led2 = !led2; } // This function is called when TX buffer goes empty void txEmpty(MODSERIAL_IRQ_INFO *q) { led2 = 0; pc.puts(" Done. "); } // This function is called when a character goes into the RX buffer. void rxCallback(MODSERIAL_IRQ_INFO *q) { led3 = !led3; pc.putc(uart.getc()); } int main() { int c = 'A'; // Ensure the baud rate for the PC "USB" serial is much // higher than "uart" baud rate below. pc.baud(PC_BAUD); // Use a deliberatly slow baud to fill up the TX buffer uart.baud(1200); uart.attach(&txCallback, MODSERIAL::TxIrq); uart.attach(&rxCallback, MODSERIAL::RxIrq); uart.attach(&txEmpty, MODSERIAL::TxEmpty); // Loop sending characters. We send 512 // which is twice the default TX/RX buffer size. led1 = 1; // Show start of sending with LED1. for (int loop = 0; loop < 512; loop++) { uart.printf("%c", c); c++; if (c > 'Z') c = 'A'; } led1 = 0; // Show the end of sending by switching off LED1. // End program. Flash LED4. Notice how LED 2 and 3 continue // to flash for a short period while the interrupt system // continues to send the characters left in the TX buffer. while(1) { led4 = !led4; wait(0.25); } } /* * Notes. Here is the sort of output you can expect on your PC/Mac/Linux host * machine that is connected to the "pc" USB serial port. * * ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUV * WXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQR * STUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMN * OPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ * KLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEF * GHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZAB * CDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQ Done. R * * Of interest is that last "R" character after the system has said "Done." * This comes from the fact that the TxEmpty callback is made when the TX buffer * becomes empty. MODSERIAL makes use of the fact that the Uarts built into the * LPC17xx device use a 16 byte FIFO on both RX and TX channels. This means that * when the TxEmpty callback is made, the TX buffer is empty, but that just means * the "last few characters" were written to the TX FIFO. So although the TX * buffer has gone empty, the Uart's transmit system is still sending any remaining * characters from it's TX FIFO. If you want to be truely sure all the characters * you have sent have left the Mbed then call txIsBusy(); This function will * return true if characters are still being sent. If it returns false after * the Tx buffer is empty then all your characters have been sent. * * In a similar way, when characters are received into the RX FIFO, the entire * FIFO contents is moved to the RX buffer, assuming there is room left in the * RX buffer. If there is not, any remaining characters are left in the RX FIFO * and will be moved to the RX buffer on the next interrupt or when the running * program removes a character(s) from the RX buffer with the getc() method. */ #endif
CMUBOOST/BOOST_Stalker
rosserial/rosserial_mbed/src/ros_lib/MODSERIAL/example1.cpp
C++
bsd-3-clause
4,310
/* Write a Program detab,which replaces tabs in the input with a proper number of blanks to spaces */ #include<stdio.h> #define TABINC 8 int main(void) { int nb,pos,c; nb = 0; pos = 1; while((c=getchar())!=EOF) { if( c == '\t') { nb = TABINC - (( pos - 1) % TABINC); while( nb > 0) { putchar('#'); ++pos; --nb; } } else if( c == '\n') { putchar(c); pos = 1; } else { putchar(c); ++pos; } } return 0; }
beqa2323/learntosolveit
languages/cprogs/Ex_1.20_detab.c
C
bsd-3-clause
472
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/ip_endpoint.h" #include <ostream> #include <string.h> #include <tuple> #include "base/check.h" #include "base/check_op.h" #include "base/notreached.h" #include "base/strings/string_number_conversions.h" #include "base/sys_byteorder.h" #include "build/build_config.h" #include "net/base/ip_address.h" #include "net/base/sys_addrinfo.h" #if BUILDFLAG(IS_WIN) #include <winsock2.h> #include <ws2bth.h> #include "net/base/winsock_util.h" // For kBluetoothAddressSize #endif namespace net { IPEndPoint::IPEndPoint() = default; IPEndPoint::~IPEndPoint() = default; IPEndPoint::IPEndPoint(const IPAddress& address, uint16_t port) : address_(address), port_(port) {} IPEndPoint::IPEndPoint(const IPEndPoint& endpoint) = default; uint16_t IPEndPoint::port() const { #if BUILDFLAG(IS_WIN) DCHECK_NE(address_.size(), kBluetoothAddressSize); #endif return port_; } AddressFamily IPEndPoint::GetFamily() const { return GetAddressFamily(address_); } int IPEndPoint::GetSockAddrFamily() const { switch (address_.size()) { case IPAddress::kIPv4AddressSize: return AF_INET; case IPAddress::kIPv6AddressSize: return AF_INET6; #if BUILDFLAG(IS_WIN) case kBluetoothAddressSize: return AF_BTH; #endif default: NOTREACHED() << "Bad IP address"; return AF_UNSPEC; } } bool IPEndPoint::ToSockAddr(struct sockaddr* address, socklen_t* address_length) const { // By definition, socklen_t is large enough to hold both sizes. constexpr socklen_t kSockaddrInSize = static_cast<socklen_t>(sizeof(struct sockaddr_in)); constexpr socklen_t kSockaddrIn6Size = static_cast<socklen_t>(sizeof(struct sockaddr_in6)); DCHECK(address); DCHECK(address_length); #if BUILDFLAG(IS_WIN) DCHECK_NE(address_.size(), kBluetoothAddressSize); #endif switch (address_.size()) { case IPAddress::kIPv4AddressSize: { if (*address_length < kSockaddrInSize) return false; *address_length = kSockaddrInSize; struct sockaddr_in* addr = reinterpret_cast<struct sockaddr_in*>(address); memset(addr, 0, sizeof(struct sockaddr_in)); addr->sin_family = AF_INET; addr->sin_port = base::HostToNet16(port_); memcpy(&addr->sin_addr, address_.bytes().data(), IPAddress::kIPv4AddressSize); break; } case IPAddress::kIPv6AddressSize: { if (*address_length < kSockaddrIn6Size) return false; *address_length = kSockaddrIn6Size; struct sockaddr_in6* addr6 = reinterpret_cast<struct sockaddr_in6*>(address); memset(addr6, 0, sizeof(struct sockaddr_in6)); addr6->sin6_family = AF_INET6; addr6->sin6_port = base::HostToNet16(port_); memcpy(&addr6->sin6_addr, address_.bytes().data(), IPAddress::kIPv6AddressSize); break; } default: return false; } return true; } bool IPEndPoint::FromSockAddr(const struct sockaddr* sock_addr, socklen_t sock_addr_len) { DCHECK(sock_addr); switch (sock_addr->sa_family) { case AF_INET: { if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in))) return false; const struct sockaddr_in* addr = reinterpret_cast<const struct sockaddr_in*>(sock_addr); *this = IPEndPoint( IPAddress(reinterpret_cast<const uint8_t*>(&addr->sin_addr), IPAddress::kIPv4AddressSize), base::NetToHost16(addr->sin_port)); return true; } case AF_INET6: { if (sock_addr_len < static_cast<socklen_t>(sizeof(struct sockaddr_in6))) return false; const struct sockaddr_in6* addr = reinterpret_cast<const struct sockaddr_in6*>(sock_addr); *this = IPEndPoint( IPAddress(reinterpret_cast<const uint8_t*>(&addr->sin6_addr), IPAddress::kIPv6AddressSize), base::NetToHost16(addr->sin6_port)); return true; } #if BUILDFLAG(IS_WIN) case AF_BTH: { if (sock_addr_len < static_cast<socklen_t>(sizeof(SOCKADDR_BTH))) return false; const SOCKADDR_BTH* addr = reinterpret_cast<const SOCKADDR_BTH*>(sock_addr); *this = IPEndPoint(); address_ = IPAddress(reinterpret_cast<const uint8_t*>(&addr->btAddr), kBluetoothAddressSize); // Intentionally ignoring Bluetooth port. It is a ULONG, but // `IPEndPoint::port_` is a uint16_t. See https://crbug.com/1231273. return true; } #endif } return false; // Unrecognized |sa_family|. } std::string IPEndPoint::ToString() const { #if BUILDFLAG(IS_WIN) DCHECK_NE(address_.size(), kBluetoothAddressSize); #endif return IPAddressToStringWithPort(address_, port_); } std::string IPEndPoint::ToStringWithoutPort() const { #if BUILDFLAG(IS_WIN) DCHECK_NE(address_.size(), kBluetoothAddressSize); #endif return address_.ToString(); } bool IPEndPoint::operator<(const IPEndPoint& other) const { // Sort IPv4 before IPv6. if (address_.size() != other.address_.size()) { return address_.size() < other.address_.size(); } return std::tie(address_, port_) < std::tie(other.address_, other.port_); } bool IPEndPoint::operator==(const IPEndPoint& other) const { return address_ == other.address_ && port_ == other.port_; } bool IPEndPoint::operator!=(const IPEndPoint& that) const { return !(*this == that); } std::ostream& operator<<(std::ostream& os, const IPEndPoint& ip_endpoint) { return os << ip_endpoint.ToString(); } } // namespace net
chromium/chromium
net/base/ip_endpoint.cc
C++
bsd-3-clause
5,740
//===- Intrinsics.h - LLVM Intrinsic Function Handling ----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines a set of enums which allow processing of intrinsic // functions. Values of these enum types are returned by // Function::getIntrinsicID. // //===----------------------------------------------------------------------===// #ifndef LLVM_IR_INTRINSICS_H #define LLVM_IR_INTRINSICS_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include <string> namespace llvm { class Type; class FunctionType; class Function; class LLVMContext; class Module; class AttributeList; /// This namespace contains an enum with a value for every intrinsic/builtin /// function known by LLVM. The enum values are returned by /// Function::getIntrinsicID(). namespace Intrinsic { // Intrinsic ID type. This is an opaque typedef to facilitate splitting up // the enum into target-specific enums. typedef unsigned ID; enum IndependentIntrinsics : unsigned { not_intrinsic = 0, // Must be zero // Get the intrinsic enums generated from Intrinsics.td #define GET_INTRINSIC_ENUM_VALUES #include "llvm/IR/IntrinsicEnums.inc" #undef GET_INTRINSIC_ENUM_VALUES }; /// Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx". /// Note, this version is for intrinsics with no overloads. Use the other /// version of getName if overloads are required. StringRef getName(ID id); /// Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx". /// Note, this version of getName supports overloads, but is less efficient /// than the StringRef version of this function. If no overloads are /// requried, it is safe to use this version, but better to use the StringRef /// version. std::string getName(ID id, ArrayRef<Type*> Tys); /// Return the function type for an intrinsic. FunctionType *getType(LLVMContext &Context, ID id, ArrayRef<Type*> Tys = None); /// Returns true if the intrinsic can be overloaded. bool isOverloaded(ID id); /// Returns true if the intrinsic is a leaf, i.e. it does not make any calls /// itself. Most intrinsics are leafs, the exceptions being the patchpoint /// and statepoint intrinsics. These call (or invoke) their "target" argument. bool isLeaf(ID id); /// Return the attributes for an intrinsic. AttributeList getAttributes(LLVMContext &C, ID id); /// Create or insert an LLVM Function declaration for an intrinsic, and return /// it. /// /// The Tys parameter is for intrinsics with overloaded types (e.g., those /// using iAny, fAny, vAny, or iPTRAny). For a declaration of an overloaded /// intrinsic, Tys must provide exactly one type for each overloaded type in /// the intrinsic. Function *getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys = None); /// Looks up Name in NameTable via binary search. NameTable must be sorted /// and all entries must start with "llvm.". If NameTable contains an exact /// match for Name or a prefix of Name followed by a dot, its index in /// NameTable is returned. Otherwise, -1 is returned. int lookupLLVMIntrinsicByName(ArrayRef<const char *> NameTable, StringRef Name); /// Map a GCC builtin name to an intrinsic ID. ID getIntrinsicForGCCBuiltin(const char *Prefix, StringRef BuiltinName); /// Map a MS builtin name to an intrinsic ID. ID getIntrinsicForMSBuiltin(const char *Prefix, StringRef BuiltinName); /// This is a type descriptor which explains the type requirements of an /// intrinsic. This is returned by getIntrinsicInfoTableEntries. struct IITDescriptor { enum IITDescriptorKind { Void, VarArg, MMX, Token, Metadata, Half, Float, Double, Quad, Integer, Vector, Pointer, Struct, Argument, ExtendArgument, TruncArgument, HalfVecArgument, SameVecWidthArgument, PtrToArgument, PtrToElt, VecOfAnyPtrsToElt, VecElementArgument, ScalableVecArgument, Subdivide2Argument, Subdivide4Argument, VecOfBitcastsToInt } Kind; union { unsigned Integer_Width; unsigned Float_Width; unsigned Vector_Width; unsigned Pointer_AddressSpace; unsigned Struct_NumElements; unsigned Argument_Info; }; enum ArgKind { AK_Any, AK_AnyInteger, AK_AnyFloat, AK_AnyVector, AK_AnyPointer, AK_MatchType = 7 }; unsigned getArgumentNumber() const { assert(Kind == Argument || Kind == ExtendArgument || Kind == TruncArgument || Kind == HalfVecArgument || Kind == SameVecWidthArgument || Kind == PtrToArgument || Kind == PtrToElt || Kind == VecElementArgument || Kind == Subdivide2Argument || Kind == Subdivide4Argument || Kind == VecOfBitcastsToInt); return Argument_Info >> 3; } ArgKind getArgumentKind() const { assert(Kind == Argument || Kind == ExtendArgument || Kind == TruncArgument || Kind == HalfVecArgument || Kind == SameVecWidthArgument || Kind == PtrToArgument || Kind == VecElementArgument || Kind == Subdivide2Argument || Kind == Subdivide4Argument || Kind == VecOfBitcastsToInt); return (ArgKind)(Argument_Info & 7); } // VecOfAnyPtrsToElt uses both an overloaded argument (for address space) // and a reference argument (for matching vector width and element types) unsigned getOverloadArgNumber() const { assert(Kind == VecOfAnyPtrsToElt); return Argument_Info >> 16; } unsigned getRefArgNumber() const { assert(Kind == VecOfAnyPtrsToElt); return Argument_Info & 0xFFFF; } static IITDescriptor get(IITDescriptorKind K, unsigned Field) { IITDescriptor Result = { K, { Field } }; return Result; } static IITDescriptor get(IITDescriptorKind K, unsigned short Hi, unsigned short Lo) { unsigned Field = Hi << 16 | Lo; IITDescriptor Result = {K, {Field}}; return Result; } }; /// Return the IIT table descriptor for the specified intrinsic into an array /// of IITDescriptors. void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl<IITDescriptor> &T); enum MatchIntrinsicTypesResult { MatchIntrinsicTypes_Match = 0, MatchIntrinsicTypes_NoMatchRet = 1, MatchIntrinsicTypes_NoMatchArg = 2, }; /// Match the specified function type with the type constraints specified by /// the .td file. If the given type is an overloaded type it is pushed to the /// ArgTys vector. /// /// Returns false if the given type matches with the constraints, true /// otherwise. MatchIntrinsicTypesResult matchIntrinsicSignature(FunctionType *FTy, ArrayRef<IITDescriptor> &Infos, SmallVectorImpl<Type *> &ArgTys); /// Verify if the intrinsic has variable arguments. This method is intended to /// be called after all the fixed arguments have been matched first. /// /// This method returns true on error. bool matchIntrinsicVarArg(bool isVarArg, ArrayRef<IITDescriptor> &Infos); // Checks if the intrinsic name matches with its signature and if not // returns the declaration with the same signature and remangled name. llvm::Optional<Function*> remangleIntrinsicFunction(Function *F); } // End Intrinsic namespace } // End llvm namespace #endif
endlessm/chromium-browser
third_party/swiftshader/third_party/llvm-10.0/llvm/include/llvm/IR/Intrinsics.h
C
bsd-3-clause
7,692
#ifndef ERBGENERATOR_H #define ERBGENERATOR_H #include <QStringList> #include <QDir> #include <QPair> #include <QVariant> class ErbGenerator { public: ErbGenerator(const QString &view, const QList<QPair<QString, QVariant::Type>> &fields, int pkIdx, int autoValIdx); bool generate(const QString &dstDir) const; private: QString viewName; QList<QPair<QString, QVariant::Type>> fieldList; int primaryKeyIndex; int autoValueIndex; }; #endif // ERBGENERATOR_H
froglogic/treefrog-framework
tools/tspawn/erbgenerator.h
C
bsd-3-clause
484
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SPEECH_SPEECH_RECOGNITION_TEST_HELPER_H_ #define CHROME_BROWSER_SPEECH_SPEECH_RECOGNITION_TEST_HELPER_H_ #include <memory> #include <string> #include <vector> class KeyedService; class Profile; namespace base { struct Feature; } // namespace base namespace content { class BrowserContext; class FakeSpeechRecognitionManager; } // namespace content namespace speech { class FakeSpeechRecognitionService; enum class SpeechRecognitionType; } // namespace speech // This class provides on-device and network speech recognition test // infrastructure. Test classes can use this one to easily interact with // speech recognizers. For example: // // SpeechRecognitionTestHelper* test_helper_ = ...; // SpeechRecognizer* recognizer->Start(); // test_helper_->WaitForRecognitionStarted(); // ... Continue with test ... // // For examples, please see SpeechRecognitionPrivateBaseTest or // DictationBaseTest. class SpeechRecognitionTestHelper { public: explicit SpeechRecognitionTestHelper(speech::SpeechRecognitionType type); ~SpeechRecognitionTestHelper(); SpeechRecognitionTestHelper(const SpeechRecognitionTestHelper&) = delete; SpeechRecognitionTestHelper& operator=(const SpeechRecognitionTestHelper&) = delete; // Sets up either on-device or network speech recognition. void SetUp(Profile* profile); // Waits for the speech recognition service to start. void WaitForRecognitionStarted(); // Waits for the speech recognition service to stop. void WaitForRecognitionStopped(); // Sends a fake speech result and waits for tasks to finish. void SendFakeSpeechResultAndWait(const std::string& transcript, bool is_final); // Similar to above, but ensures that `is_final` is true. void SendFinalFakeSpeechResultAndWait(const std::string& transcript); // Sends a fake speech recognition error and waits for tasks to finish. void SendFakeSpeechRecognitionErrorAndWait(); // Returns a list of features that should be enabled. std::vector<base::Feature> GetEnabledFeatures(); // Returns a list of features that should be disabled. std::vector<base::Feature> GetDisabledFeatures(); private: // Methods for setup. void SetUpNetworkRecognition(); void SetUpOnDeviceRecognition(Profile* profile); std::unique_ptr<KeyedService> CreateTestOnDeviceSpeechRecognitionService( content::BrowserContext* context); speech::SpeechRecognitionType type_; // For network recognition. std::unique_ptr<content::FakeSpeechRecognitionManager> fake_speech_recognition_manager_; // For on-device recognition. KeyedService owned by the test profile. speech::FakeSpeechRecognitionService* fake_service_; }; #endif // CHROME_BROWSER_SPEECH_SPEECH_RECOGNITION_TEST_HELPER_H_
ric2b/Vivaldi-browser
chromium/chrome/browser/speech/speech_recognition_test_helper.h
C
bsd-3-clause
2,950
/* * This file is part of wl1251 * * Copyright (c) 1998-2007 Texas Instruments Incorporated * Copyright (C) 2008 Nokia Corporation * * Contact: Kalle Valo <kalle.valo@nokia.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <linux/kernel.h> #include <linux/module.h> #include "wl1251.h" #include "wl1251_reg.h" #include "wl1251_tx.h" #include "wl1251_ps.h" #include "wl1251_io.h" static bool wl1251_tx_double_buffer_busy(struct wl1251 *wl, u32 data_out_count) { int used, data_in_count; data_in_count = wl->data_in_count; if (data_in_count < data_out_count) /* data_in_count has wrapped */ data_in_count += TX_STATUS_DATA_OUT_COUNT_MASK + 1; used = data_in_count - data_out_count; WARN_ON(used < 0); WARN_ON(used > DP_TX_PACKET_RING_CHUNK_NUM); if (used >= DP_TX_PACKET_RING_CHUNK_NUM) return true; else return false; } static int wl1251_tx_path_status(struct wl1251 *wl) { u32 status, addr, data_out_count; bool busy; addr = wl->data_path->tx_control_addr; status = wl1251_mem_read32(wl, addr); data_out_count = status & TX_STATUS_DATA_OUT_COUNT_MASK; busy = wl1251_tx_double_buffer_busy(wl, data_out_count); if (busy) return -EBUSY; return 0; } static int wl1251_tx_id(struct wl1251 *wl, struct sk_buff *skb) { int i; for (i = 0; i < FW_TX_CMPLT_BLOCK_SIZE; i++) if (wl->tx_frames[i] == NULL) { wl->tx_frames[i] = skb; return i; } return -EBUSY; } static void wl1251_tx_control(struct tx_double_buffer_desc *tx_hdr, struct ieee80211_tx_info *control, u16 fc) { *(u16 *)&tx_hdr->control = 0; tx_hdr->control.rate_policy = 0; /* 802.11 packets */ tx_hdr->control.packet_type = 0; if (control->flags & IEEE80211_TX_CTL_NO_ACK) tx_hdr->control.ack_policy = 1; tx_hdr->control.tx_complete = 1; if ((fc & IEEE80211_FTYPE_DATA) && ((fc & IEEE80211_STYPE_QOS_DATA) || (fc & IEEE80211_STYPE_QOS_NULLFUNC))) tx_hdr->control.qos = 1; } /* RSN + MIC = 8 + 8 = 16 bytes (worst case - AES). */ #define MAX_MSDU_SECURITY_LENGTH 16 #define MAX_MPDU_SECURITY_LENGTH 16 #define WLAN_QOS_HDR_LEN 26 #define MAX_MPDU_HEADER_AND_SECURITY (MAX_MPDU_SECURITY_LENGTH + \ WLAN_QOS_HDR_LEN) #define HW_BLOCK_SIZE 252 static void wl1251_tx_frag_block_num(struct tx_double_buffer_desc *tx_hdr) { u16 payload_len, frag_threshold, mem_blocks; u16 num_mpdus, mem_blocks_per_frag; frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD; tx_hdr->frag_threshold = cpu_to_le16(frag_threshold); payload_len = tx_hdr->length + MAX_MSDU_SECURITY_LENGTH; if (payload_len > frag_threshold) { mem_blocks_per_frag = ((frag_threshold + MAX_MPDU_HEADER_AND_SECURITY) / HW_BLOCK_SIZE) + 1; num_mpdus = payload_len / frag_threshold; mem_blocks = num_mpdus * mem_blocks_per_frag; payload_len -= num_mpdus * frag_threshold; num_mpdus++; } else { mem_blocks_per_frag = 0; mem_blocks = 0; num_mpdus = 1; } mem_blocks += (payload_len / HW_BLOCK_SIZE) + 1; if (num_mpdus > 1) mem_blocks += min(num_mpdus, mem_blocks_per_frag); tx_hdr->num_mem_blocks = mem_blocks; } static int wl1251_tx_fill_hdr(struct wl1251 *wl, struct sk_buff *skb, struct ieee80211_tx_info *control) { struct tx_double_buffer_desc *tx_hdr; struct ieee80211_rate *rate; int id; u16 fc; if (!skb) return -EINVAL; id = wl1251_tx_id(wl, skb); if (id < 0) return id; fc = *(u16 *)skb->data; tx_hdr = (struct tx_double_buffer_desc *) skb_push(skb, sizeof(*tx_hdr)); tx_hdr->length = cpu_to_le16(skb->len - sizeof(*tx_hdr)); rate = ieee80211_get_tx_rate(wl->hw, control); tx_hdr->rate = cpu_to_le16(rate->hw_value); tx_hdr->expiry_time = cpu_to_le32(1 << 16); tx_hdr->id = id; /* FIXME: how to get the correct queue id? */ tx_hdr->xmit_queue = 0; wl1251_tx_control(tx_hdr, control, fc); wl1251_tx_frag_block_num(tx_hdr); return 0; } /* We copy the packet to the target */ static int wl1251_tx_send_packet(struct wl1251 *wl, struct sk_buff *skb, struct ieee80211_tx_info *control) { struct tx_double_buffer_desc *tx_hdr; int len; u32 addr; if (!skb) return -EINVAL; tx_hdr = (struct tx_double_buffer_desc *) skb->data; if (control->control.hw_key && control->control.hw_key->alg == ALG_TKIP) { int hdrlen; u16 fc; u8 *pos; fc = *(u16 *)(skb->data + sizeof(*tx_hdr)); tx_hdr->length += WL1251_TKIP_IV_SPACE; hdrlen = ieee80211_hdrlen(fc); pos = skb_push(skb, WL1251_TKIP_IV_SPACE); memmove(pos, pos + WL1251_TKIP_IV_SPACE, sizeof(*tx_hdr) + hdrlen); } /* Revisit. This is a workaround for getting non-aligned packets. This happens at least with EAPOL packets from the user space. Our DMA requires packets to be aligned on a 4-byte boundary. */ if (unlikely((long)skb->data & 0x03)) { int offset = (4 - (long)skb->data) & 0x03; wl1251_debug(DEBUG_TX, "skb offset %d", offset); /* check whether the current skb can be used */ if (!skb_cloned(skb) && (skb_tailroom(skb) >= offset)) { unsigned char *src = skb->data; /* align the buffer on a 4-byte boundary */ skb_reserve(skb, offset); memmove(skb->data, src, skb->len); } else { wl1251_info("No handler, fixme!"); return -EINVAL; } } /* Our skb->data at this point includes the HW header */ len = WL1251_TX_ALIGN(skb->len); if (wl->data_in_count & 0x1) addr = wl->data_path->tx_packet_ring_addr + wl->data_path->tx_packet_ring_chunk_size; else addr = wl->data_path->tx_packet_ring_addr; wl1251_mem_write(wl, addr, skb->data, len); wl1251_debug(DEBUG_TX, "tx id %u skb 0x%p payload %u rate 0x%x", tx_hdr->id, skb, tx_hdr->length, tx_hdr->rate); return 0; } static void wl1251_tx_trigger(struct wl1251 *wl) { u32 data, addr; if (wl->data_in_count & 0x1) { addr = ACX_REG_INTERRUPT_TRIG_H; data = INTR_TRIG_TX_PROC1; } else { addr = ACX_REG_INTERRUPT_TRIG; data = INTR_TRIG_TX_PROC0; } wl1251_reg_write32(wl, addr, data); /* Bumping data in */ wl->data_in_count = (wl->data_in_count + 1) & TX_STATUS_DATA_OUT_COUNT_MASK; } /* caller must hold wl->mutex */ static int wl1251_tx_frame(struct wl1251 *wl, struct sk_buff *skb) { struct ieee80211_tx_info *info; int ret = 0; u8 idx; info = IEEE80211_SKB_CB(skb); if (info->control.hw_key) { idx = info->control.hw_key->hw_key_idx; if (unlikely(wl->default_key != idx)) { ret = wl1251_acx_default_key(wl, idx); if (ret < 0) return ret; } } ret = wl1251_tx_path_status(wl); if (ret < 0) return ret; ret = wl1251_tx_fill_hdr(wl, skb, info); if (ret < 0) return ret; ret = wl1251_tx_send_packet(wl, skb, info); if (ret < 0) return ret; wl1251_tx_trigger(wl); return ret; } void wl1251_tx_work(struct work_struct *work) { struct wl1251 *wl = container_of(work, struct wl1251, tx_work); struct sk_buff *skb; bool woken_up = false; int ret; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1251_STATE_OFF)) goto out; while ((skb = skb_dequeue(&wl->tx_queue))) { if (!woken_up) { ret = wl1251_ps_elp_wakeup(wl); if (ret < 0) goto out; woken_up = true; } ret = wl1251_tx_frame(wl, skb); if (ret == -EBUSY) { /* firmware buffer is full, stop queues */ wl1251_debug(DEBUG_TX, "tx_work: fw buffer full, " "stop queues"); ieee80211_stop_queues(wl->hw); wl->tx_queue_stopped = true; skb_queue_head(&wl->tx_queue, skb); goto out; } else if (ret < 0) { dev_kfree_skb(skb); goto out; } } out: if (woken_up) wl1251_ps_elp_sleep(wl); mutex_unlock(&wl->mutex); } static const char *wl1251_tx_parse_status(u8 status) { /* 8 bit status field, one character per bit plus null */ static char buf[9]; int i = 0; memset(buf, 0, sizeof(buf)); if (status & TX_DMA_ERROR) buf[i++] = 'm'; if (status & TX_DISABLED) buf[i++] = 'd'; if (status & TX_RETRY_EXCEEDED) buf[i++] = 'r'; if (status & TX_TIMEOUT) buf[i++] = 't'; if (status & TX_KEY_NOT_FOUND) buf[i++] = 'k'; if (status & TX_ENCRYPT_FAIL) buf[i++] = 'e'; if (status & TX_UNAVAILABLE_PRIORITY) buf[i++] = 'p'; /* bit 0 is unused apparently */ return buf; } static void wl1251_tx_packet_cb(struct wl1251 *wl, struct tx_result *result) { struct ieee80211_tx_info *info; struct sk_buff *skb; int hdrlen, ret; u8 *frame; skb = wl->tx_frames[result->id]; if (skb == NULL) { wl1251_error("SKB for packet %d is NULL", result->id); return; } info = IEEE80211_SKB_CB(skb); if (!(info->flags & IEEE80211_TX_CTL_NO_ACK) && (result->status == TX_SUCCESS)) info->flags |= IEEE80211_TX_STAT_ACK; info->status.rates[0].count = result->ack_failures + 1; wl->stats.retry_count += result->ack_failures; /* * We have to remove our private TX header before pushing * the skb back to mac80211. */ frame = skb_pull(skb, sizeof(struct tx_double_buffer_desc)); if (info->control.hw_key && info->control.hw_key->alg == ALG_TKIP) { hdrlen = ieee80211_get_hdrlen_from_skb(skb); memmove(frame + WL1251_TKIP_IV_SPACE, frame, hdrlen); skb_pull(skb, WL1251_TKIP_IV_SPACE); } wl1251_debug(DEBUG_TX, "tx status id %u skb 0x%p failures %u rate 0x%x" " status 0x%x (%s)", result->id, skb, result->ack_failures, result->rate, result->status, wl1251_tx_parse_status(result->status)); ieee80211_tx_status(wl->hw, skb); wl->tx_frames[result->id] = NULL; if (wl->tx_queue_stopped) { wl1251_debug(DEBUG_TX, "cb: queue was stopped"); skb = skb_dequeue(&wl->tx_queue); /* The skb can be NULL because tx_work might have been scheduled before the queue was stopped making the queue empty */ if (skb) { ret = wl1251_tx_frame(wl, skb); if (ret == -EBUSY) { /* firmware buffer is still full */ wl1251_debug(DEBUG_TX, "cb: fw buffer " "still full"); skb_queue_head(&wl->tx_queue, skb); return; } else if (ret < 0) { dev_kfree_skb(skb); return; } } wl1251_debug(DEBUG_TX, "cb: waking queues"); ieee80211_wake_queues(wl->hw); wl->tx_queue_stopped = false; } } /* Called upon reception of a TX complete interrupt */ void wl1251_tx_complete(struct wl1251 *wl) { int i, result_index, num_complete = 0; struct tx_result result[FW_TX_CMPLT_BLOCK_SIZE], *result_ptr; if (unlikely(wl->state != WL1251_STATE_ON)) return; /* First we read the result */ wl1251_mem_read(wl, wl->data_path->tx_complete_addr, result, sizeof(result)); result_index = wl->next_tx_complete; for (i = 0; i < ARRAY_SIZE(result); i++) { result_ptr = &result[result_index]; if (result_ptr->done_1 == 1 && result_ptr->done_2 == 1) { wl1251_tx_packet_cb(wl, result_ptr); result_ptr->done_1 = 0; result_ptr->done_2 = 0; result_index = (result_index + 1) & (FW_TX_CMPLT_BLOCK_SIZE - 1); num_complete++; } else { break; } } /* Every completed frame needs to be acknowledged */ if (num_complete) { /* * If we've wrapped, we have to clear * the results in 2 steps. */ if (result_index > wl->next_tx_complete) { /* Only 1 write is needed */ wl1251_mem_write(wl, wl->data_path->tx_complete_addr + (wl->next_tx_complete * sizeof(struct tx_result)), &result[wl->next_tx_complete], num_complete * sizeof(struct tx_result)); } else if (result_index < wl->next_tx_complete) { /* 2 writes are needed */ wl1251_mem_write(wl, wl->data_path->tx_complete_addr + (wl->next_tx_complete * sizeof(struct tx_result)), &result[wl->next_tx_complete], (FW_TX_CMPLT_BLOCK_SIZE - wl->next_tx_complete) * sizeof(struct tx_result)); wl1251_mem_write(wl, wl->data_path->tx_complete_addr, result, (num_complete - FW_TX_CMPLT_BLOCK_SIZE + wl->next_tx_complete) * sizeof(struct tx_result)); } else { /* We have to write the whole array */ wl1251_mem_write(wl, wl->data_path->tx_complete_addr, result, FW_TX_CMPLT_BLOCK_SIZE * sizeof(struct tx_result)); } } wl->next_tx_complete = result_index; } /* caller must hold wl->mutex */ void wl1251_tx_flush(struct wl1251 *wl) { int i; struct sk_buff *skb; struct ieee80211_tx_info *info; /* TX failure */ /* control->flags = 0; FIXME */ while ((skb = skb_dequeue(&wl->tx_queue))) { info = IEEE80211_SKB_CB(skb); wl1251_debug(DEBUG_TX, "flushing skb 0x%p", skb); if (!(info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS)) continue; ieee80211_tx_status(wl->hw, skb); } for (i = 0; i < FW_TX_CMPLT_BLOCK_SIZE; i++) if (wl->tx_frames[i] != NULL) { skb = wl->tx_frames[i]; info = IEEE80211_SKB_CB(skb); if (!(info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS)) continue; ieee80211_tx_status(wl->hw, skb); wl->tx_frames[i] = NULL; } }
go2ev-devteam/Gplus_2159_0801
openplatform/sdk/os/kernel-2.6.32/drivers/net/wireless/wl12xx/wl1251_tx.c
C
gpl-2.0
13,386
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.EventGrid { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<EventGridManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(EventGridManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the EventGridManagementClient /// </summary> public EventGridManagementClient Client { get; private set; } /// <summary> /// List available operations /// </summary> /// <remarks> /// List the available operations supported by the Microsoft.EventGrid resource /// provider /// </remarks> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IEnumerable<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.EventGrid/operations").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IEnumerable<Operation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
shahabhijeet/azure-sdk-for-net
src/SDKs/EventGrid/management/Management.EventGrid/Generated/Operations.cs
C#
mit
9,663
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean source html dirhtml singlehtml pickle \ json htmlhelp qthelp devhelp epub latex latexpdf \ text man changes linkcheck doctest gettext \ _gh-pages-assert-repo gh-pages-update gh-pages-push \ gh-pages-clone gh-pages-pull help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/*/* source: source/index.rst source/index.rst: ../README.rst source/tail.rest cat $^ > $@ html: source $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Requestel.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Requestel.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Requestel" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Requestel" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ## GitHub Pages REPO_URL = git@github.com:tkf/emacs-request.git # Check if build/html is really a git repository. Otherwise, # committing files in there is pretty dangerous as it might goes into # Jedi's master branch. _gh-pages-assert-repo: test -d build/html/.git gh-pages-clone: rm -rf build/html git clone --branch gh-pages $(REPO_URL) build/html gh-pages-pull: _gh-pages-assert-repo cd build/html && git pull gh-pages-update: _gh-pages-assert-repo clean html @echo "Update gh-pages" cd build/html/ && \ git add . && \ if [ -n "$$(git ls-files --deleted)" ]; then \ git ls-files --deleted | xargs git rm; \ fi && \ git commit -m "Update" gh-pages-push: _gh-pages-assert-repo cd build/html && git push -u origin gh-pages
sameedali/dotemacs
my-code/backup/libs/emacs-request/doc/Makefile
Makefile
mit
6,532
// coding: utf-8 // ---------------------------------------------------------------------------- /* Copyright (c) 2009, Roboterclub Aachen e.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Roboterclub Aachen e.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // ---------------------------------------------------------------------------- #include "count_type.hpp" std::size_t unittest::CountType::numberOfDefaultConstructorCalls = 0; std::size_t unittest::CountType::numberOfCopyConstructorCalls = 0; std::size_t unittest::CountType::numberOfAssignments = 0; std::size_t unittest::CountType::numberOfDestructorCalls = 0; std::size_t unittest::CountType::numberOfReallocs = 0; std::size_t unittest::CountType::numberOfOperations = 0; unittest::CountType::CountType() { ++numberOfDefaultConstructorCalls; ++numberOfOperations; } unittest::CountType::CountType(const CountType&) { ++numberOfCopyConstructorCalls; ++numberOfOperations; } unittest::CountType::~CountType() { ++numberOfDestructorCalls; if (numberOfDestructorCalls == (numberOfCopyConstructorCalls - numberOfDefaultConstructorCalls)) { ++numberOfReallocs; } ++numberOfOperations; } unittest::CountType& unittest::CountType::operator = (const CountType&) { ++numberOfAssignments; ++numberOfOperations; return *this; } void unittest::CountType::reset() { numberOfDefaultConstructorCalls = 0; numberOfCopyConstructorCalls = 0; numberOfAssignments = 0; numberOfDestructorCalls = 0; numberOfReallocs = 0; numberOfOperations = 0; }
jrahlf/3D-Non-Contact-Laser-Profilometer
xpcc/src/unittest/type/count_type.cpp
C++
mit
2,944
--- title: Telerik.Web.UI.GridEditFormItem page_title: Telerik.Web.UI.GridEditFormItem description: Telerik.Web.UI.GridEditFormItem --- # Telerik.Web.UI.GridEditFormItem Item that loads an EditForm during binding if P:Telerik.Web.UI.GridTableView.EditMode is F:Telerik.Web.UI.GridEditMode.EditForms . When in this mode RadGrid loads an EditFormItem for each normal data-bound item. EditForm is generated only for the items that are in P:Telerik.Web.UI.GridItem.Edit = true mode. ## Inheritance Hierarchy * System.Object * System.Web.UI.Control * System.Web.UI.WebControls.WebControl * System.Web.UI.WebControls.TableRow * Telerik.Web.UI.GridTableRow * Telerik.Web.UI.GridItem * Telerik.Web.UI.GridEditableItem * Telerik.Web.UI.GridEditFormItem ## Properties ### EditFormCell `TableCell` The table cell where the edit form will be instantiated, during data-binding. ### FormColumns `Control[]` FormColumns are only available when EditFormType is GridEditFormType.AutoGenerated. These are the container controls for each edit-form-column. You cna find the edit controls in these containers. You should not remove any controls from this containers. ### ParentItem `GridDataItem` The corresponding DataItem that the edit form is generated for. ### EditManager `GridEditManager` Allows you to access the column editors ### IsDataBound `Boolean` Gets a value indicating whether the grid item is bound to a data source. ### IsInEditMode `Boolean` Gets a value indicating whether the grid item is in edit mode at the moment. ### SavedOldValues `IDictionary` Gets the old value of the edited item ### CanExtractValues `Boolean` ### EditManager `GridEditManager` Allows you to access the column editors ### Item `TableCell` ### Item `TableCell` ### SavedOldValues `IDictionary` Gets the old value of the edited item ### CanExtractValues `Boolean` ### KeyValues `String` ### OwnerTableView `GridTableView` Gets a reference to the GridTableView that owns this GridItem. ### OwnerID `String` Gets the ClientID of the GridTableView that owns this instance. ### OwnerGridID `String` Gets the ClientID of the RadGrid instance that owns the item. #### Remarks This would be useful if several controls use the same eventhandler and you need to diferentiate the Grid instances in the handler. ### HasChildItems `Boolean` Gets a value indicating whether this item has child items - or items somehow related to this. ### CanExpand `Boolean` Gets a value indicating whether the item can be "expanded" to show its child items ### DataItem `Object` The original DataItem from the DataSource. See examples section below. ### DataSetIndex `Int32` Gets the index of the GridDataItem in the underlying DataTable/specified table from a DataSet. ### ItemIndex `Int32` Gets the index of the grid item among the collection. This index also can be used to get the DataKeyValues corresponding to this item from a GridTableView. ### ClientRowIndex `Int32` Gets the index of the row as in the html table object rendered on the client ### RowIndex `Int32` Gets the index of the item in the rows collection of the underlying Table server control ### ItemIndexHierarchical `Int32` Get the unique item index among all the item in the hierarchy. This index is used when setting item to selected, edited, etc ### ItemType `GridItemType` Gets the respective GridItemType of the grid item. ### Expanded `Boolean` Gets or sets a value indicating whether the grid item is expanded or collapsed. ### ConditionalExpanded `Boolean` Used in HierarchyLoadMode="Conditional" ### Display `Boolean` Sets whether the GridItem will be visible or with style="display:none;" ### Selected `Boolean` Gets or set a value indicating whether the grid item is selected ### SelectableMode `GridItemSelectableMode` Gets or sets a value determining if the chould be selected either on the client or on the server. ### Edit `Boolean` Sets the Item in edit mode. Requires Telerik RadGrid to rebind. #### Remarks If is set to InPlace, the grid column editors will be displayed inline of this item. If is set to EditForms, a new GridItem will be created, which will be child of this item (GridEditFormItem). The new item will hold the edit form. ### GroupIndex `String` Gets the index of the Item in the group. This works only when grouping. ### IsDataBound `Boolean` Gets a value indicating whether the grid item is bound to a data source. ### IsInEditMode `Boolean` Gets a value indicating whether the grid item is in edit mode at the moment. ### OriginalClientID `String` ### ClientID `String` Gets the server control identifier generated by ASP.NET. ## Methods ### PrepareItemStyle Override this method to change the default logic for rendering the item. Intended for internal usage. #### Returns `System.Void` ### Initialize This method is not intended to be used directly from your code #### Parameters #### columns `Telerik.Web.UI.GridColumn` #### Returns `System.Void` ### SetupItem #### Returns `System.Void` ### InitializeEditorInCell #### Returns `System.Void` ### ExtractValues Extracts values for each column, using #### Parameters #### newValues `System.Collections.IDictionary` This dictionary to fill, this parameter should not be null #### Returns `System.Void` ### InitializeEditorInCell #### Returns `System.Void` ### ExtractValues Extracts values for each column, using #### Parameters #### newValues `System.Collections.IDictionary` This dictionary to fill, this parameter should not be null #### Returns `System.Void` ### UpdateValues Extracts values for each column, using and updates values in provided object; #### Parameters #### objectToUpdate `System.Object` The object that should be updated #### Returns `System.Void` ### GetDataKeyValue Get the DataKeyValues from the owner GridTableView with the corresponding item ItemIndex and keyName. The keyName should be one of the specified in the array #### Parameters #### keyName `System.String` data key name #### Returns `System.Object` data key value ### FireCommandEvent Use this method to simulate item command event that bubbles to RadGrid and can be handeled automatically or in a custom manner, handling RadGrid.ItemCommand event. #### Parameters #### commandName `System.String` command to bubble, for example 'Page' #### commandArgument `System.Object` command argument, for example 'Next' #### Returns `System.Void` ### RestoreDecorator This method is not intended to be used directly from your code. #### Returns `System.Void` ### Initialize This method is not intended to be used directly from your code #### Returns `System.Void` ### SetupItem This method is not intended to be used directly from your code #### Returns `System.Void` ### PrepareItemStyle Override this method to change the default logic for rendering the item #### Returns `System.Void` ### PrepareItemVisibility Override this method to change the default logic for item visibility #### Returns `System.Void` ### SetTempIndexHierarchical Used after postback before ViewState becomes available - for example in ItemCreated and ItemDataBound events #### Parameters #### value `System.String` #### Returns `System.Void` ### RemoveChildSelectedItems #### Returns `System.Void` ### RemoveChildEditItems #### Returns `System.Void` ### SetChildrenVisible #### Returns `System.Void` ### SetVisibleChildren #### Returns `System.Void` ### ExpandHierarchyToTop #### Returns `System.Void` ### CalcColSpan Calculate column-span value for a cell using column list, when the cell indicated with FromCellIndex should be spanned to ToCellIndex #### Parameters #### columns `Telerik.Web.UI.GridColumn` columns - visible property is taken in count #### FromCellIndex `System.Int32` cell inbdex of spanned cell #### ToCellIndex `System.Int32` cell index of next not-spanned cell or -1 for the last cell index #### Returns `System.Int32` ColSpan number
scstauf/ajax-docs
api/server/Telerik.Web.UI/GridEditFormItem.md
Markdown
mit
8,435
--- title: "Quick-Start Guide" permalink: /docs/quick-start-guide/ excerpt: "How to quickly install and setup Minimal Mistakes for use with GitHub Pages." last_modified_at: 2017-11-15T09:49:52-05:00 redirect_from: - /theme-setup/ toc: true --- Minimal Mistakes has been developed as a [Jekyll theme gem](http://jekyllrb.com/docs/themes/) for easier use. It is also 100% compatible with GitHub Pages --- just with slightly different installation process. ## Installing the Theme If you're running Jekyll v3.5+ and self-hosting you can quickly install the theme as a Ruby gem. [^structure]: See [**Structure** page]({{ "/docs/structure/" | absolute_url }}) for a list of theme files and what they do. **ProTip:** Be sure to remove `/docs` and `/test` if you forked Minimal Mistakes. These folders contain documentation and test pages for the theme and you probably don't want them littering up your repo. {: .notice--info} ### Ruby Gem Method Add this line to your Jekyll site's `Gemfile`: ```ruby gem "minimal-mistakes-jekyll" ``` Add this line to your Jekyll site's `_config.yml` file: ```yaml theme: minimal-mistakes-jekyll ``` Then run Bundler to install the theme gem and dependencies: ```bash bundle install ``` ### GitHub Pages Compatible Methods If you're hosting with GitHub Pages follow these steps instead. **Note:** [jekyll-remote-theme](https://github.com/benbalter/jekyll-remote-theme) is currently in beta on GitHub Pages. In my tests it works as advertised, with the occasional failure due to missing `_includes` and `_layouts` --- your results may vary. {: .notice--warning} Replace `gem "jekyll"` with: ``` gem "github-pages", group: :jekyll_plugins gem "jekyll-remote-theme" ``` Run `bundle update` and verify that all gems install properly. Add `remote_theme: "mmistakes/minimal-mistakes"` to your `_config.yml` file. Then add [`jekyll-remote-theme`](https://github.com/benbalter/jekyll-remote-theme) to the `plugins` (previously gems) array in your `_config.yml` file like so: ``` plugins: - jekyll-remote-theme ``` --- **Note:** Your Jekyll site should be viewable immediately at <http://USERNAME.github.io>. If it's not, you can force a rebuild by **Customizing Your Site** (see below for more details). {: .notice--warning} If you're hosting several Jekyll based sites under the same GitHub username you will have to use Project Pages instead of User Pages. Essentially you rename the repo to something other than **USERNAME.github.io** and create a `gh-pages` branch off of `master`. For more details on how to set things up check [GitHub's documentation](https://help.github.com/articles/user-organization-and-project-pages/). <figure> <img src="{{ '/assets/images/mm-gh-pages.gif' | absolute_url }}" alt="creating a new branch on GitHub"> </figure> You can also install the theme by copying all of the theme files[^structure] into your project. To do so fork the [Minimal Mistakes theme](https://github.com/mmistakes/minimal-mistakes/fork), then rename the repo to **USERNAME.github.io** --- replacing **USERNAME** with your GitHub username. <figure> <img src="{{ '/assets/images/mm-theme-fork-repo.png' | absolute_url }}" alt="fork Minimal Mistakes"> </figure> **GitHub Pages Alternatives:** Looking to host your site for free and install/update the theme painlessly? [Netflify][netlify-jekyll], [GitLab Pages][gitlab-jekyll], and [Continuous Integration (CI) services][ci-jekyll] have you covered. In most cases all you need to do is connect your repository to them, create a simple configuration file, and install the theme following the [Ruby Gem Method](#ruby-gem-method) above. {: .notice--info} [netlify-jekyll]: https://www.netlify.com/blog/2015/10/28/a-step-by-step-guide-jekyll-3.0-on-netlify/ [gitlab-jekyll]: https://about.gitlab.com/2016/04/07/gitlab-pages-setup/ [ci-jekyll]: https://jekyllrb.com/docs/continuous-integration/ ### Remove the Unnecessary If you forked or downloaded the `minimal-mistakes-jekyll` repo you can safely remove the following folders and files: - `.editorconfig` - `.gitattributes` - `.github` - `/docs` - `/test` - `CHANGELOG.md` - `minimal-mistakes-jekyll.gemspec` - `README.md` - `screenshot-layouts.png` - `screenshot.png` ## Setup Your Site Depending on the path you took installing Minimal Mistakes you'll setup things a little differently. **ProTip:** The source code and content files for this site can be found in the [`/docs` folder](https://github.com/mmistakes/minimal-mistakes/tree/master/docs) if you want to copy or learn from them. {: .notice--info} ### Starting Fresh Starting with an empty folder and `Gemfile` you'll need to copy or re-create this [default `_config.yml`](https://github.com/mmistakes/minimal-mistakes/blob/master/_config.yml) file. For a full explanation of every setting be sure to read the [**Configuration**]({{ "/docs/configuration/" | absolute_url }}) section. From `v4.5.0` onwards, Minimal Mistakes theme-gem comes bundled with the necessary data files and will automatically use them via the [`jekyll-data`](https://github.com/ashmaroli/jekyll-data) plugin. So you no longer need to maintain a copy of these data files at your project directory. However like all other bundled files, you'll need to create and edit these data files to customize them. The bundled data files are: - [`_data/ui-text.yml`](https://github.com/mmistakes/minimal-mistakes/blob/master/_data/ui-text.yml) - UI text [documentation]({{ "/docs/ui-text/" | absolute_url }}) - [`_data/navigation.yml`](https://github.com/mmistakes/minimal-mistakes/blob/master/_data/navigation.yml) - navigation [documentation]({{ "/docs/navigation/" | absolute_url }}) ### Starting from `jekyll new` Scaffolding out a site with the `jekyll new` command requires you to modify a few files that it creates. Edit `_config.yml`. Then: - Replace `<site root>/index.md` with a modified [Minimal Mistakes `index.html`](https://github.com/mmistakes/minimal-mistakes/blob/master/index.html). Be sure to enable pagination if using the [`home` layout]({{ "/docs/layouts/#home-page" | absolute_url }}) by adding the necessary lines to **_config.yml**. - Change `layout: post` in `_posts/0000-00-00-welcome-to-jekyll.markdown` to `layout: single`. - Remove `about.md`, or at the very least change `layout: page` to `layout: single` and remove references to `icon-github.html` (or [copy to your `_includes`](https://github.com/jekyll/minima/tree/master/_includes) if using it). ### Migrating to Gem Version If you're migrating a site already using Minimal Mistakes and haven't customized any of the theme files things upgrading will be easier for you. Start by removing the following folders and any files within them: ```terminal ├── _includes ├── _layouts ├── _sass ├── assets | ├── css | ├── fonts | └── js ``` You won't need these anymore as they're bundled with the theme gem --- unless you intend to [override them](http://jekyllrb.com/docs/themes/#overriding-theme-defaults). **Note:** When clearing out the `assets` folder be sure to leave any files you've added and need. This includes images, CSS, or JavaScript that aren't already [bundled in the theme](https://github.com/mmistakes/minimal-mistakes/tree/master/assets). {: .notice--warning} From `v4.5.0` onwards, you don't have to maintain a copy of the default data files viz. `_data/ui-text.yml` and `_data/navigation.yml` either. The default files are read-in automatically via the [`jekyll-data`](https://github.com/ashmaroli/jekyll-data) plugin. If you customized any of these files leave them alone, and only remove the untouched ones. If done correctly your modified versions should [override](http://jekyllrb.com/docs/themes/#overriding-theme-defaults) the versions bundled with the theme and be used by Jekyll instead. #### Update Gemfile Replace `gem "github-pages` or `gem "jekyll"` with `gem "jekyll", "~> 3.5"`. You'll need the latest version of Jekyll[^update-jekyll] for Minimal Mistakes to work and load all of the theme's assets properly, this line forces Bundler to do that. [^update-jekyll]: You could also run `bundle update jekyll` to update Jekyll. Add the Minimal Mistakes theme gem: ```ruby gem "minimal-mistakes-jekyll" ``` When finished your `Gemfile` should look something like this: ```ruby source "https://rubygems.org" gem "jekyll", "~> 3.5" gem "minimal-mistakes-jekyll" ``` Then run `bundle update` and add `theme: minimal-mistakes-jekyll` to your `_config.yml`. **v4 Breaking Change:** Paths for image headers, overlays, teasers, [galleries]({{ "/docs/helpers/#gallery" | absolute_url }}), and [feature rows]({{ "/docs/helpers/#feature-row" | absolute_url }}) have changed and now require a full path. Instead of just `image: filename.jpg` you'll need to use the full path eg: `image: /assets/images/filename.jpg`. The preferred location is now `/assets/images/` but can be placed elsewhere or externally hosted. This applies to image references in `_config.yml` and `author.yml` as well. {: .notice--danger} --- That's it! If all goes well running `bundle exec jekyll serve` should spin-up your site.
dwinter/minimal-mistakes
docs/_docs/01-quick-start-guide.md
Markdown
mit
9,168
require 'ebay/types/pagination_result' require 'ebay/types/category' module Ebay # :nodoc: module Responses # :nodoc: # == Attributes # object_node :pagination_result, 'PaginationResult', :class => PaginationResult, :optional => true # array_node :categories, 'CategoryArray', 'Category', :class => Category, :default_value => [] # boolean_node :has_more, 'HasMore', 'true', 'false', :optional => true class GetPopularKeywords < Abstract include XML::Mapping include Initializer root_element_name 'GetPopularKeywordsResponse' object_node :pagination_result, 'PaginationResult', :class => PaginationResult, :optional => true array_node :categories, 'CategoryArray', 'Category', :class => Category, :default_value => [] boolean_node :has_more, 'HasMore', 'true', 'false', :optional => true end end end
skiz/ebayapi
lib/ebay/responses/get_popular_keywords.rb
Ruby
mit
870
// Boost Lambda Library -- control_constructs_common.hpp ------------------- // Copyright (C) 1999, 2000 Jaakko Järvi (jaakko.jarvi@cs.utu.fi) // Copyright (C) 2000 Gary Powell (powellg@amazon.com) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see www.boost.org // -------------------------------------------------------------------------- #if !defined(BOOST_CONTROL_CONSTRUCTS_COMMON_HPP) #define BOOST_CONTROL_CONSTRUCTS_COMMON_HPP namespace boost { namespace lambda { // special types of lambda functors, used with control structures // to guarantee that they are composed correctly. template<class Tag, class LambdaFunctor> class tagged_lambda_functor; template<class Tag, class Args> class tagged_lambda_functor<Tag, lambda_functor<Args> > : public lambda_functor<Args> { public: tagged_lambda_functor(const Args& a) : lambda_functor<Args>(a) {} tagged_lambda_functor(const lambda_functor<Args>& a) : lambda_functor<Args>(a) {} // for the no body cases in control structures. tagged_lambda_functor() : lambda_functor<Args>() {} }; } // lambda } // boost #endif // BOOST_CONTROL_CONSTRUCTS_COMMON_HPP
Ezeer/VegaStrike_win32FR
vegastrike/boost/1_35/boost/lambda/detail/control_constructs_common.hpp
C++
mit
1,286
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .agilent90000 import * class agilentDSA91204A(agilent90000): "Agilent Infiniium DSA91204A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO91204A') super(agilentDSA91204A, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._digital_channel_count = 0 self._channel_count = 4 self._bandwidth = 12e9 self._init_channels()
elopezga/ErrorRate
ivi/agilent/agilentDSA91204A.py
Python
mit
1,632
module.exports = { VERSION: '%KARMA_VERSION%', KARMA_URL_ROOT: '%KARMA_URL_ROOT%', KARMA_PROXY_PATH: '%KARMA_PROXY_PATH%', CONTEXT_URL: 'context.html' }
pedrotcaraujo/karma
client/constants.js
JavaScript
mit
161
''' FFmpeg video abstraction ======================== .. versionadded:: 1.0.8 This abstraction requires ffmpeg python extensions. We have made a special extension that is used for the android platform but can also be used on x86 platforms. The project is available at:: http://github.com/tito/ffmpeg-android The extension is designed for implementing a video player. Refer to the documentation of the ffmpeg-android project for more information about the requirements. ''' try: import ffmpeg except: raise from kivy.core.video import VideoBase from kivy.graphics.texture import Texture class VideoFFMpeg(VideoBase): def __init__(self, **kwargs): self._do_load = False self._player = None super(VideoFFMpeg, self).__init__(**kwargs) def unload(self): if self._player: self._player.stop() self._player = None self._state = '' self._do_load = False def load(self): self.unload() def play(self): if self._player: self.unload() self._player = ffmpeg.FFVideo(self._filename) self._player.set_volume(self._volume) self._do_load = True def stop(self): self.unload() def seek(self, percent, precise=True): if self._player is None: return self._player.seek(percent) def _do_eos(self): self.unload() self.dispatch('on_eos') super(VideoFFMpeg, self)._do_eos() def _update(self, dt): if self._do_load: self._player.open() self._do_load = False return player = self._player if player is None: return if not player.is_open: self._do_eos() return frame = player.get_next_frame() if frame is None: return # first time we got a frame, we know that video is readed now. if self._texture is None: self._texture = Texture.create(size=( player.get_width(), player.get_height()), colorfmt='rgb') self._texture.flip_vertical() self.dispatch('on_load') if self._texture: self._texture.blit_buffer(frame) self.dispatch('on_frame') def _get_duration(self): if self._player is None: return 0 return self._player.get_duration() def _get_position(self): if self._player is None: return 0 return self._player.get_position() def _set_volume(self, value): self._volume = value if self._player: self._player.set_volume(self._volume)
Cheaterman/kivy
kivy/core/video/video_ffmpeg.py
Python
mit
2,694
# stm32f4xx RT-Thread Demo --- ## 1¡¢¼ò½é ͨ¹ý `app\src\app_task.c` µÄ `test_env()` ·½·¨À´ÑÝʾ»·¾³±äÁ¿µÄ¶ÁÈ¡¼°Ð޸ŦÄÜ£¬Ã¿´ÎϵͳÆô¶¯²¢ÇÒ³õʼ»¯EasyFlash³É¹¦ºó»áµ÷Óø÷½·¨¡£ ÔÚ `test_env()` ·½·¨ÖУ¬»áÏȶÁȡϵͳµÄÆô¶¯´ÎÊý£¬¶ÁÈ¡ºó¶ÔÆô¶¯´ÎÊý¼ÓÒ»£¬ÔÙ´æÈëµ½»·¾³±äÁ¿ÖУ¬ÊµÏּǼϵͳÆô¶¯£¨¿ª»ú£©´ÎÊýµÄ¹¦ÄÜ¡£ ### 1.1¡¢Ê¹Ó÷½·¨ - 1¡¢´ò¿ªµçÄÔµÄÖÕ¶ËÓëDemoµÄ´®¿Ú1½øÐÐÁ¬½Ó£¬´®¿ÚÅäÖà 115200 8 1 N£¬´ËʱÔÚÖÕ¶ËÖоͿÉÒÔÊäÈë¡¶EasyFlash ʹÓÃ˵Ã÷¡·ÖÐÌáµ½µÄ³£ÓÃÃüÁĿǰֻÓл·¾³±äÁ¿²Ù×÷ÃüÁ - 2¡¢ÔÚÖÕ¶ËÊäÈë `printenv` ²é¿´µ±Ç°µÄϵͳÆô¶¯´ÎÊý£¬¼´ `boot_times` µÄvalue - 3¡¢ÊäÈë `reboot` ÃüÁ»òÕßÖ±½ÓÖØÆôDemoƽ̨ - 4¡¢µÈ´ýÏµÍ³ÖØÆôÍê³Éºó£¬ÔÙ´ÎÊäÈë `printenv` £¬¼´¿É²é¿´µ½Æô¶¯´ÎÊýÓÐËùÔö¼Ó > ×¢Ò⣺¶ÔÓÚÎÞ·¨Á¬½ÓÖն˵ÄÓû§£¬Ò²¿ÉÒÔʹÓ÷ÂÕæÆ÷ÓëDemoƽ̨½øÐÐÁ¬½Ó£¬À´¹Û²ìÆô¶¯´ÎÊýµÄ±ä»¯ ## 2¡¢Îļþ£¨¼Ð£©ËµÃ÷ `components\flash\port\flash_port.c` ÒÆÖ²²Î¿¼Îļþ `RVMDK` ÏÂΪKeil¹¤³ÌÎļþ£¨ºóÆÚ¼ÓÈ룬±ÊÕßĿǰµÄKeil°æ±¾ÊÇ4.12£¬²»Ö§³Östm32f4xx£© `EWARM` ÏÂΪIAR¹¤³ÌÎļþ
weitengchu/EasyFlash
demo/env/stm32f4xx/README.md
Markdown
mit
940
--- title: Binding to Table-Based DataSource page_title: Binding to Table-Based DataSource | RadMenu for ASP.NET AJAX Documentation description: Binding to Table-Based DataSource slug: menu/data-binding/binding-to-table-based-datasource tags: binding,to,table-based,datasource published: True position: 3 --- # Binding to Table-Based DataSource ## Table-based **DataSource** components, such as **SqlDataSource** and **AccessDataSource** can be used to bind the menu declaratively at design time. As with [binding to a DataSet, DataTable, or DataView]({%slug menu/data-binding/binding-to-datatable%}), you can use the *ID-ParentID* relation to establish a hierarchy among the menu items. >note The [Binding to a Data Source]({%slug menu/getting-started/binding-to-a-data-source%}) tutorial gives step-by-step instructions for binding **RadMenu** to an **AccessDataSource**. > To bind to a table-based DataSource component: 1. Drag the **DataSource** component from the toolbox onto the same page as your **RadMenu** component. 1. Configure the **DataSource** component to connect to the data. 1. Set the **DataSourceID** property of your **RadMenu** to the **ID** of the **DataSource** component you added in step 1. 1. Set the **DataTextField**, **DataValueField**, and **DataNavigateUrlField** properties to indicate the columns of the database table that supply values for the **Text**, **Value**, and **NavigateUrl** properties of menu items. 1. Establish the menu hierarchy by setting the **DataFieldID** property to the key field for records, and the **DataFieldParentID** property to the field that gives the key field value of the parent item. >caution The **ParentID** of the root items must be **null** ( **nothing** ). If for some reason the data source comes without null values for the ParentID column, use a query that returns the expected value (null). For example: >SELECT ID, Text, IF(ParentID = 0, NULL, ParentID) FROM tblDat > 1. Bind any additional properties of the menu items using the **[ItemDataBound event]({%slug menu/server-side-programming/itemdatabound%})**: ````C# protected void RadMenu1_ItemDataBound(object sender, Telerik.Web.UI.RadMenuEventArgs e) { e.Item.ToolTip = (string)DataBinder.Eval(e.Item.DataItem, "ToolTip"); } ```` ````VB.NET Protected Sub RadMenu1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadMenuEventArgs) Handles RadMenu1.ItemDataBound e.Item.ToolTip = CStr(DataBinder.Eval(e.Item.DataItem, "ToolTip")) End Sub ```` The resulting declaration looks something like the following: ````ASP.NET <telerik:RadMenu runat="server" ID="RadMenu1" DataSourceID="SqlDataSource1" DataFieldID="id" DataFieldParentID="parentID" DataTextField="Targetname" DataNavigatUrlField="target" OnItemDataBound="RadMenu1_ItemDataBound"> </telerik:RadMenu> <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="Persist Security Info=False;Integrated Security=true;Initial Catalog=MyDB;server=(local)" ProviderName="System.Data.SqlClient" SelectCommand="SELECT id, Targetname, target, tooltip, parentId from MenuTable" /> ```` # See Also * [Overview]({%slug menu/data-binding/overview%}) * [Using DataBindings]({%slug menu/data-binding/using-databindings%}) * [Binding to Hierarchical DataSource]({%slug menu/data-binding/binding-to-hierarchical-datasource%}) * [Binding to Object-Based Data Sources]({%slug menu/data-binding/binding-to-object-based-data-sources%})
scstauf/ajax-docs
controls/menu/data-binding/binding-to-table-based-datasource.md
Markdown
mit
3,536
<?php /** * This file is part of PHP_Depend. * * PHP Version 5 * * Copyright (c) 2008-2012, Manuel Pichler <mapi@pdepend.org>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Manuel Pichler nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category PHP * @package PHP_Depend * @subpackage Parser * @author Manuel Pichler <mapi@pdepend.org> * @copyright 2008-2012 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id$ * @link http://www.pdepend.org/ */ /** * This type of exception is thrown when the parser reaches the end of the token * stream, but expects further tokens. * * @category PHP * @package PHP_Depend * @subpackage Parser * @author Manuel Pichler <mapi@pdepend.org> * @copyright 2008-2012 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: @package_version@ * @link http://www.pdepend.org/ */ class PHP_Depend_Parser_TokenStreamEndException extends PHP_Depend_Parser_TokenException { /** * Constructs a new end of token stream exception. * * @param PHP_Depend_TokenizerI $tokenizer The context tokenizer instance. */ public function __construct(PHP_Depend_TokenizerI $tokenizer) { parent::__construct( sprintf( 'Unexpected end of token stream in file: %s.', $tokenizer->getSourceFile() ) ); } }
drBenway/siteResearch
vendor/pdepend/pdepend/src/main/php/PHP/Depend/Parser/TokenStreamEndException_1.php
PHP
mit
3,000
var AreasOfEffect = (() => { 'use strict'; let MENU_CMD = '!areasOfEffectShowMenu'; let ADD_EFFECT_CMD = '!areasOfEffectAddEffect'; let APPLY_EFFECT_CMD = '!areasOfEffectApplyEffet'; let DEL_EFFECT_CMD = '!areasOfEffectDeleteEffect'; let SHOW_EFFECTS_CMD = '!areasOfEffectShowEffects'; let VERSION = '1.0'; let MENU_CSS = { 'effectsTable': { 'width': '100%' }, 'effectThumbnail': { 'height': '50px', 'width': '50px' }, 'menu': { 'background': '#fff', 'border': 'solid 1px #000', 'border-radius': '5px', 'font-weight': 'bold', 'margin-bottom': '1em', 'overflow': 'hidden' }, 'menuBody': { 'padding': '5px', 'text-align': 'center' }, 'menuHeader': { 'background': '#000', 'color': '#fff', 'text-align': 'center' } }; /** * A saved area of effect graphic. * @typedef {object} AreaOfEffect * @property {string} name * @property {number} rotateOffset * The offset of the rotation facing for the effect's graphic * from 0, going clockwise in radians. * @property {Mat3} ptTransform * The offset of the effect's graphic from its origin. * @property {number} scale * The scale of the image's width compared to the length of the segments drawn for it. * @property {string} imgsrc * The URL of the effect's image. */ /** * Applies an effect to a path. * @param {string} who * @param {string} playerid * @param {string} name * @param {Path} path */ function applyEffect(who, playerid, name, path) { let effect = state.AreasOfEffect.saved[name]; let segment = PathMath.toSegments(path)[0]; let u = VecMath.sub(segment[1], segment[0]); let radians = Math.atan2(u[1], u[0]); let rotation = (radians + effect.rotateOffset)/Math.PI*180; let width = VecMath.length(u)*effect.scale; let m = MatrixMath.rotate(radians); m = MatrixMath.multiply(m, MatrixMath.scale(VecMath.length(u))); m = MatrixMath.multiply(m, effect.ptTransform); let v = MatrixMath.multiply(m, [0, 0, 1]); let pt = VecMath.add(segment[0], v); let graphic = createObj('graphic', { name: effect.name, _pageid: path.get('_pageid'), layer: 'objects', left: pt[0], top: pt[1], rotation: rotation, width: width, height: width/effect.aspectRatio, imgsrc: _getCleanImgsrc(effect.imgsrc), controlledby: playerid }); toBack(graphic); path.remove(); } /** * Deletes a saved area of effect. * @param {string} who * @param {string} playerid * @param {string} name */ function deleteEffect(who, playerid, name) { delete state.AreasOfEffect.saved[name]; _showEffectsListMenu(who, playerid); } /** * Fixes msg.who. * @param {string} who * @return {string} */ function _fixWho(who) { return who.replace(/\(GM\)/, '').trim(); } /** * Cookbook.getCleanImgsrc * https://wiki.roll20.net/API:Cookbook#getCleanImgsrc */ function _getCleanImgsrc(imgsrc) { var parts = imgsrc.match(/(.*\/images\/.*)(thumb|med|original|max)(.*)$/); if(parts) return parts[1]+'thumb'+parts[3]; throw new Error('Only images that you have uploaded to your library ' + 'can be used as custom status markers. ' + 'See https://wiki.roll20.net/API:Objects#imgsrc_and_avatar_property_restrictions for more information.'); } /** * Initializes the state of this script. */ function _initState() { _.defaults(state, { AreasOfEffect: {} }); _.defaults(state.AreasOfEffect, { saved: {} }); } /** * Checks if the chat message starts with some API command. * @private * @param {Msg} msg The chat message for the API command. * @param {String} cmdName * @return {Boolean} */ function _msgStartsWith(msg, cmdName) { var msgTxt = msg.content; return (msg.type == 'api' && msgTxt.indexOf(cmdName) !== -1); } /** * Saves an area of effect. * @param {string} who * @param {string} playerid * @param {string} name * @param {Graphic} effect * @param {Path} path */ function saveEffect(who, playerid, name, effect, path) { let segment = PathMath.toSegments(path)[0]; let u = VecMath.sub(segment[1], segment[0]); let pt = [ effect.get('left'), effect.get('top') ]; let scale = effect.get('width')/VecMath.length(u); let radians = -Math.atan2(u[1], u[0]); let v = VecMath.sub(pt, segment[0]); let vHat = VecMath.normalize(v); let m = MatrixMath.identity(3); m = MatrixMath.multiply(m, MatrixMath.scale(VecMath.length(v)/ VecMath.length(u))); m = MatrixMath.multiply(m, MatrixMath.rotate(radians)); m = MatrixMath.multiply(m, MatrixMath.translate(vHat)); // Save the effect. state.AreasOfEffect.saved[name] = { name: name, ptTransform: m, rotateOffset: effect.get('rotation')/180*Math.PI + radians, scale: scale, aspectRatio: effect.get('width')/effect.get('height'), imgsrc: _getCleanImgsrc(effect.get('imgsrc')) }; // Delete the effect graphic and path. effect.remove(); path.remove(); _whisper(who, 'Created Area of Effect: ' + name); _showMainMenu(who, playerid); } /** * Shows the list of effects which can be applied to a selected path. * @param {string} who * @param {string} playerid */ function _showEffectsListMenu(who, playerid) { let content = new HtmlBuilder('div'); let effects = _.values(state.AreasOfEffect.saved).sort(function(a,b) { if(a.name < b.name) return -1; else if(a.name > b.name) return 1; else return 0; }); let table = content.append('table.effectsTable'); _.each(effects, effect => { let row = table.append('tr'); row.append('td.effectThumbnail', new HtmlBuilder('img', '', { src: effect.imgsrc })); row.append('td', '[' + effect.name + '](' + APPLY_EFFECT_CMD + ' ' + effect.name + ')'); // The GM is allowed to delete effects. if(playerIsGM(playerid)) row.append('td', '[❌](' + DEL_EFFECT_CMD + ' ' + effect.name + ' ?{Delete effect: Are you sure?|yes|no})'); }); content.append('div', '[Back](' + MENU_CMD + ')'); let menu = _showMenuPanel('Choose effect', content); _whisper(who, menu.toString(MENU_CSS)); } /** * Shows the main menu for script. * @param {string} who * @param {string} playerid */ function _showMainMenu(who, playerId) { let content = new HtmlBuilder('div'); content.append('div', '[Apply an effect](' + SHOW_EFFECTS_CMD + ')'); if(playerIsGM(playerId)) content.append('div', '[Save effect](' + ADD_EFFECT_CMD + ' ?{Save Area of Effect: name})'); let menu = _showMenuPanel('Main Menu', content); _whisper(who, menu.toString(MENU_CSS)); } /** * Displays one of the script's menus. * @param {string} header * @param {(string|HtmlBuilder)} content * @return {HtmlBuilder} */ function _showMenuPanel(header, content) { let menu = new HtmlBuilder('.menu'); menu.append('.menuHeader', header); menu.append('.menuBody', content) return menu; } /** * @private * Whispers a Marching Order message to someone. */ function _whisper(who, msg) { sendChat('Areas Of Effect', '/w "' + _fixWho(who) + '" ' + msg); } /** * Check that the menu macro for this script is installed. */ on('ready', () => { let menuMacro = findObjs({ _type: 'macro', name: 'AreasOfEffectMenu' })[0]; if(!menuMacro) { let players = findObjs({ _type: 'player' }); let gms = _.filter(players, player => { return playerIsGM(player.get('_id')); }); _.each(gms, gm => { createObj('macro', { _playerid: gm.get('_id'), name: 'AreasOfEffectMenu', action: MENU_CMD, visibleto: 'all' }); }) } _initState(); log('--- Initialized Areas Of Effect v' + VERSION + ' ---'); }); /** * Set up our chat command handler. */ on("chat:message", function(msg) { try { if(_msgStartsWith(msg, ADD_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv.slice(1).join('_'); let graphic, path; _.each(msg.selected, item => { if(item._type === 'graphic') graphic = getObj('graphic', item._id); if(item._type === 'path') path = getObj('path', item._id); }); if(graphic && path) { saveEffect(msg.who, msg.playerid, name, graphic, path); } else { _whisper(msg.who, 'ERROR: You must select a graphic and a path to save an effect.'); } } else if(_msgStartsWith(msg, APPLY_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv.slice(1).join('_'); let path; _.each(msg.selected, item => { if(item._type === 'path') path = getObj('path', item._id); }); if(path) applyEffect(msg.who, msg.playerid, name, path); else _whisper(msg.who, 'ERROR: You must select a path to apply the effect to.'); } else if(_msgStartsWith(msg, DEL_EFFECT_CMD)) { let argv = msg.content.split(' '); let name = argv[1]; let confirm = argv[2]; if(confirm === 'yes') deleteEffect(msg.who, msg.playerid, name); } else if(_msgStartsWith(msg, SHOW_EFFECTS_CMD)) { _showEffectsListMenu(msg.who, msg.playerid) } else if(_msgStartsWith(msg, MENU_CMD)) { _showMainMenu(msg.who, msg.playerid); } } catch(err) { log('Areas Of Effect ERROR: ' + err.message); sendChat('Areas Of Effect ERROR:', '/w ' + _fixWho(msg.who) + ' ' + err.message); log(err.stack); } }); })();
shdwjk/roll20-api-scripts
AreasOfEffect/1.0/aoe.js
JavaScript
mit
10,124
/** @file ***************************************************************************** Declaration of interfaces for a gadget that can be created from an R1CS constraint system. ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef GADGET_FROM_R1CS_HPP_ #define GADGET_FROM_R1CS_HPP_ #include <map> #include "gadgetlib1/gadget.hpp" namespace libsnark { template<typename FieldT> class gadget_from_r1cs : public gadget<FieldT> { private: const std::vector<pb_variable_array<FieldT> > vars; const r1cs_constraint_system<FieldT> cs; std::map<size_t, size_t> cs_to_vars; public: gadget_from_r1cs(protoboard<FieldT> &pb, const std::vector<pb_variable_array<FieldT> > &vars, const r1cs_constraint_system<FieldT> &cs, const std::string &annotation_prefix); void generate_r1cs_constraints(); void generate_r1cs_witness(const r1cs_primary_input<FieldT> &primary_input, const r1cs_auxiliary_input<FieldT> &auxiliary_input); }; } // libsnark #include "gadgetlib1/gadgets/gadget_from_r1cs.tcc" #endif // GADGET_FROM_R1CS_HPP_
litecoinz-project/litecoinz
src/snark/libsnark/gadgetlib1/gadgets/gadget_from_r1cs.hpp
C++
mit
1,424
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2013-2014 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_BSTREE_HPP #define BOOST_INTRUSIVE_BSTREE_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/detail/assert.hpp> #include <boost/static_assert.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/bs_set_hook.hpp> #include <boost/intrusive/detail/tree_node.hpp> #include <boost/intrusive/detail/tree_iterator.hpp> #include <boost/intrusive/detail/ebo_functor_holder.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <boost/intrusive/pointer_traits.hpp> #include <boost/intrusive/detail/is_stateful_value_traits.hpp> #include <boost/intrusive/detail/empty_node_checker.hpp> #include <boost/intrusive/detail/default_header_holder.hpp> #include <boost/intrusive/detail/reverse_iterator.hpp> #include <boost/intrusive/detail/exception_disposer.hpp> #include <boost/intrusive/detail/node_cloner_disposer.hpp> #include <boost/intrusive/detail/key_nodeptr_comp.hpp> #include <boost/intrusive/detail/simple_disposers.hpp> #include <boost/intrusive/detail/size_holder.hpp> #include <boost/intrusive/detail/algo_type.hpp> #include <boost/intrusive/detail/algorithm.hpp> #include <boost/intrusive/detail/tree_value_compare.hpp> #include <boost/intrusive/detail/get_value_traits.hpp> #include <boost/intrusive/bstree_algorithms.hpp> #include <boost/intrusive/link_mode.hpp> #include <boost/intrusive/parent_from_member.hpp> #include <boost/move/utility_core.hpp> #include <boost/move/adl_move_swap.hpp> #include <boost/intrusive/detail/minimal_pair_header.hpp> #include <cstddef> //size_t... #include <boost/intrusive/detail/minimal_less_equal_header.hpp>//less, equal_to #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif namespace boost { namespace intrusive { /// @cond struct default_bstree_hook_applier { template <class T> struct apply{ typedef typename T::default_bstree_hook type; }; }; template<> struct is_default_hook_tag<default_bstree_hook_applier> { static const bool value = true; }; struct bstree_defaults { typedef default_bstree_hook_applier proto_value_traits; static const bool constant_time_size = true; typedef std::size_t size_type; typedef void compare; typedef void key_of_value; static const bool floating_point = true; //For sgtree typedef void priority; //For treap typedef void header_holder_type; }; template<class ValueTraits, algo_types AlgoType, typename HeaderHolder> struct bstbase3 { typedef ValueTraits value_traits; typedef typename value_traits::node_traits node_traits; typedef typename node_traits::node node_type; typedef typename get_algo<AlgoType, node_traits>::type node_algorithms; typedef typename node_traits::node_ptr node_ptr; typedef typename node_traits::const_node_ptr const_node_ptr; typedef tree_iterator<value_traits, false> iterator; typedef tree_iterator<value_traits, true> const_iterator; typedef boost::intrusive::reverse_iterator<iterator> reverse_iterator; typedef boost::intrusive::reverse_iterator<const_iterator> const_reverse_iterator; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::pointer) pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::const_pointer) const_pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<pointer>::element_type) value_type; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<pointer>::reference) reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::reference) const_reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::difference_type) difference_type; typedef typename detail::get_header_holder_type < value_traits,HeaderHolder >::type header_holder_type; static const bool safemode_or_autounlink = is_safe_autounlink<value_traits::link_mode>::value; static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value; static const bool has_container_from_iterator = detail::is_same< header_holder_type, detail::default_header_holder< node_traits > >::value; struct holder_t : public ValueTraits { BOOST_INTRUSIVE_FORCEINLINE explicit holder_t(const ValueTraits &vtraits) : ValueTraits(vtraits) {} header_holder_type root; } holder; static bstbase3 &get_tree_base_from_end_iterator(const const_iterator &end_iterator) { BOOST_STATIC_ASSERT(has_container_from_iterator); node_ptr p = end_iterator.pointed_node(); header_holder_type* h = header_holder_type::get_holder(p); holder_t *holder = get_parent_from_member<holder_t, header_holder_type>(h, &holder_t::root); bstbase3 *base = get_parent_from_member<bstbase3, holder_t> (holder, &bstbase3::holder); return *base; } BOOST_INTRUSIVE_FORCEINLINE bstbase3(const ValueTraits &vtraits) : holder(vtraits) { node_algorithms::init_header(this->header_ptr()); } BOOST_INTRUSIVE_FORCEINLINE node_ptr header_ptr() { return holder.root.get_node(); } BOOST_INTRUSIVE_FORCEINLINE const_node_ptr header_ptr() const { return holder.root.get_node(); } BOOST_INTRUSIVE_FORCEINLINE const value_traits &get_value_traits() const { return this->holder; } BOOST_INTRUSIVE_FORCEINLINE value_traits &get_value_traits() { return this->holder; } typedef typename boost::intrusive::value_traits_pointers <ValueTraits>::const_value_traits_ptr const_value_traits_ptr; BOOST_INTRUSIVE_FORCEINLINE const_value_traits_ptr priv_value_traits_ptr() const { return pointer_traits<const_value_traits_ptr>::pointer_to(this->get_value_traits()); } BOOST_INTRUSIVE_FORCEINLINE iterator begin() BOOST_NOEXCEPT { return iterator(node_algorithms::begin_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator begin() const BOOST_NOEXCEPT { return cbegin(); } BOOST_INTRUSIVE_FORCEINLINE const_iterator cbegin() const BOOST_NOEXCEPT { return const_iterator(node_algorithms::begin_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE iterator end() BOOST_NOEXCEPT { return iterator(node_algorithms::end_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator end() const BOOST_NOEXCEPT { return cend(); } BOOST_INTRUSIVE_FORCEINLINE const_iterator cend() const BOOST_NOEXCEPT { return const_iterator(node_algorithms::end_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE iterator root() { return iterator(node_algorithms::root_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator root() const { return croot(); } BOOST_INTRUSIVE_FORCEINLINE const_iterator croot() const { return const_iterator(node_algorithms::root_node(this->header_ptr()), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE reverse_iterator rbegin() { return reverse_iterator(end()); } BOOST_INTRUSIVE_FORCEINLINE const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } BOOST_INTRUSIVE_FORCEINLINE const_reverse_iterator crbegin() const { return const_reverse_iterator(end()); } BOOST_INTRUSIVE_FORCEINLINE reverse_iterator rend() { return reverse_iterator(begin()); } BOOST_INTRUSIVE_FORCEINLINE const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } BOOST_INTRUSIVE_FORCEINLINE const_reverse_iterator crend() const { return const_reverse_iterator(begin()); } void replace_node(iterator replace_this, reference with_this) { node_algorithms::replace_node( get_value_traits().to_node_ptr(*replace_this) , this->header_ptr() , get_value_traits().to_node_ptr(with_this)); BOOST_IF_CONSTEXPR(safemode_or_autounlink) node_algorithms::init(replace_this.pointed_node()); } BOOST_INTRUSIVE_FORCEINLINE void rebalance() BOOST_NOEXCEPT { node_algorithms::rebalance(this->header_ptr()); } iterator rebalance_subtree(iterator root) BOOST_NOEXCEPT { return iterator(node_algorithms::rebalance_subtree(root.pointed_node()), this->priv_value_traits_ptr()); } static iterator s_iterator_to(reference value) BOOST_NOEXCEPT { BOOST_STATIC_ASSERT((!stateful_value_traits)); return iterator (value_traits::to_node_ptr(value), const_value_traits_ptr()); } static const_iterator s_iterator_to(const_reference value) BOOST_NOEXCEPT { BOOST_STATIC_ASSERT((!stateful_value_traits)); return const_iterator (value_traits::to_node_ptr(*pointer_traits<pointer>::const_cast_from(pointer_traits<const_pointer>::pointer_to(value))), const_value_traits_ptr()); } iterator iterator_to(reference value) BOOST_NOEXCEPT { return iterator (this->get_value_traits().to_node_ptr(value), this->priv_value_traits_ptr()); } const_iterator iterator_to(const_reference value) const BOOST_NOEXCEPT { return const_iterator (this->get_value_traits().to_node_ptr(*pointer_traits<pointer>::const_cast_from(pointer_traits<const_pointer>::pointer_to(value))), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE static void init_node(reference value) { node_algorithms::init(value_traits::to_node_ptr(value)); } }; template<class Less, class T> struct get_compare { typedef Less type; }; template<class T> struct get_compare<void, T> { typedef ::std::less<T> type; }; template<class KeyOfValue, class T> struct get_key_of_value { typedef KeyOfValue type; }; template<class T> struct get_key_of_value<void, T> { typedef ::boost::intrusive::detail::identity<T> type; }; template<class ValuePtr, class VoidOrKeyOfValue, class VoidOrKeyComp> struct bst_key_types { typedef typename boost::movelib::pointer_element<ValuePtr>::type value_type; typedef typename get_key_of_value < VoidOrKeyOfValue, value_type>::type key_of_value; typedef typename key_of_value::type key_type; typedef typename get_compare< VoidOrKeyComp , key_type >::type key_compare; typedef tree_value_compare <ValuePtr, key_compare, key_of_value> value_compare; }; template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, algo_types AlgoType, typename HeaderHolder> struct bstbase2 //Put the (possibly empty) functor in the first position to get EBO in MSVC //Use public inheritance to avoid MSVC bugs with closures : public detail::ebo_functor_holder < typename bst_key_types < typename ValueTraits::pointer , VoidOrKeyOfValue , VoidOrKeyComp >::value_compare > , public bstbase3<ValueTraits, AlgoType, HeaderHolder> { typedef bstbase3<ValueTraits, AlgoType, HeaderHolder> treeheader_t; typedef bst_key_types< typename ValueTraits::pointer , VoidOrKeyOfValue , VoidOrKeyComp> key_types; typedef typename treeheader_t::value_traits value_traits; typedef typename treeheader_t::node_algorithms node_algorithms; typedef typename ValueTraits::value_type value_type; typedef typename key_types::key_type key_type; typedef typename key_types::key_of_value key_of_value; typedef typename key_types::key_compare key_compare; typedef typename key_types::value_compare value_compare; typedef typename treeheader_t::iterator iterator; typedef typename treeheader_t::const_iterator const_iterator; typedef typename treeheader_t::node_ptr node_ptr; typedef typename treeheader_t::const_node_ptr const_node_ptr; bstbase2(const key_compare &comp, const ValueTraits &vtraits) : detail::ebo_functor_holder<value_compare>(value_compare(comp)), treeheader_t(vtraits) {} const value_compare &comp() const { return this->get(); } value_compare &comp() { return this->get(); } typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::pointer) pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::const_pointer) const_pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<pointer>::reference) reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::reference) const_reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::difference_type) difference_type; typedef typename node_algorithms::insert_commit_data insert_commit_data; BOOST_INTRUSIVE_FORCEINLINE value_compare value_comp() const { return this->comp(); } BOOST_INTRUSIVE_FORCEINLINE key_compare key_comp() const { return this->comp().key_comp(); } //lower_bound BOOST_INTRUSIVE_FORCEINLINE iterator lower_bound(const key_type &key) { return this->lower_bound(key, this->key_comp()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator lower_bound(const key_type &key) const { return this->lower_bound(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType &key, KeyTypeKeyCompare comp) { return iterator(node_algorithms::lower_bound (this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType &key, KeyTypeKeyCompare comp) const { return const_iterator(node_algorithms::lower_bound (this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } //upper_bound BOOST_INTRUSIVE_FORCEINLINE iterator upper_bound(const key_type &key) { return this->upper_bound(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType &key, KeyTypeKeyCompare comp) { return iterator(node_algorithms::upper_bound (this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator upper_bound(const key_type &key) const { return this->upper_bound(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType &key, KeyTypeKeyCompare comp) const { return const_iterator(node_algorithms::upper_bound (this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } template<class KeyTypeKeyCompare> struct key_node_comp_ret { typedef detail::key_nodeptr_comp<KeyTypeKeyCompare, value_traits, key_of_value> type; }; template<class KeyTypeKeyCompare> BOOST_INTRUSIVE_FORCEINLINE typename key_node_comp_ret<KeyTypeKeyCompare>::type key_node_comp(KeyTypeKeyCompare comp) const { return detail::key_nodeptr_comp<KeyTypeKeyCompare, value_traits, key_of_value>(comp, &this->get_value_traits()); } //find BOOST_INTRUSIVE_FORCEINLINE iterator find(const key_type &key) { return this->find(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType &key, KeyTypeKeyCompare comp) { return iterator (node_algorithms::find(this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } BOOST_INTRUSIVE_FORCEINLINE const_iterator find(const key_type &key) const { return this->find(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType &key, KeyTypeKeyCompare comp) const { return const_iterator (node_algorithms::find(this->header_ptr(), key, this->key_node_comp(comp)), this->priv_value_traits_ptr()); } //equal_range BOOST_INTRUSIVE_FORCEINLINE std::pair<iterator,iterator> equal_range(const key_type &key) { return this->equal_range(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType &key, KeyTypeKeyCompare comp) { std::pair<node_ptr, node_ptr> ret (node_algorithms::equal_range(this->header_ptr(), key, this->key_node_comp(comp))); return std::pair<iterator, iterator>( iterator(ret.first, this->priv_value_traits_ptr()) , iterator(ret.second, this->priv_value_traits_ptr())); } BOOST_INTRUSIVE_FORCEINLINE std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const { return this->equal_range(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType &key, KeyTypeKeyCompare comp) const { std::pair<node_ptr, node_ptr> ret (node_algorithms::equal_range(this->header_ptr(), key, this->key_node_comp(comp))); return std::pair<const_iterator, const_iterator>( const_iterator(ret.first, this->priv_value_traits_ptr()) , const_iterator(ret.second, this->priv_value_traits_ptr())); } //lower_bound_range BOOST_INTRUSIVE_FORCEINLINE std::pair<iterator,iterator> lower_bound_range(const key_type &key) { return this->lower_bound_range(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> lower_bound_range(const KeyType &key, KeyTypeKeyCompare comp) { std::pair<node_ptr, node_ptr> ret (node_algorithms::lower_bound_range(this->header_ptr(), key, this->key_node_comp(comp))); return std::pair<iterator, iterator>( iterator(ret.first, this->priv_value_traits_ptr()) , iterator(ret.second, this->priv_value_traits_ptr())); } BOOST_INTRUSIVE_FORCEINLINE std::pair<const_iterator, const_iterator> lower_bound_range(const key_type &key) const { return this->lower_bound_range(key, this->key_comp()); } template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> lower_bound_range(const KeyType &key, KeyTypeKeyCompare comp) const { std::pair<node_ptr, node_ptr> ret (node_algorithms::lower_bound_range(this->header_ptr(), key, this->key_node_comp(comp))); return std::pair<const_iterator, const_iterator>( const_iterator(ret.first, this->priv_value_traits_ptr()) , const_iterator(ret.second, this->priv_value_traits_ptr())); } //bounded_range BOOST_INTRUSIVE_FORCEINLINE std::pair<iterator,iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) { return this->bounded_range(lower_key, upper_key, this->key_comp(), left_closed, right_closed); } template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType &lower_key, const KeyType &upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) { std::pair<node_ptr, node_ptr> ret (node_algorithms::bounded_range (this->header_ptr(), lower_key, upper_key, this->key_node_comp(comp), left_closed, right_closed)); return std::pair<iterator, iterator>( iterator(ret.first, this->priv_value_traits_ptr()) , iterator(ret.second, this->priv_value_traits_ptr())); } BOOST_INTRUSIVE_FORCEINLINE std::pair<const_iterator,const_iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const { return this->bounded_range(lower_key, upper_key, this->key_comp(), left_closed, right_closed); } template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator,const_iterator> bounded_range (const KeyType &lower_key, const KeyType &upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const { std::pair<node_ptr, node_ptr> ret (node_algorithms::bounded_range (this->header_ptr(), lower_key, upper_key, this->key_node_comp(comp), left_closed, right_closed)); return std::pair<const_iterator, const_iterator>( const_iterator(ret.first, this->priv_value_traits_ptr()) , const_iterator(ret.second, this->priv_value_traits_ptr())); } //insert_unique_check BOOST_INTRUSIVE_FORCEINLINE std::pair<iterator, bool> insert_unique_check (const key_type &key, insert_commit_data &commit_data) { return this->insert_unique_check(key, this->key_comp(), commit_data); } BOOST_INTRUSIVE_FORCEINLINE std::pair<iterator, bool> insert_unique_check (const_iterator hint, const key_type &key, insert_commit_data &commit_data) { return this->insert_unique_check(hint, key, this->key_comp(), commit_data); } template<class KeyType, class KeyTypeKeyCompare> BOOST_INTRUSIVE_DOC1ST(std::pair<iterator BOOST_INTRUSIVE_I bool> , typename detail::disable_if_convertible <KeyType BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I std::pair<iterator BOOST_INTRUSIVE_I bool> >::type) insert_unique_check (const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data) { std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (this->header_ptr(), key, this->key_node_comp(comp), commit_data)); return std::pair<iterator, bool>(iterator(ret.first, this->priv_value_traits_ptr()), ret.second); } template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_unique_check (const_iterator hint, const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data) { std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (this->header_ptr(), hint.pointed_node(), key, this->key_node_comp(comp), commit_data)); return std::pair<iterator, bool>(iterator(ret.first, this->priv_value_traits_ptr()), ret.second); } }; //Due to MSVC's EBO implementation, to save space and maintain the ABI, we must put the non-empty size member //in the first position, but if size is not going to be stored then we'll use an specialization //that doesn't inherit from size_holder template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, bool ConstantTimeSize, class SizeType, algo_types AlgoType, typename HeaderHolder> struct bstbase_hack : public detail::size_holder<ConstantTimeSize, SizeType> , public bstbase2 < ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, AlgoType, HeaderHolder> { typedef bstbase2< ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, AlgoType, HeaderHolder> base_type; typedef typename base_type::key_compare key_compare; typedef typename base_type::value_compare value_compare; typedef SizeType size_type; typedef typename base_type::node_traits node_traits; typedef typename get_algo <AlgoType, node_traits>::type algo_type; BOOST_INTRUSIVE_FORCEINLINE bstbase_hack(const key_compare & comp, const ValueTraits &vtraits) : base_type(comp, vtraits) { this->sz_traits().set_size(size_type(0)); } typedef detail::size_holder<ConstantTimeSize, SizeType> size_traits; BOOST_INTRUSIVE_FORCEINLINE size_traits &sz_traits() { return static_cast<size_traits &>(*this); } BOOST_INTRUSIVE_FORCEINLINE const size_traits &sz_traits() const { return static_cast<const size_traits &>(*this); } }; //Specialization for ConstantTimeSize == false template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, class SizeType, algo_types AlgoType, typename HeaderHolder> struct bstbase_hack<ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, false, SizeType, AlgoType, HeaderHolder> : public bstbase2 < ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, AlgoType, HeaderHolder> { typedef bstbase2< ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, AlgoType, HeaderHolder> base_type; typedef typename base_type::value_compare value_compare; typedef typename base_type::key_compare key_compare; BOOST_INTRUSIVE_FORCEINLINE bstbase_hack(const key_compare & comp, const ValueTraits &vtraits) : base_type(comp, vtraits) {} typedef detail::size_holder<false, SizeType> size_traits; BOOST_INTRUSIVE_FORCEINLINE size_traits sz_traits() const { return size_traits(); } }; //This class will template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, bool ConstantTimeSize, class SizeType, algo_types AlgoType, typename HeaderHolder> struct bstbase : public bstbase_hack< ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, ConstantTimeSize, SizeType, AlgoType, HeaderHolder> { typedef bstbase_hack< ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, ConstantTimeSize, SizeType, AlgoType, HeaderHolder> base_type; typedef ValueTraits value_traits; typedef typename base_type::value_compare value_compare; typedef typename base_type::key_compare key_compare; typedef typename base_type::const_reference const_reference; typedef typename base_type::reference reference; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::node_traits node_traits; typedef typename get_algo <AlgoType, node_traits>::type node_algorithms; typedef SizeType size_type; BOOST_INTRUSIVE_FORCEINLINE bstbase(const key_compare & comp, const ValueTraits &vtraits) : base_type(comp, vtraits) {} //Detach all inserted nodes. This will add exception safety to bstree_impl //constructors inserting elements. ~bstbase() { if(is_safe_autounlink<value_traits::link_mode>::value){ node_algorithms::clear_and_dispose ( this->header_ptr() , detail::node_disposer<detail::null_disposer, value_traits, AlgoType> (detail::null_disposer(), &this->get_value_traits())); node_algorithms::init(this->header_ptr()); } } }; /// @endcond //! The class template bstree is an unbalanced intrusive binary search tree //! container. The no-throw guarantee holds only, if the key_compare object //! doesn't throw. //! //! The complexity guarantees only hold if the tree is balanced, logarithmic //! complexity would increase to linear if the tree is totally unbalanced. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, class SizeType, bool ConstantTimeSize, algo_types AlgoType, typename HeaderHolder> #endif class bstree_impl : public bstbase<ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, ConstantTimeSize, SizeType, AlgoType, HeaderHolder> { public: /// @cond typedef bstbase<ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, ConstantTimeSize, SizeType, AlgoType, HeaderHolder> data_type; typedef tree_iterator<ValueTraits, false> iterator_type; typedef tree_iterator<ValueTraits, true> const_iterator_type; /// @endcond typedef BOOST_INTRUSIVE_IMPDEF(ValueTraits) value_traits; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::pointer) pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::const_pointer) const_pointer; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<pointer>::element_type) value_type; typedef BOOST_INTRUSIVE_IMPDEF(typename data_type::key_type) key_type; typedef BOOST_INTRUSIVE_IMPDEF(typename data_type::key_of_value) key_of_value; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<pointer>::reference) reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::reference) const_reference; typedef BOOST_INTRUSIVE_IMPDEF(typename pointer_traits<const_pointer>::difference_type) difference_type; typedef BOOST_INTRUSIVE_IMPDEF(SizeType) size_type; typedef BOOST_INTRUSIVE_IMPDEF(typename data_type::value_compare) value_compare; typedef BOOST_INTRUSIVE_IMPDEF(typename data_type::key_compare) key_compare; typedef BOOST_INTRUSIVE_IMPDEF(iterator_type) iterator; typedef BOOST_INTRUSIVE_IMPDEF(const_iterator_type) const_iterator; typedef BOOST_INTRUSIVE_IMPDEF(boost::intrusive::reverse_iterator<iterator>) reverse_iterator; typedef BOOST_INTRUSIVE_IMPDEF(boost::intrusive::reverse_iterator<const_iterator>) const_reverse_iterator; typedef BOOST_INTRUSIVE_IMPDEF(typename value_traits::node_traits) node_traits; typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::node) node; typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::node_ptr) node_ptr; typedef BOOST_INTRUSIVE_IMPDEF(typename node_traits::const_node_ptr) const_node_ptr; /// @cond typedef typename get_algo<AlgoType, node_traits>::type algo_type; /// @endcond typedef BOOST_INTRUSIVE_IMPDEF(algo_type) node_algorithms; static const bool constant_time_size = ConstantTimeSize; static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value; /// @cond private: //noncopyable BOOST_MOVABLE_BUT_NOT_COPYABLE(bstree_impl) static const bool safemode_or_autounlink = is_safe_autounlink<value_traits::link_mode>::value; //Constant-time size is incompatible with auto-unlink hooks! BOOST_STATIC_ASSERT(!(constant_time_size && ((int)value_traits::link_mode == (int)auto_unlink))); protected: /// @endcond public: typedef typename node_algorithms::insert_commit_data insert_commit_data; //! <b>Effects</b>: Constructs an empty container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor of the key_compare object throws. Basic guarantee. bstree_impl() : data_type(key_compare(), value_traits()) {} //! <b>Effects</b>: Constructs an empty container with given comparison and traits. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor of the key_compare object throws. Basic guarantee. explicit bstree_impl( const key_compare &cmp, const value_traits &v_traits = value_traits()) : data_type(cmp, v_traits) {} //! <b>Requires</b>: Dereferencing iterator must yield an lvalue of type value_type. //! cmp must be a comparison function that induces a strict weak ordering. //! //! <b>Effects</b>: Constructs an empty container and inserts elements from //! [b, e). //! //! <b>Complexity</b>: Linear in N if [b, e) is already sorted using //! comp and otherwise N * log N, where N is the distance between first and last. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor/operator() of the key_compare object throws. Basic guarantee. template<class Iterator> bstree_impl( bool unique, Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : data_type(cmp, v_traits) { //bstbase releases elements in case of exceptions if(unique) this->insert_unique(b, e); else this->insert_equal(b, e); } //! <b>Effects</b>: Constructs a container moving resources from another container. //! Internal comparison object and value traits are move constructed and //! nodes belonging to x (except the node representing the "end") are linked to *this. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_traits::node_traits::node's //! move constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the move constructor of the comparison objet throws. bstree_impl(BOOST_RV_REF(bstree_impl) x) : data_type(::boost::move(x.comp()), ::boost::move(x.get_value_traits())) { this->swap(x); } //! <b>Effects</b>: Equivalent to swap //! BOOST_INTRUSIVE_FORCEINLINE bstree_impl& operator=(BOOST_RV_REF(bstree_impl) x) { this->swap(x); return *this; } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Effects</b>: Detaches all elements from this. The objects in the set //! are not deleted (i.e. no destructors are called), but the nodes according to //! the value_traits template parameter are reinitialized and thus can be reused. //! //! <b>Complexity</b>: Linear to elements contained in *this. //! //! <b>Throws</b>: Nothing. ~bstree_impl() {} //! <b>Effects</b>: Returns an iterator pointing to the beginning of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator begin() BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the beginning of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator begin() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the beginning of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator cbegin() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns an iterator pointing to the end of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator end() BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the end of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator end() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the end of the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator cend() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning of the //! reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. reverse_iterator rbegin() BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator rbegin() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator crbegin() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. reverse_iterator rend() BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator rend() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_reverse_iterator crend() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a iterator pointing to the root node of the container or end() if not present. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator root() BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the root node of the container or cend() if not present. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator root() const BOOST_NOEXCEPT; //! <b>Effects</b>: Returns a const_iterator pointing to the root node of the container or cend() if not present. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator croot() const BOOST_NOEXCEPT; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Precondition</b>: end_iterator must be a valid end iterator //! of the container. //! //! <b>Effects</b>: Returns a const reference to the container associated to the end iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. static bstree_impl &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT { return static_cast<bstree_impl&> (data_type::get_tree_base_from_end_iterator(end_iterator)); } //! <b>Precondition</b>: end_iterator must be a valid end const_iterator //! of the container. //! //! <b>Effects</b>: Returns a const reference to the container associated to the iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. static const bstree_impl &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT { return static_cast<bstree_impl&> (data_type::get_tree_base_from_end_iterator(end_iterator)); } //! <b>Precondition</b>: it must be a valid iterator //! of the container. //! //! <b>Effects</b>: Returns a const reference to the container associated to the iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Logarithmic. static bstree_impl &container_from_iterator(iterator it) BOOST_NOEXCEPT { return container_from_end_iterator(it.end_iterator_from_it()); } //! <b>Precondition</b>: it must be a valid end const_iterator //! of container. //! //! <b>Effects</b>: Returns a const reference to the container associated to the end iterator //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Logarithmic. static const bstree_impl &container_from_iterator(const_iterator it) BOOST_NOEXCEPT { return container_from_end_iterator(it.end_iterator_from_it()); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Effects</b>: Returns the key_compare object used by the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If key_compare copy-constructor throws. key_compare key_comp() const; //! <b>Effects</b>: Returns the value_compare object used by the container. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_compare copy-constructor throws. value_compare value_comp() const; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Effects</b>: Returns true if the container is empty. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. bool empty() const BOOST_NOEXCEPT { if(ConstantTimeSize){ return !this->data_type::sz_traits().get_size(); } else{ return algo_type::unique(this->header_ptr()); } } //! <b>Effects</b>: Returns the number of elements stored in the container. //! //! <b>Complexity</b>: Linear to elements contained in *this //! if constant-time size option is disabled. Constant time otherwise. //! //! <b>Throws</b>: Nothing. size_type size() const BOOST_NOEXCEPT { BOOST_IF_CONSTEXPR(constant_time_size) return this->sz_traits().get_size(); else{ return (size_type)node_algorithms::size(this->header_ptr()); } } //! <b>Effects</b>: Swaps the contents of two containers. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the comparison functor's swap call throws. void swap(bstree_impl& other) { //This can throw ::boost::adl_move_swap(this->comp(), other.comp()); //These can't throw node_algorithms::swap_tree(this->header_ptr(), node_ptr(other.header_ptr())); this->sz_traits().swap(other.sz_traits()); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! Cloner should yield to nodes equivalent to the original nodes. //! //! <b>Effects</b>: Erases all the elements from *this //! calling Disposer::operator()(pointer), clones all the //! elements from src calling Cloner::operator()(const_reference ) //! and inserts them on *this. Copies the predicate from the source container. //! //! If cloner throws, all cloned elements are unlinked and disposed //! calling Disposer::operator()(pointer). //! //! <b>Complexity</b>: Linear to erased plus inserted elements. //! //! <b>Throws</b>: If cloner throws or predicate copy assignment throws. Basic guarantee. template <class Cloner, class Disposer> void clone_from(const bstree_impl &src, Cloner cloner, Disposer disposer) { this->clear_and_dispose(disposer); if(!src.empty()){ detail::exception_disposer<bstree_impl, Disposer> rollback(*this, disposer); node_algorithms::clone (src.header_ptr() ,this->header_ptr() ,detail::node_cloner <Cloner, value_traits, AlgoType>(cloner, &this->get_value_traits()) ,detail::node_disposer<Disposer, value_traits, AlgoType>(disposer, &this->get_value_traits())); this->sz_traits().set_size(src.sz_traits().get_size()); this->comp() = src.comp(); rollback.release(); } } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! Cloner should yield to nodes equivalent to the original nodes. //! //! <b>Effects</b>: Erases all the elements from *this //! calling Disposer::operator()(pointer), clones all the //! elements from src calling Cloner::operator()(reference) //! and inserts them on *this. Copies the predicate from the source container. //! //! If cloner throws, all cloned elements are unlinked and disposed //! calling Disposer::operator()(pointer). //! //! <b>Complexity</b>: Linear to erased plus inserted elements. //! //! <b>Throws</b>: If cloner throws or predicate copy assignment throws. Basic guarantee. //! //! <b>Note</b>: This version can modify the source container, useful to implement //! move semantics. template <class Cloner, class Disposer> void clone_from(BOOST_RV_REF(bstree_impl) src, Cloner cloner, Disposer disposer) { this->clear_and_dispose(disposer); if(!src.empty()){ detail::exception_disposer<bstree_impl, Disposer> rollback(*this, disposer); node_algorithms::clone (src.header_ptr() ,this->header_ptr() ,detail::node_cloner <Cloner, value_traits, AlgoType, false>(cloner, &this->get_value_traits()) ,detail::node_disposer<Disposer, value_traits, AlgoType>(disposer, &this->get_value_traits())); this->sz_traits().set_size(src.sz_traits().get_size()); this->comp() = src.comp(); rollback.release(); } } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Inserts value into the container before the upper bound. //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: If the internal key_compare ordering function throws. Strong guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(reference value) { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); iterator ret(node_algorithms::insert_equal_upper_bound (this->header_ptr(), to_insert, this->key_node_comp(this->key_comp())), this->priv_value_traits_ptr()); this->sz_traits().increment(); return ret; } //! <b>Requires</b>: value must be an lvalue, and "hint" must be //! a valid iterator. //! //! <b>Effects</b>: Inserts x into the container, using "hint" as a hint to //! where it will be inserted. If "hint" is the upper_bound //! the insertion takes constant time (two comparisons in the worst case) //! //! <b>Complexity</b>: Logarithmic in general, but it is amortized //! constant time if t is inserted immediately before hint. //! //! <b>Throws</b>: If the internal key_compare ordering function throws. Strong guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(const_iterator hint, reference value) { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); iterator ret(node_algorithms::insert_equal (this->header_ptr(), hint.pointed_node(), to_insert, this->key_node_comp(this->key_comp())), this->priv_value_traits_ptr()); this->sz_traits().increment(); return ret; } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Inserts a each element of a range into the container //! before the upper bound of the key of each element. //! //! <b>Complexity</b>: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! <b>Throws</b>: If the comparison functor call throws. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_equal(Iterator b, Iterator e) { iterator iend(this->end()); for (; b != e; ++b) this->insert_equal(iend, *b); } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Inserts value into the container if the value //! is not already present. //! //! <b>Complexity</b>: Average complexity for insert element is at //! most logarithmic. //! //! <b>Throws</b>: If the comparison functor call throws. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. std::pair<iterator, bool> insert_unique(reference value) { insert_commit_data commit_data; std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (this->header_ptr(), key_of_value()(value), this->key_node_comp(this->key_comp()), commit_data)); return std::pair<iterator, bool> ( ret.second ? this->insert_unique_commit(value, commit_data) : iterator(ret.first, this->priv_value_traits_ptr()) , ret.second); } //! <b>Requires</b>: value must be an lvalue, and "hint" must be //! a valid iterator //! //! <b>Effects</b>: Tries to insert x into the container, using "hint" as a hint //! to where it will be inserted. //! //! <b>Complexity</b>: Logarithmic in general, but it is amortized //! constant time (two comparisons in the worst case) //! if t is inserted immediately before hint. //! //! <b>Throws</b>: If the comparison functor call throws. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_unique(const_iterator hint, reference value) { insert_commit_data commit_data; std::pair<node_ptr, bool> ret = (node_algorithms::insert_unique_check (this->header_ptr(), hint.pointed_node(), key_of_value()(value), this->key_node_comp(this->key_comp()), commit_data)); return ret.second ? this->insert_unique_commit(value, commit_data) : iterator(ret.first, this->priv_value_traits_ptr()); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Tries to insert each element of a range into the container. //! //! <b>Complexity</b>: Insert range is in general O(N * log(N)), where N is the //! size of the range. However, it is linear in N if the range is already sorted //! by value_comp(). //! //! <b>Throws</b>: If the comparison functor call throws. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_unique(Iterator b, Iterator e) { if(this->empty()){ iterator iend(this->end()); for (; b != e; ++b) this->insert_unique(iend, *b); } else{ for (; b != e; ++b) this->insert_unique(*b); } } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Average complexity is at most logarithmic. //! //! <b>Throws</b>: If the comp ordering function throws. Strong guarantee. std::pair<iterator, bool> insert_unique_check(const key_type &key, insert_commit_data &commit_data); //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself, using "hint" //! as a hint to where it will be inserted. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Logarithmic in general, but it's amortized //! constant time if t is inserted immediately before hint. //! //! <b>Throws</b>: If the comp ordering function throws. Strong guarantee. std::pair<iterator, bool> insert_unique_check(const_iterator hint, const key_type &key, insert_commit_data &commit_data); //! <b>Requires</b>: comp must be a comparison function that induces //! the same strict weak ordering as key_compare. The difference is that //! comp compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Average complexity is at most logarithmic. //! //! <b>Throws</b>: If the comp ordering function throws. Strong guarantee. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that //! part to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! "insert_commit" to insert the object in constant-time. This gives a total //! logarithmic complexity to the insertion: check(O(log(N)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_commit" only if no more //! objects are inserted or erased from the container. template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_unique_check (const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data); //! <b>Requires</b>: comp must be a comparison function that induces //! the same strict weak ordering as key_compare. The difference is that //! comp compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Checks if a value can be inserted in the container, using //! a user provided key instead of the value itself, using "hint" //! as a hint to where it will be inserted. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Logarithmic in general, but it's amortized //! constant time if t is inserted immediately before hint. //! //! <b>Throws</b>: If the comp ordering function throws. Strong guarantee. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! constructing that is used to impose the order is much cheaper to construct //! than the value_type and this function offers the possibility to use that key //! to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! "insert_commit" to insert the object in constant-time. This can give a total //! constant-time complexity to the insertion: check(O(1)) + commit(O(1)). //! //! "commit_data" remains valid for a subsequent "insert_commit" only if no more //! objects are inserted or erased from the container. template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_unique_check (const_iterator hint, const KeyType &key ,KeyTypeKeyCompare comp, insert_commit_data &commit_data); #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! <b>Requires</b>: value must be an lvalue of type value_type. commit_data //! must have been obtained from a previous call to "insert_check". //! No objects should have been inserted or erased from the container between //! the "insert_check" that filled "commit_data" and the call to "insert_commit". //! //! <b>Effects</b>: Inserts the value in the container using the information obtained //! from the "commit_data" that a previous "insert_check" filled. //! //! <b>Returns</b>: An iterator to the newly inserted object. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function has only sense if a "insert_check" has been //! previously executed to fill "commit_data". No value should be inserted or //! erased between the "insert_check" and "insert_commit" calls. iterator insert_unique_commit(reference value, const insert_commit_data &commit_data) BOOST_NOEXCEPT { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); #if !(defined(BOOST_DISABLE_ASSERTS) || ( defined(BOOST_ENABLE_ASSERT_DEBUG_HANDLER) && defined(NDEBUG) )) //Test insertion position is correct iterator p(commit_data.node, this->priv_value_traits_ptr()); if(!commit_data.link_left){ ++p; } //Check if the insertion point is correct to detect wrong //uses insert_unique_check BOOST_ASSERT(( p == this->end() || !this->comp()(*p, value) )); BOOST_ASSERT(( p == this->begin() || !this->comp()(value, *--p) )); #endif node_algorithms::insert_unique_commit (this->header_ptr(), to_insert, commit_data); this->sz_traits().increment(); return iterator(to_insert, this->priv_value_traits_ptr()); } //! <b>Requires</b>: value must be an lvalue, "pos" must be //! a valid iterator (or end) and must be the succesor of value //! once inserted according to the predicate //! //! <b>Effects</b>: Inserts x into the container before "pos". //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if "pos" is not //! the successor of "value" container ordering invariant will be broken. //! This is a low-level function to be used only for performance reasons //! by advanced users. iterator insert_before(const_iterator pos, reference value) BOOST_NOEXCEPT { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); this->sz_traits().increment(); return iterator(node_algorithms::insert_before (this->header_ptr(), pos.pointed_node(), to_insert), this->priv_value_traits_ptr()); } //! <b>Requires</b>: value must be an lvalue, and it must be no less //! than the greatest inserted key //! //! <b>Effects</b>: Inserts x into the container in the last position. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if value is //! less than the greatest inserted key container ordering invariant will be broken. //! This function is slightly more efficient than using "insert_before". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_back(reference value) BOOST_NOEXCEPT { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); this->sz_traits().increment(); node_algorithms::push_back(this->header_ptr(), to_insert); } //! <b>Requires</b>: value must be an lvalue, and it must be no greater //! than the minimum inserted key //! //! <b>Effects</b>: Inserts x into the container in the first position. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function does not check preconditions so if value is //! greater than the minimum inserted key container ordering invariant will be broken. //! This function is slightly more efficient than using "insert_before". //! This is a low-level function to be used only for performance reasons //! by advanced users. void push_front(reference value) BOOST_NOEXCEPT { node_ptr to_insert(this->get_value_traits().to_node_ptr(value)); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || node_algorithms::unique(to_insert)); this->sz_traits().increment(); node_algorithms::push_front(this->header_ptr(), to_insert); } //! <b>Effects</b>: Erases the element pointed to by i. //! //! <b>Complexity</b>: Average complexity for erase element is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator i) BOOST_NOEXCEPT { const_iterator ret(i); ++ret; node_ptr to_erase(i.pointed_node()); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || !node_algorithms::unique(to_erase)); node_algorithms::erase(this->header_ptr(), to_erase); this->sz_traits().decrement(); BOOST_IF_CONSTEXPR(safemode_or_autounlink) node_algorithms::init(to_erase); return ret.unconst(); } //! <b>Effects</b>: Erases the range pointed to by b end e. //! //! <b>Complexity</b>: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. iterator erase(const_iterator b, const_iterator e) BOOST_NOEXCEPT { size_type n; return this->private_erase(b, e, n); } //! <b>Effects</b>: Erases all the elements with the given value. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. size_type erase(const key_type &key) BOOST_NOEXCEPT { return this->erase(key, this->key_comp()); } //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! comp(nk, key) and !comp(key, nk), with comp(nk, key) implying !comp(key, nk), //! with nk the key_type of a value_type inserted into `*this`. //! //! <b>Effects</b>: Erases all the elements with the given key. //! according to the comparison functor "comp". //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class KeyType, class KeyTypeKeyCompare> BOOST_INTRUSIVE_DOC1ST(size_type , typename detail::disable_if_convertible<KeyTypeKeyCompare BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I size_type>::type) erase(const KeyType& key, KeyTypeKeyCompare comp) { std::pair<iterator,iterator> p = this->equal_range(key, comp); size_type n; this->private_erase(p.first, p.second, n); return n; } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the element pointed to by i. //! Disposer::operator()(pointer) is called for the removed element. //! //! <b>Complexity</b>: Average complexity for erase element is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer) BOOST_NOEXCEPT { node_ptr to_erase(i.pointed_node()); iterator ret(this->erase(i)); disposer(this->get_value_traits().to_value_ptr(to_erase)); return ret; } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given value. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class Disposer> size_type erase_and_dispose(const key_type &key, Disposer disposer) { std::pair<iterator,iterator> p = this->equal_range(key); size_type n; this->private_erase(p.first, p.second, n, disposer); return n; } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the range pointed to by b end e. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Complexity</b>: Average complexity for erase range is at most //! O(log(size() + N)), where N is the number of elements in the range. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) BOOST_NOEXCEPT { size_type n; return this->private_erase(b, e, n, disposer); } //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! comp(nk, key) and !comp(key, nk), with comp(nk, key) implying !comp(key, nk) //! and nk the key_type of a value_type inserted into `*this`. //! //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given key. //! according to the comparison functor "comp". //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: O(log(size() + N). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class KeyType, class KeyTypeKeyCompare, class Disposer> BOOST_INTRUSIVE_DOC1ST(size_type , typename detail::disable_if_convertible<KeyTypeKeyCompare BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I size_type>::type) erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer) { std::pair<iterator,iterator> p = this->equal_range(key, comp); size_type n; this->private_erase(p.first, p.second, n, disposer); return n; } //! <b>Effects</b>: Erases all of the elements. //! //! <b>Complexity</b>: Linear to the number of elements on the container. //! if it's a safe-mode or auto-unlink value_type. Constant time otherwise. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. void clear() BOOST_NOEXCEPT { BOOST_IF_CONSTEXPR(safemode_or_autounlink){ this->clear_and_dispose(detail::null_disposer()); } else{ node_algorithms::init_header(this->header_ptr()); this->sz_traits().set_size(0); } } //! <b>Effects</b>: Erases all of the elements calling disposer(p) for //! each node to be erased. //! <b>Complexity</b>: Average complexity for is at most O(log(size() + N)), //! where N is the number of elements in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. Calls N times to disposer functor. template<class Disposer> void clear_and_dispose(Disposer disposer) BOOST_NOEXCEPT { node_algorithms::clear_and_dispose(this->header_ptr() , detail::node_disposer<Disposer, value_traits, AlgoType>(disposer, &this->get_value_traits())); node_algorithms::init_header(this->header_ptr()); this->sz_traits().set_size(0); } //! <b>Effects</b>: Returns the number of contained elements with the given value //! //! <b>Complexity</b>: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given value. //! //! <b>Throws</b>: If `key_compare` throws. size_type count(const key_type &key) const { return size_type(this->count(key, this->key_comp())); } //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! comp(nk, key) and !comp(key, nk), with comp(nk, key) implying !comp(key, nk), //! and nk the key_type of a value_type inserted into `*this`. //! //! <b>Effects</b>: Returns the number of contained elements with the given key //! //! <b>Complexity</b>: Logarithmic to the number of elements contained plus lineal //! to number of objects with the given key. //! //! <b>Throws</b>: If `comp` throws. template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType &key, KeyTypeKeyCompare comp) const { std::pair<const_iterator, const_iterator> ret = this->equal_range(key, comp); size_type n = 0; for(; ret.first != ret.second; ++ret.first){ ++n; } return n; } #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //Add non-const overloads to theoretically const members //as some algorithms have different behavior when non-const versions are used (like splay trees). size_type count(const key_type &key) { return size_type(this->count(key, this->key_comp())); } template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType &key, KeyTypeKeyCompare comp) { std::pair<const_iterator, const_iterator> ret = this->equal_range(key, comp); size_type n = 0; for(; ret.first != ret.second; ++ret.first){ ++n; } return n; } #else //defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. iterator lower_bound(const key_type &key); //! <b>Effects</b>: Returns an iterator to the first element whose //! key is not less than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. const_iterator lower_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::bstree::lower_bound(const key_type &) template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType &key, KeyTypeKeyCompare comp) const; //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. iterator upper_bound(const key_type &key); //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! !comp(key, nk), with nk the key_type of a value_type inserted into `*this`. //! //! <b>Effects</b>: Returns an iterator to the first element whose //! key is greater than k according to comp or end() if that element //! does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `comp` throws. template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::bstree::upper_bound(const key_type &) const_iterator upper_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType &key, KeyTypeKeyCompare comp) const; //! <b>Effects</b>: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. iterator find(const key_type &key); //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! comp(nk, key) and !comp(key, nk), with comp(nk, key) implying !comp(key, nk), //! and nk the key_type of a value_type inserted into `*this`. //! //! <b>Effects</b>: Finds an iterator to the first element whose key is //! k or end() if that element does not exist. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `comp` throws. template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::bstree::find(const key_type &) const_iterator find(const key_type &key) const; //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType &key, KeyTypeKeyCompare comp) const; //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. std::pair<iterator,iterator> equal_range(const key_type &key); //! <b>Requires</b>: key is a value such that `*this` is partitioned with respect to //! comp(nk, key) and !comp(key, nk), with comp(nk, key) implying !comp(key, nk), //! with nk the key_type of a value_type inserted into `*this`. //! //! <b>Effects</b>: Finds a range containing all elements whose key is k or //! an empty range that indicates the position where those elements would be //! if they there is no elements with key k. //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `comp` throws. template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType &key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::bstree::equal_range(const key_type &) std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const; //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType &key, KeyTypeKeyCompare comp) const; //! <b>Requires</b>: //! `upper_key` shall not precede `lower_key` according to key_compare. //! [key_comp()(upper_key, lower_key) shall be false] //! //! If `lower_key` is equivalent to `upper_key` //! [!key_comp()(upper_key, lower_key) && !key_comp()(lower_key, upper_key)] then //! ('left_closed' || 'right_closed') must be false. //! //! <b>Effects</b>: Returns an a pair with the following criteria: //! //! first = lower_bound(lower_key) if left_closed, upper_bound(lower_key) otherwise //! //! second = upper_bound(upper_key) if right_closed, lower_bound(upper_key) otherwise //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `key_compare` throws. //! //! <b>Note</b>: This function can be more efficient than calling upper_bound //! and lower_bound for lower_value and upper_value. //! //! <b>Note</b>: Experimental function, the interface might change in future releases. std::pair<iterator,iterator> bounded_range (const key_type &lower_key, const key_type &upper_value, bool left_closed, bool right_closed); //! <b>Requires</b>: //! `lower_key` is a value such that `*this` is partitioned with respect to //! comp(nk, lower_key) if left_closed is true, with respect to !comp(lower_key, nk) otherwise. //! //! `upper_key` is a value such that `*this` is partitioned with respect to //! !comp(upper_key, nk) if right_closed is true, with respect to comp(nk, upper_key) otherwise. //! //! `upper_key` shall not precede `lower_key` according to comp //! [comp(upper_key, lower_key) shall be false] //! //! If `lower_key` is equivalent to `upper_key` //! [!comp(upper_key, lower_key) && !comp(lower_key, upper_key)] then //! ('left_closed' || 'right_closed') must be false. //! //! <b>Effects</b>: Returns an a pair with the following criteria: //! //! first = lower_bound(lower_key, comp) if left_closed, upper_bound(lower_key, comp) otherwise //! //! second = upper_bound(upper_key, comp) if right_closed, lower_bound(upper_key, comp) otherwise //! //! <b>Complexity</b>: Logarithmic. //! //! <b>Throws</b>: If `comp` throws. //! //! <b>Note</b>: This function can be more efficient than calling upper_bound //! and lower_bound for lower_key and upper_key. //! //! <b>Note</b>: Experimental function, the interface might change in future releases. template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType &lower_key, const KeyType &upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::bstree::bounded_range(const key_type &,const key_type &,bool,bool) std::pair<const_iterator,const_iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool) template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator,const_iterator> bounded_range (const KeyType &lower_key, const KeyType &upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const; //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid iterator i belonging to the set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static iterator s_iterator_to(reference value) BOOST_NOEXCEPT; //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static const_iterator s_iterator_to(const_reference value) BOOST_NOEXCEPT; //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid iterator i belonging to the set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator iterator_to(reference value) BOOST_NOEXCEPT; //! <b>Requires</b>: value must be an lvalue and shall be in a set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_iterator i belonging to the //! set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator iterator_to(const_reference value) const BOOST_NOEXCEPT; //! <b>Requires</b>: value shall not be in a container. //! //! <b>Effects</b>: init_node puts the hook of a value in a well-known default //! state. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant time. //! //! <b>Note</b>: This function puts the hook in the well-known default state //! used by auto_unlink and safe hooks. static void init_node(reference value) BOOST_NOEXCEPT; #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: Unlinks the leftmost node from the container. //! //! <b>Complexity</b>: Average complexity is constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function breaks the container and the container can //! only be used for more unlink_leftmost_without_rebalance calls. //! This function is normally used to achieve a step by step //! controlled destruction of the container. pointer unlink_leftmost_without_rebalance() BOOST_NOEXCEPT { node_ptr to_be_disposed(node_algorithms::unlink_leftmost_without_rebalance (this->header_ptr())); if(!to_be_disposed) return 0; this->sz_traits().decrement(); BOOST_IF_CONSTEXPR(safemode_or_autounlink)//If this is commented does not work with normal_link node_algorithms::init(to_be_disposed); return this->get_value_traits().to_value_ptr(to_be_disposed); } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Requires</b>: replace_this must be a valid iterator of *this //! and with_this must not be inserted in any container. //! //! <b>Effects</b>: Replaces replace_this in its position in the //! container with with_this. The container does not need to be rebalanced. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This function will break container ordering invariants if //! with_this is not equivalent to *replace_this according to the //! ordering rules. This function is faster than erasing and inserting //! the node, since no rebalancing or comparison is needed. void replace_node(iterator replace_this, reference with_this) BOOST_NOEXCEPT; //! <b>Effects</b>: Rebalances the tree. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear. void rebalance() BOOST_NOEXCEPT; //! <b>Requires</b>: old_root is a node of a tree. //! //! <b>Effects</b>: Rebalances the subtree rooted at old_root. //! //! <b>Returns</b>: The new root of the subtree. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Linear to the elements in the subtree. iterator rebalance_subtree(iterator root) BOOST_NOEXCEPT; #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: removes "value" from the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Logarithmic time. //! //! <b>Note</b>: This static function is only usable with non-constant //! time size containers that have stateless comparison functors. //! //! If the user calls //! this function with a constant time size container or stateful comparison //! functor a compilation error will be issued. static void remove_node(reference value) BOOST_NOEXCEPT { BOOST_STATIC_ASSERT((!constant_time_size)); node_ptr to_remove(value_traits::to_node_ptr(value)); node_algorithms::unlink(to_remove); BOOST_IF_CONSTEXPR(safemode_or_autounlink) node_algorithms::init(to_remove); } //! <b>Requires</b>: "source" container's Options can only can differ in the comparison //! function from *this. //! //! <b>Effects</b>: Attempts to extract each element in source and insert it into a using //! the comparison object of *this. If there is an element in a with key equivalent to the //! key of an element from source, then that element is not extracted from source. //! //! <b>Postcondition</b>: Pointers and references to the transferred elements of source refer //! to those same elements but as members of *this. Iterators referring to the transferred //! elements will continue to refer to their elements, but they now behave as iterators into *this, //! not into source. //! //! <b>Throws</b>: Nothing unless the comparison object throws. //! //! <b>Complexity</b>: N log(a.size() + N) (N has the value source.size()) #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options2> void merge_unique(bstree<T, Options2...> &); #else template<class Compare2> void merge_unique(bstree_impl <ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, AlgoType, HeaderHolder> &source) #endif { node_ptr it (node_algorithms::begin_node(source.header_ptr())) , itend(node_algorithms::end_node (source.header_ptr())); while(it != itend){ node_ptr const p(it); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || !node_algorithms::unique(p)); it = node_algorithms::next_node(it); if( node_algorithms::transfer_unique(this->header_ptr(), this->key_node_comp(this->key_comp()), source.header_ptr(), p) ){ source.sz_traits().decrement(); this->sz_traits().increment(); } } } //! <b>Requires</b>: "source" container's Options can only can differ in the comparison //! function from *this. //! //! <b>Effects</b>: Extracts each element in source and insert it into a using //! the comparison object of *this. //! //! <b>Postcondition</b>: Pointers and references to the transferred elements of source refer //! to those same elements but as members of *this. Iterators referring to the transferred //! elements will continue to refer to their elements, but they now behave as iterators into *this, //! not into source. //! //! <b>Throws</b>: Nothing unless the comparison object throws. //! //! <b>Complexity</b>: N log(a.size() + N) (N has the value source.size()) #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options2> void merge_equal(bstree<T, Options2...> &); #else template<class Compare2> void merge_equal(bstree_impl <ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, AlgoType, HeaderHolder> &source) #endif { node_ptr it (node_algorithms::begin_node(source.header_ptr())) , itend(node_algorithms::end_node (source.header_ptr())); while(it != itend){ node_ptr const p(it); BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || !node_algorithms::unique(p)); it = node_algorithms::next_node(it); node_algorithms::transfer_equal(this->header_ptr(), this->key_node_comp(this->key_comp()), source.header_ptr(), p); source.sz_traits().decrement(); this->sz_traits().increment(); } } //! <b>Effects</b>: Asserts the integrity of the container with additional checks provided by the user. //! //! <b>Complexity</b>: Linear time. //! //! <b>Note</b>: The method might not have effect when asserts are turned off (e.g., with NDEBUG). //! Experimental function, interface might change in future versions. template <class ExtraChecker> void check(ExtraChecker extra_checker) const { typedef detail::key_nodeptr_comp<key_compare, value_traits, key_of_value> nodeptr_comp_t; nodeptr_comp_t nodeptr_comp(this->key_comp(), &this->get_value_traits()); typedef typename get_node_checker<AlgoType, ValueTraits, nodeptr_comp_t, ExtraChecker>::type node_checker_t; typename node_checker_t::return_type checker_return; node_algorithms::check(this->header_ptr(), node_checker_t(nodeptr_comp, extra_checker), checker_return); BOOST_INTRUSIVE_INVARIANT_ASSERT(!constant_time_size || this->sz_traits().get_size() == checker_return.node_count); } //! <b>Effects</b>: Asserts the integrity of the container. //! //! <b>Complexity</b>: Linear time. //! //! <b>Note</b>: The method has no effect when asserts are turned off (e.g., with NDEBUG). //! Experimental function, interface might change in future versions. void check() const { check(detail::empty_node_checker<ValueTraits>()); } friend bool operator==(const bstree_impl &x, const bstree_impl &y) { if(constant_time_size && x.size() != y.size()){ return false; } return boost::intrusive::algo_equal(x.cbegin(), x.cend(), y.cbegin(), y.cend()); } friend bool operator!=(const bstree_impl &x, const bstree_impl &y) { return !(x == y); } friend bool operator<(const bstree_impl &x, const bstree_impl &y) { return ::boost::intrusive::algo_lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } friend bool operator>(const bstree_impl &x, const bstree_impl &y) { return y < x; } friend bool operator<=(const bstree_impl &x, const bstree_impl &y) { return !(x > y); } friend bool operator>=(const bstree_impl &x, const bstree_impl &y) { return !(x < y); } friend void swap(bstree_impl &x, bstree_impl &y) { x.swap(y); } /// @cond private: template<class Disposer> iterator private_erase(const_iterator b, const_iterator e, size_type &n, Disposer disposer) { for(n = 0; b != e; ++n) this->erase_and_dispose(b++, disposer); return b.unconst(); } iterator private_erase(const_iterator b, const_iterator e, size_type &n) { for(n = 0; b != e; ++n) this->erase(b++); return b.unconst(); } /// @endcond }; //! Helper metafunction to define a \c bstree that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void> #endif struct make_bstree { /// @cond typedef typename pack_options < bstree_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef bstree_impl < value_traits , typename packed_options::key_of_value , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size , BsTreeAlgorithms , typename packed_options::header_holder_type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif class bstree : public make_bstree<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type { typedef typename make_bstree <T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(bstree) public: typedef typename Base::key_compare key_compare; typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); BOOST_INTRUSIVE_FORCEINLINE bstree() : Base() {} BOOST_INTRUSIVE_FORCEINLINE explicit bstree( const key_compare &cmp, const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> BOOST_INTRUSIVE_FORCEINLINE bstree( bool unique, Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : Base(unique, b, e, cmp, v_traits) {} BOOST_INTRUSIVE_FORCEINLINE bstree(BOOST_RV_REF(bstree) x) : Base(BOOST_MOVE_BASE(Base, x)) {} BOOST_INTRUSIVE_FORCEINLINE bstree& operator=(BOOST_RV_REF(bstree) x) { return static_cast<bstree &>(this->Base::operator=(BOOST_MOVE_BASE(Base, x))); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(const bstree &src, Cloner cloner, Disposer disposer) { Base::clone_from(src, cloner, disposer); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(BOOST_RV_REF(bstree) src, Cloner cloner, Disposer disposer) { Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); } BOOST_INTRUSIVE_FORCEINLINE static bstree &container_from_end_iterator(iterator end_iterator) BOOST_NOEXCEPT { return static_cast<bstree &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static const bstree &container_from_end_iterator(const_iterator end_iterator) BOOST_NOEXCEPT { return static_cast<const bstree &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static bstree &container_from_iterator(iterator it) BOOST_NOEXCEPT { return static_cast<bstree &>(Base::container_from_iterator(it)); } BOOST_INTRUSIVE_FORCEINLINE static const bstree &container_from_iterator(const_iterator it) BOOST_NOEXCEPT { return static_cast<const bstree &>(Base::container_from_iterator(it)); } }; #endif } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_BSTREE_HPP
phusion/passenger
src/cxx_supportlib/vendor-modified/boost/intrusive/bstree.hpp
C++
mit
96,305
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Product\Model; use Doctrine\Common\Collections\Collection; use Sylius\Component\Attribute\Model\AttributeSubjectInterface; use Sylius\Component\Resource\Model\CodeAwareInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Model\SlugAwareInterface; use Sylius\Component\Resource\Model\TimestampableInterface; use Sylius\Component\Resource\Model\ToggleableInterface; use Sylius\Component\Resource\Model\TranslatableInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk> */ interface ProductInterface extends AttributeSubjectInterface, CodeAwareInterface, ResourceInterface, SlugAwareInterface, TimestampableInterface, ToggleableInterface, TranslatableInterface { /** * @return string */ public function getName(); /** * @param string $name */ public function setName($name); /** * @return string */ public function getDescription(); /** * @param string $description */ public function setDescription($description); /** * @return string */ public function getMetaKeywords(); /** * @param string $metaKeywords */ public function setMetaKeywords($metaKeywords); /** * @return string */ public function getMetaDescription(); /** * @param string $metaDescription */ public function setMetaDescription($metaDescription); /** * @return bool */ public function hasVariants(); /** * @return Collection|ProductVariantInterface[] */ public function getVariants(); /** * @param ProductVariantInterface $variant */ public function addVariant(ProductVariantInterface $variant); /** * @param ProductVariantInterface $variant */ public function removeVariant(ProductVariantInterface $variant); /** * @param ProductVariantInterface $variant * * @return bool */ public function hasVariant(ProductVariantInterface $variant); /** * @return bool */ public function hasOptions(); /** * @return Collection|ProductOptionInterface[] */ public function getOptions(); /** * @param ProductOptionInterface $option */ public function addOption(ProductOptionInterface $option); /** * @param ProductOptionInterface $option */ public function removeOption(ProductOptionInterface $option); /** * @param ProductOptionInterface $option * * @return bool */ public function hasOption(ProductOptionInterface $option); /** * @return bool */ public function isAvailable(); /** * @return \DateTime */ public function getAvailableOn(); /** * @param \DateTime|null $availableOn */ public function setAvailableOn(\DateTime $availableOn = null); /** * @return \DateTime */ public function getAvailableUntil(); /** * @param \DateTime|null $availableUntil */ public function setAvailableUntil(\DateTime $availableUntil = null); /** * @param ProductAssociationInterface $association */ public function addAssociation(ProductAssociationInterface $association); /** * @return ProductAssociationInterface[] */ public function getAssociations(); /** * @param ProductAssociationInterface $association */ public function removeAssociation(ProductAssociationInterface $association); /** * @return bool */ public function isSimple(); /** * @return bool */ public function isConfigurable(); }
sweoggy/Sylius
src/Sylius/Component/Product/Model/ProductInterface.php
PHP
mit
3,967
<!--Title:Indexing (under construction)--> <!--Url:indexing--> //TODO
jokokko/marten
documentation/documentation/postgres/indexing.md
Markdown
mit
71
# frozen_string_literal: true require "bundler/shared_helpers" Bundler::SharedHelpers.major_deprecation "Bundler no longer integrates with " \ "Capistrano, but Capistrano provides its own integration with " \ "Bundler via the capistrano-bundler gem. Use it instead." module Bundler class Deployment def self.define_task(context, task_method = :task, opts = {}) if defined?(Capistrano) && context.is_a?(Capistrano::Configuration) context_name = "capistrano" role_default = "{:except => {:no_release => true}}" error_type = ::Capistrano::CommandError else context_name = "vlad" role_default = "[:app]" error_type = ::Rake::CommandFailedError end roles = context.fetch(:bundle_roles, false) opts[:roles] = roles if roles context.send :namespace, :bundle do send :desc, <<-DESC Install the current Bundler environment. By default, gems will be \ installed to the shared/bundle path. Gems in the development and \ test group will not be installed. The install command is executed \ with the --deployment and --quiet flags. If the bundle cmd cannot \ be found then you can override the bundle_cmd variable to specify \ which one it should use. The base path to the app is fetched from \ the :latest_release variable. Set it for custom deploy layouts. You can override any of these defaults by setting the variables shown below. N.B. bundle_roles must be defined before you require 'bundler/#{context_name}' \ in your deploy.rb file. set :bundle_gemfile, "Gemfile" set :bundle_dir, File.join(fetch(:shared_path), 'bundle') set :bundle_flags, "--deployment --quiet" set :bundle_without, [:development, :test] set :bundle_with, [:mysql] set :bundle_cmd, "bundle" # e.g. "/opt/ruby/bin/bundle" set :bundle_roles, #{role_default} # e.g. [:app, :batch] DESC send task_method, :install, opts do bundle_cmd = context.fetch(:bundle_cmd, "bundle") bundle_flags = context.fetch(:bundle_flags, "--deployment --quiet") bundle_dir = context.fetch(:bundle_dir, File.join(context.fetch(:shared_path), "bundle")) bundle_gemfile = context.fetch(:bundle_gemfile, "Gemfile") bundle_without = [*context.fetch(:bundle_without, [:development, :test])].compact bundle_with = [*context.fetch(:bundle_with, [])].compact app_path = context.fetch(:latest_release) if app_path.to_s.empty? raise error_type.new("Cannot detect current release path - make sure you have deployed at least once.") end args = ["--gemfile #{File.join(app_path, bundle_gemfile)}"] args << "--path #{bundle_dir}" unless bundle_dir.to_s.empty? args << bundle_flags.to_s args << "--without #{bundle_without.join(" ")}" unless bundle_without.empty? args << "--with #{bundle_with.join(" ")}" unless bundle_with.empty? run "cd #{app_path} && #{bundle_cmd} install #{args.join(" ")}" end end end end end
sho-h/ruby_env
ruby-2.3.3-x64-mingw32/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/deployment.rb
Ruby
mit
3,265
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2005 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_CONS_ITERATOR_07172005_0849) #define FUSION_CONS_ITERATOR_07172005_0849 #include <boost/fusion/support/config.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/fusion/support/iterator_base.hpp> #include <boost/fusion/container/list/detail/deref_impl.hpp> #include <boost/fusion/container/list/detail/next_impl.hpp> #include <boost/fusion/container/list/detail/value_of_impl.hpp> #include <boost/fusion/container/list/detail/equal_to_impl.hpp> #include <boost/fusion/container/list/list_fwd.hpp> namespace boost { namespace fusion { struct nil_; struct cons_iterator_tag; struct forward_traversal_tag; template <typename Cons> struct cons_iterator_identity; template <typename Cons = nil_> struct cons_iterator : iterator_base<cons_iterator<Cons> > { typedef cons_iterator_tag fusion_tag; typedef forward_traversal_tag category; typedef Cons cons_type; typedef cons_iterator_identity< typename add_const<Cons>::type> identity; BOOST_FUSION_GPU_ENABLED explicit cons_iterator(cons_type& in_cons) : cons(in_cons) {} cons_type& cons; private: // silence MSVC warning C4512: assignment operator could not be generated cons_iterator& operator= (cons_iterator const&); }; struct nil_iterator : iterator_base<nil_iterator> { typedef forward_traversal_tag category; typedef cons_iterator_tag fusion_tag; typedef nil_ cons_type; typedef cons_iterator_identity< add_const<nil_>::type> identity; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED nil_iterator() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit nil_iterator(nil_ const&) {} }; template <> struct cons_iterator<nil_> : nil_iterator { BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED cons_iterator() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit cons_iterator(nil_ const&) {} }; template <> struct cons_iterator<nil_ const> : nil_iterator { BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED cons_iterator() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit cons_iterator(nil_ const&) {} }; template <> struct cons_iterator<list<> > : nil_iterator { BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED cons_iterator() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit cons_iterator(nil_ const&) {} }; template <> struct cons_iterator<list<> const> : nil_iterator { BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED cons_iterator() {} BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit cons_iterator(nil_ const&) {} }; }} #endif
viennautils/viennautils-dev
override/boost/fusion/container/list/cons_iterator.hpp
C++
mit
3,331
var fs = require('fs'); var os = require('os'); var path = require('path'); var util = require('./ci-util'); // initialize _package util.initializePackagePath(); // create the tasks.zip util.createTasksZip(); var branch = null; if (process.env.TF_BUILD) { // during CI agent checks out a commit, not a branch. // $(build.sourceBranch) indicates the branch name, e.g. releases/m108 branch = process.env.BUILD_SOURCEBRANCH; } else { // assumes user has checked out a branch. this is a fairly safe assumption. // this code only runs during "package" and "publish" build targets, which // is not typically run locally. branch = util.run('git symbolic-ref HEAD'); } var commitInfo = util.run('git log -1 --format=oneline'); // create the script fs.mkdirSync(util.hotfixLayoutPath); var scriptPath = path.join(util.hotfixLayoutPath, `${process.env.TASK}.ps1`); var scriptContent = '# Hotfix created from branch: ' + branch + os.EOL; scriptContent += '# Commit: ' + commitInfo + os.EOL; scriptContent += '$ErrorActionPreference=\'Stop\'' + os.EOL; scriptContent += 'Update-DistributedTaskDefinitions -TaskZip $PSScriptRoot\\tasks.zip' + os.EOL; fs.writeFileSync(scriptPath, scriptContent); // link the non-aggregate tasks zip var zipDestPath = path.join(util.hotfixLayoutPath, 'tasks.zip'); fs.linkSync(util.tasksZipPath, zipDestPath)
vithati/vsts-tasks
ci/stage-hotfix.js
JavaScript
mit
1,362
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\ORM; use ArrayObject; use BadMethodCallException; use Cake\Core\App; use Cake\Database\Schema\TableSchema; use Cake\Database\Type; use Cake\Datasource\ConnectionInterface; use Cake\Datasource\EntityInterface; use Cake\Datasource\Exception\InvalidPrimaryKeyException; use Cake\Datasource\RepositoryInterface; use Cake\Datasource\RulesAwareTrait; use Cake\Event\EventDispatcherInterface; use Cake\Event\EventDispatcherTrait; use Cake\Event\EventListenerInterface; use Cake\Event\EventManager; use Cake\ORM\Association\BelongsTo; use Cake\ORM\Association\BelongsToMany; use Cake\ORM\Association\HasMany; use Cake\ORM\Association\HasOne; use Cake\ORM\Exception\MissingEntityException; use Cake\ORM\Exception\PersistenceFailedException; use Cake\ORM\Exception\RolledbackTransactionException; use Cake\ORM\Rule\IsUnique; use Cake\Utility\Inflector; use Cake\Validation\ValidatorAwareTrait; use InvalidArgumentException; use RuntimeException; /** * Represents a single database table. * * Exposes methods for retrieving data out of it, and manages the associations * this table has to other tables. Multiple instances of this class can be created * for the same database table with different aliases, this allows you to address * your database structure in a richer and more expressive way. * * ### Retrieving data * * The primary way to retrieve data is using Table::find(). See that method * for more information. * * ### Dynamic finders * * In addition to the standard find($type) finder methods, CakePHP provides dynamic * finder methods. These methods allow you to easily set basic conditions up. For example * to filter users by username you would call * * ``` * $query = $users->findByUsername('mark'); * ``` * * You can also combine conditions on multiple fields using either `Or` or `And`: * * ``` * $query = $users->findByUsernameOrEmail('mark', 'mark@example.org'); * ``` * * ### Bulk updates/deletes * * You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes. * You should be aware that events will *not* be fired for bulk updates/deletes. * * ### Callbacks/events * * Table objects provide a few callbacks/events you can hook into to augment/replace * find operations. Each event uses the standard event subsystem in CakePHP * * - `beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)` * Fired before each find operation. By stopping the event and supplying a * return value you can bypass the find operation entirely. Any changes done * to the $query instance will be retained for the rest of the find. The * $primary parameter indicates whether or not this is the root query, * or an associated query. * * - `buildValidator(Event $event, Validator $validator, string $name)` * Allows listeners to modify validation rules for the provided named validator. * * - `buildRules(Event $event, RulesChecker $rules)` * Allows listeners to modify the rules checker by adding more rules. * * - `beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, string $operation)` * Fired before an entity is validated using the rules checker. By stopping this event, * you can return the final value of the rules checking operation. * * - `afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)` * Fired after the rules have been checked on the entity. By stopping this event, * you can return the final value of the rules checking operation. * * - `beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)` * Fired before each entity is saved. Stopping this event will abort the save * operation. When the event is stopped the result of the event will be returned. * * - `afterSave(Event $event, EntityInterface $entity, ArrayObject $options)` * Fired after an entity is saved. * * - `afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options)` * Fired after the transaction in which the save operation is wrapped has been committed. * It’s also triggered for non atomic saves where database operations are implicitly committed. * The event is triggered only for the primary table on which save() is directly called. * The event is not triggered if a transaction is started before calling save. * * - `beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)` * Fired before an entity is deleted. By stopping this event you will abort * the delete operation. * * - `afterDelete(Event $event, EntityInterface $entity, ArrayObject $options)` * Fired after an entity has been deleted. * * @see \Cake\Event\EventManager for reference on the events system. */ class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface { use EventDispatcherTrait; use RulesAwareTrait; use ValidatorAwareTrait; /** * Name of default validation set. * * @var string */ const DEFAULT_VALIDATOR = 'default'; /** * The alias this object is assigned to validators as. * * @var string */ const VALIDATOR_PROVIDER_NAME = 'table'; /** * The rules class name that is used. * * @var string */ const RULES_CLASS = 'Cake\ORM\RulesChecker'; /** * Name of the table as it can be found in the database * * @var string */ protected $_table; /** * Human name giving to this particular instance. Multiple objects representing * the same database table can exist by using different aliases. * * @var string */ protected $_alias; /** * Connection instance * * @var \Cake\Datasource\ConnectionInterface */ protected $_connection; /** * The schema object containing a description of this table fields * * @var \Cake\Database\Schema\TableSchema */ protected $_schema; /** * The name of the field that represents the primary key in the table * * @var string|array */ protected $_primaryKey; /** * The name of the field that represents a human readable representation of a row * * @var string */ protected $_displayField; /** * The associations container for this Table. * * @var \Cake\ORM\AssociationCollection */ protected $_associations; /** * BehaviorRegistry for this table * * @var \Cake\ORM\BehaviorRegistry */ protected $_behaviors; /** * The name of the class that represent a single row for this table * * @var string */ protected $_entityClass; /** * Registry key used to create this table object * * @var string */ protected $_registryAlias; /** * Initializes a new instance * * The $config array understands the following keys: * * - table: Name of the database table to represent * - alias: Alias to be assigned to this table (default to table name) * - connection: The connection instance to use * - entityClass: The fully namespaced class name of the entity class that will * represent rows in this table. * - schema: A \Cake\Database\Schema\TableSchema object or an array that can be * passed to it. * - eventManager: An instance of an event manager to use for internal events * - behaviors: A BehaviorRegistry. Generally not used outside of tests. * - associations: An AssociationCollection instance. * - validator: A Validator instance which is assigned as the "default" * validation set, or an associative array, where key is the name of the * validation set and value the Validator instance. * * @param array $config List of options for this table */ public function __construct(array $config = []) { if (!empty($config['registryAlias'])) { $this->setRegistryAlias($config['registryAlias']); } if (!empty($config['table'])) { $this->setTable($config['table']); } if (!empty($config['alias'])) { $this->setAlias($config['alias']); } if (!empty($config['connection'])) { $this->setConnection($config['connection']); } if (!empty($config['schema'])) { $this->setSchema($config['schema']); } if (!empty($config['entityClass'])) { $this->setEntityClass($config['entityClass']); } $eventManager = $behaviors = $associations = null; if (!empty($config['eventManager'])) { $eventManager = $config['eventManager']; } if (!empty($config['behaviors'])) { $behaviors = $config['behaviors']; } if (!empty($config['associations'])) { $associations = $config['associations']; } if (!empty($config['validator'])) { if (!is_array($config['validator'])) { $this->validator(static::DEFAULT_VALIDATOR, $config['validator']); } else { foreach ($config['validator'] as $name => $validator) { $this->validator($name, $validator); } } } $this->_eventManager = $eventManager ?: new EventManager(); $this->_behaviors = $behaviors ?: new BehaviorRegistry(); $this->_behaviors->setTable($this); $this->_associations = $associations ?: new AssociationCollection(); $this->initialize($config); $this->_eventManager->on($this); $this->dispatchEvent('Model.initialize'); } /** * Get the default connection name. * * This method is used to get the fallback connection name if an * instance is created through the TableRegistry without a connection. * * @return string * @see \Cake\ORM\TableRegistry::get() */ public static function defaultConnectionName() { return 'default'; } /** * Initialize a table instance. Called after the constructor. * * You can use this method to define associations, attach behaviors * define validation and do any other initialization logic you need. * * ``` * public function initialize(array $config) * { * $this->belongsTo('Users'); * $this->belongsToMany('Tagging.Tags'); * $this->setPrimaryKey('something_else'); * } * ``` * * @param array $config Configuration options passed to the constructor * @return void */ public function initialize(array $config) { } /** * Sets the database table name. * * @param string $table Table name. * @return $this */ public function setTable($table) { $this->_table = $table; return $this; } /** * Returns the database table name. * * @return string */ public function getTable() { if ($this->_table === null) { $table = namespaceSplit(get_class($this)); $table = substr(end($table), 0, -5); if (!$table) { $table = $this->getAlias(); } $this->_table = Inflector::underscore($table); } return $this->_table; } /** * Returns the database table name or sets a new one. * * @deprecated 3.4.0 Use setTable()/getTable() instead. * @param string|null $table the new table name * @return string */ public function table($table = null) { if ($table !== null) { $this->setTable($table); } return $this->getTable(); } /** * Sets the table alias. * * @param string $alias Table alias * @return $this */ public function setAlias($alias) { $this->_alias = $alias; return $this; } /** * Returns the table alias. * * @return string */ public function getAlias() { if ($this->_alias === null) { $alias = namespaceSplit(get_class($this)); $alias = substr(end($alias), 0, -5) ?: $this->_table; $this->_alias = $alias; } return $this->_alias; } /** * {@inheritDoc} * @deprecated 3.4.0 Use setAlias()/getAlias() instead. */ public function alias($alias = null) { if ($alias !== null) { $this->setAlias($alias); } return $this->getAlias(); } /** * Alias a field with the table's current alias. * * If field is already aliased it will result in no-op. * * @param string $field The field to alias. * @return string The field prefixed with the table alias. */ public function aliasField($field) { if (strpos($field, '.') !== false) { return $field; } return $this->getAlias() . '.' . $field; } /** * Sets the table registry key used to create this table instance. * * @param string $registryAlias The key used to access this object. * @return $this */ public function setRegistryAlias($registryAlias) { $this->_registryAlias = $registryAlias; return $this; } /** * Returns the table registry key used to create this table instance. * * @return string */ public function getRegistryAlias() { if ($this->_registryAlias === null) { $this->_registryAlias = $this->getAlias(); } return $this->_registryAlias; } /** * Returns the table registry key used to create this table instance or sets one. * * @deprecated 3.4.0 Use setRegistryAlias()/getRegistryAlias() instead. * @param string|null $registryAlias the key used to access this object * @return string */ public function registryAlias($registryAlias = null) { if ($registryAlias !== null) { $this->setRegistryAlias($registryAlias); } return $this->getRegistryAlias(); } /** * Sets the connection instance. * * @param \Cake\Datasource\ConnectionInterface $connection The connection instance * @return $this */ public function setConnection(ConnectionInterface $connection) { $this->_connection = $connection; return $this; } /** * Returns the connection instance. * * @return \Cake\Datasource\ConnectionInterface */ public function getConnection() { return $this->_connection; } /** * Returns the connection instance or sets a new one * * @deprecated 3.4.0 Use setConnection()/getConnection() instead. * @param \Cake\Datasource\ConnectionInterface|null $connection The new connection instance * @return \Cake\Datasource\ConnectionInterface */ public function connection(ConnectionInterface $connection = null) { if ($connection !== null) { $this->setConnection($connection); } return $this->getConnection(); } /** * Returns the schema table object describing this table's properties. * * @return \Cake\Database\Schema\TableSchema */ public function getSchema() { if ($this->_schema === null) { $this->_schema = $this->_initializeSchema( $this->getConnection() ->getSchemaCollection() ->describe($this->getTable()) ); } return $this->_schema; } /** * Sets the schema table object describing this table's properties. * * If an array is passed, a new TableSchema will be constructed * out of it and used as the schema for this table. * * @param array|\Cake\Database\Schema\TableSchema $schema Schema to be used for this table * @return $this */ public function setSchema($schema) { if (is_array($schema)) { $constraints = []; if (isset($schema['_constraints'])) { $constraints = $schema['_constraints']; unset($schema['_constraints']); } $schema = new TableSchema($this->getTable(), $schema); foreach ($constraints as $name => $value) { $schema->addConstraint($name, $value); } } $this->_schema = $schema; return $this; } /** * Returns the schema table object describing this table's properties. * * If a TableSchema is passed, it will be used for this table * instead of the default one. * * If an array is passed, a new TableSchema will be constructed * out of it and used as the schema for this table. * * @deprecated 3.4.0 Use setSchema()/getSchema() instead. * @param array|\Cake\Database\Schema\TableSchema|null $schema New schema to be used for this table * @return \Cake\Database\Schema\TableSchema */ public function schema($schema = null) { if ($schema !== null) { $this->setSchema($schema); } return $this->getSchema(); } /** * Override this function in order to alter the schema used by this table. * This function is only called after fetching the schema out of the database. * If you wish to provide your own schema to this table without touching the * database, you can override schema() or inject the definitions though that * method. * * ### Example: * * ``` * protected function _initializeSchema(\Cake\Database\Schema\TableSchema $schema) { * $schema->columnType('preferences', 'json'); * return $schema; * } * ``` * * @param \Cake\Database\Schema\TableSchema $schema The table definition fetched from database. * @return \Cake\Database\Schema\TableSchema the altered schema */ protected function _initializeSchema(TableSchema $schema) { return $schema; } /** * Test to see if a Table has a specific field/column. * * Delegates to the schema object and checks for column presence * using the Schema\Table instance. * * @param string $field The field to check for. * @return bool True if the field exists, false if it does not. */ public function hasField($field) { $schema = $this->getSchema(); return $schema->column($field) !== null; } /** * Sets the primary key field name. * * @param string|array $key Sets a new name to be used as primary key * @return $this */ public function setPrimaryKey($key) { $this->_primaryKey = $key; return $this; } /** * Returns the primary key field name. * * @return string|array */ public function getPrimaryKey() { if ($this->_primaryKey === null) { $key = (array)$this->getSchema()->primaryKey(); if (count($key) === 1) { $key = $key[0]; } $this->_primaryKey = $key; } return $this->_primaryKey; } /** * Returns the primary key field name or sets a new one * * @deprecated 3.4.0 Use setPrimaryKey()/getPrimaryKey() instead. * @param string|array|null $key Sets a new name to be used as primary key * @return string|array */ public function primaryKey($key = null) { if ($key !== null) { $this->setPrimaryKey($key); } return $this->getPrimaryKey(); } /** * Sets the display field. * * @param string $key Name to be used as display field. * @return $this */ public function setDisplayField($key) { $this->_displayField = $key; return $this; } /** * Returns the display field. * * @return string */ public function getDisplayField() { if ($this->_displayField === null) { $schema = $this->getSchema(); $primary = (array)$this->getPrimaryKey(); $this->_displayField = array_shift($primary); if ($schema->column('title')) { $this->_displayField = 'title'; } if ($schema->column('name')) { $this->_displayField = 'name'; } } return $this->_displayField; } /** * Returns the display field or sets a new one * * @deprecated 3.4.0 Use setDisplayField()/getDisplayField() instead. * @param string|null $key sets a new name to be used as display field * @return string */ public function displayField($key = null) { if ($key !== null) { return $this->setDisplayField($key); } return $this->getDisplayField(); } /** * Returns the class used to hydrate rows for this table. * * @return string */ public function getEntityClass() { if (!$this->_entityClass) { $default = '\Cake\ORM\Entity'; $self = get_called_class(); $parts = explode('\\', $self); if ($self === __CLASS__ || count($parts) < 3) { return $this->_entityClass = $default; } $alias = Inflector::singularize(substr(array_pop($parts), 0, -5)); $name = implode('\\', array_slice($parts, 0, -1)) . '\Entity\\' . $alias; if (!class_exists($name)) { return $this->_entityClass = $default; } $class = App::className($name, 'Model/Entity'); if (!$class) { throw new MissingEntityException([$name]); } $this->_entityClass = $class; } return $this->_entityClass; } /** * Sets the class used to hydrate rows for this table. * * @param string $name The name of the class to use * @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found * @return $this */ public function setEntityClass($name) { $class = App::className($name, 'Model/Entity'); if (!$class) { throw new MissingEntityException([$name]); } $this->_entityClass = $class; return $this; } /** * Returns the class used to hydrate rows for this table or sets * a new one * * @deprecated 3.4.0 Use setEntityClass()/getEntityClass() instead. * @param string|null $name The name of the class to use * @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found * @return string */ public function entityClass($name = null) { if ($name !== null) { $this->setEntityClass($name); } return $this->getEntityClass(); } /** * Add a behavior. * * Adds a behavior to this table's behavior collection. Behaviors * provide an easy way to create horizontally re-usable features * that can provide trait like functionality, and allow for events * to be listened to. * * Example: * * Load a behavior, with some settings. * * ``` * $this->addBehavior('Tree', ['parent' => 'parentId']); * ``` * * Behaviors are generally loaded during Table::initialize(). * * @param string $name The name of the behavior. Can be a short class reference. * @param array $options The options for the behavior to use. * @return void * @throws \RuntimeException If a behavior is being reloaded. * @see \Cake\ORM\Behavior */ public function addBehavior($name, array $options = []) { $this->_behaviors->load($name, $options); } /** * Removes a behavior from this table's behavior registry. * * Example: * * Remove a behavior from this table. * * ``` * $this->removeBehavior('Tree'); * ``` * * @param string $name The alias that the behavior was added with. * @return void * @see \Cake\ORM\Behavior */ public function removeBehavior($name) { $this->_behaviors->unload($name); } /** * Returns the behavior registry for this table. * * @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance. */ public function behaviors() { return $this->_behaviors; } /** * Check if a behavior with the given alias has been loaded. * * @param string $name The behavior alias to check. * @return bool Whether or not the behavior exists. */ public function hasBehavior($name) { return $this->_behaviors->has($name); } /** * Returns an association object configured for the specified alias if any * * @param string $name the alias used for the association. * @return \Cake\ORM\Association|null Either the association or null. */ public function association($name) { return $this->_associations->get($name); } /** * Get the associations collection for this table. * * @return \Cake\ORM\AssociationCollection The collection of association objects. */ public function associations() { return $this->_associations; } /** * Setup multiple associations. * * It takes an array containing set of table names indexed by association type * as argument: * * ``` * $this->Posts->addAssociations([ * 'belongsTo' => [ * 'Users' => ['className' => 'App\Model\Table\UsersTable'] * ], * 'hasMany' => ['Comments'], * 'belongsToMany' => ['Tags'] * ]); * ``` * * Each association type accepts multiple associations where the keys * are the aliases, and the values are association config data. If numeric * keys are used the values will be treated as association aliases. * * @param array $params Set of associations to bind (indexed by association type) * @return void * @see \Cake\ORM\Table::belongsTo() * @see \Cake\ORM\Table::hasOne() * @see \Cake\ORM\Table::hasMany() * @see \Cake\ORM\Table::belongsToMany() */ public function addAssociations(array $params) { foreach ($params as $assocType => $tables) { foreach ($tables as $associated => $options) { if (is_numeric($associated)) { $associated = $options; $options = []; } $this->{$assocType}($associated, $options); } } } /** * Creates a new BelongsTo association between this table and a target * table. A "belongs to" association is a N-1 relationship where this table * is the N side, and where there is a single associated record in the target * table for each one in this table. * * Target table can be inferred by its name, which is provided in the * first argument, or you can either pass the to be instantiated or * an instance of it directly. * * The options array accept the following keys: * * - className: The class name of the target table object * - targetTable: An instance of a table object to be used as the target table * - foreignKey: The name of the field to use as foreign key, if false none * will be used * - conditions: array with a list of conditions to filter the join with * - joinType: The type of join to be used (e.g. INNER) * - strategy: The loading strategy to use. 'join' and 'select' are supported. * - finder: The finder method to use when loading records from this association. * Defaults to 'all'. When the strategy is 'join', only the fields, containments, * and where conditions will be used from the finder. * * This method will return the association object that was built. * * @param string $associated the alias for the target table. This is used to * uniquely identify the association * @param array $options list of options to configure the association definition * @return \Cake\ORM\Association\BelongsTo */ public function belongsTo($associated, array $options = []) { $options += ['sourceTable' => $this]; $association = new BelongsTo($associated, $options); return $this->_associations->add($association->getName(), $association); } /** * Creates a new HasOne association between this table and a target * table. A "has one" association is a 1-1 relationship. * * Target table can be inferred by its name, which is provided in the * first argument, or you can either pass the class name to be instantiated or * an instance of it directly. * * The options array accept the following keys: * * - className: The class name of the target table object * - targetTable: An instance of a table object to be used as the target table * - foreignKey: The name of the field to use as foreign key, if false none * will be used * - dependent: Set to true if you want CakePHP to cascade deletes to the * associated table when an entity is removed on this table. The delete operation * on the associated table will not cascade further. To get recursive cascades enable * `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove * associated data, or when you are using database constraints. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on * cascaded deletes. If false the ORM will use deleteAll() to remove data. * When true records will be loaded and then deleted. * - conditions: array with a list of conditions to filter the join with * - joinType: The type of join to be used (e.g. LEFT) * - strategy: The loading strategy to use. 'join' and 'select' are supported. * - finder: The finder method to use when loading records from this association. * Defaults to 'all'. When the strategy is 'join', only the fields, containments, * and where conditions will be used from the finder. * * This method will return the association object that was built. * * @param string $associated the alias for the target table. This is used to * uniquely identify the association * @param array $options list of options to configure the association definition * @return \Cake\ORM\Association\HasOne */ public function hasOne($associated, array $options = []) { $options += ['sourceTable' => $this]; $association = new HasOne($associated, $options); return $this->_associations->add($association->getName(), $association); } /** * Creates a new HasMany association between this table and a target * table. A "has many" association is a 1-N relationship. * * Target table can be inferred by its name, which is provided in the * first argument, or you can either pass the class name to be instantiated or * an instance of it directly. * * The options array accept the following keys: * * - className: The class name of the target table object * - targetTable: An instance of a table object to be used as the target table * - foreignKey: The name of the field to use as foreign key, if false none * will be used * - dependent: Set to true if you want CakePHP to cascade deletes to the * associated table when an entity is removed on this table. The delete operation * on the associated table will not cascade further. To get recursive cascades enable * `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove * associated data, or when you are using database constraints. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on * cascaded deletes. If false the ORM will use deleteAll() to remove data. * When true records will be loaded and then deleted. * - conditions: array with a list of conditions to filter the join with * - sort: The order in which results for this association should be returned * - saveStrategy: Either 'append' or 'replace'. When 'append' the current records * are appended to any records in the database. When 'replace' associated records * not in the current set will be removed. If the foreign key is a null able column * or if `dependent` is true records will be orphaned. * - strategy: The strategy to be used for selecting results Either 'select' * or 'subquery'. If subquery is selected the query used to return results * in the source table will be used as conditions for getting rows in the * target table. * - finder: The finder method to use when loading records from this association. * Defaults to 'all'. * * This method will return the association object that was built. * * @param string $associated the alias for the target table. This is used to * uniquely identify the association * @param array $options list of options to configure the association definition * @return \Cake\ORM\Association\HasMany */ public function hasMany($associated, array $options = []) { $options += ['sourceTable' => $this]; $association = new HasMany($associated, $options); return $this->_associations->add($association->getName(), $association); } /** * Creates a new BelongsToMany association between this table and a target * table. A "belongs to many" association is a M-N relationship. * * Target table can be inferred by its name, which is provided in the * first argument, or you can either pass the class name to be instantiated or * an instance of it directly. * * The options array accept the following keys: * * - className: The class name of the target table object. * - targetTable: An instance of a table object to be used as the target table. * - foreignKey: The name of the field to use as foreign key. * - targetForeignKey: The name of the field to use as the target foreign key. * - joinTable: The name of the table representing the link between the two * - through: If you choose to use an already instantiated link table, set this * key to a configured Table instance containing associations to both the source * and target tables in this association. * - dependent: Set to false, if you do not want junction table records removed * when an owning record is removed. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on * cascaded deletes. If false the ORM will use deleteAll() to remove data. * When true join/junction table records will be loaded and then deleted. * - conditions: array with a list of conditions to filter the join with. * - sort: The order in which results for this association should be returned. * - strategy: The strategy to be used for selecting results Either 'select' * or 'subquery'. If subquery is selected the query used to return results * in the source table will be used as conditions for getting rows in the * target table. * - saveStrategy: Either 'append' or 'replace'. Indicates the mode to be used * for saving associated entities. The former will only create new links * between both side of the relation and the latter will do a wipe and * replace to create the links between the passed entities when saving. * - strategy: The loading strategy to use. 'select' and 'subquery' are supported. * - finder: The finder method to use when loading records from this association. * Defaults to 'all'. * * This method will return the association object that was built. * * @param string $associated the alias for the target table. This is used to * uniquely identify the association * @param array $options list of options to configure the association definition * @return \Cake\ORM\Association\BelongsToMany */ public function belongsToMany($associated, array $options = []) { $options += ['sourceTable' => $this]; $association = new BelongsToMany($associated, $options); return $this->_associations->add($association->getName(), $association); } /** * {@inheritDoc} * * ### Model.beforeFind event * * Each find() will trigger a `Model.beforeFind` event for all attached * listeners. Any listener can set a valid result set using $query * * By default, `$options` will recognize the following keys: * * - fields * - conditions * - order * - limit * - offset * - page * - group * - having * - contain * - join * * ### Usage * * Using the options array: * * ``` * $query = $articles->find('all', [ * 'conditions' => ['published' => 1], * 'limit' => 10, * 'contain' => ['Users', 'Comments'] * ]); * ``` * * Using the builder interface: * * ``` * $query = $articles->find() * ->where(['published' => 1]) * ->limit(10) * ->contain(['Users', 'Comments']); * ``` * * ### Calling finders * * The find() method is the entry point for custom finder methods. * You can invoke a finder by specifying the type: * * ``` * $query = $articles->find('published'); * ``` * * Would invoke the `findPublished` method. * * @return \Cake\ORM\Query The query builder */ public function find($type = 'all', $options = []) { $query = $this->query(); $query->select(); return $this->callFinder($type, $query, $options); } /** * Returns the query as passed. * * By default findAll() applies no conditions, you * can override this method in subclasses to modify how `find('all')` works. * * @param \Cake\ORM\Query $query The query to find with * @param array $options The options to use for the find * @return \Cake\ORM\Query The query builder */ public function findAll(Query $query, array $options) { return $query; } /** * Sets up a query object so results appear as an indexed array, useful for any * place where you would want a list such as for populating input select boxes. * * When calling this finder, the fields passed are used to determine what should * be used as the array key, value and optionally what to group the results by. * By default the primary key for the model is used for the key, and the display * field as value. * * The results of this finder will be in the following form: * * ``` * [ * 1 => 'value for id 1', * 2 => 'value for id 2', * 4 => 'value for id 4' * ] * ``` * * You can specify which property will be used as the key and which as value * by using the `$options` array, when not specified, it will use the results * of calling `primaryKey` and `displayField` respectively in this table: * * ``` * $table->find('list', [ * 'keyField' => 'name', * 'valueField' => 'age' * ]); * ``` * * Results can be put together in bigger groups when they share a property, you * can customize the property to use for grouping by setting `groupField`: * * ``` * $table->find('list', [ * 'groupField' => 'category_id', * ]); * ``` * * When using a `groupField` results will be returned in this format: * * ``` * [ * 'group_1' => [ * 1 => 'value for id 1', * 2 => 'value for id 2', * ] * 'group_2' => [ * 4 => 'value for id 4' * ] * ] * ``` * * @param \Cake\ORM\Query $query The query to find with * @param array $options The options for the find * @return \Cake\ORM\Query The query builder */ public function findList(Query $query, array $options) { $options += [ 'keyField' => $this->getPrimaryKey(), 'valueField' => $this->getDisplayField(), 'groupField' => null ]; if (isset($options['idField'])) { $options['keyField'] = $options['idField']; unset($options['idField']); trigger_error('Option "idField" is deprecated, use "keyField" instead.', E_USER_DEPRECATED); } if (!$query->clause('select') && !is_object($options['keyField']) && !is_object($options['valueField']) && !is_object($options['groupField']) ) { $fields = array_merge( (array)$options['keyField'], (array)$options['valueField'], (array)$options['groupField'] ); $columns = $this->getSchema()->columns(); if (count($fields) === count(array_intersect($fields, $columns))) { $query->select($fields); } } $options = $this->_setFieldMatchers( $options, ['keyField', 'valueField', 'groupField'] ); return $query->formatResults(function ($results) use ($options) { return $results->combine( $options['keyField'], $options['valueField'], $options['groupField'] ); }); } /** * Results for this finder will be a nested array, and is appropriate if you want * to use the parent_id field of your model data to build nested results. * * Values belonging to a parent row based on their parent_id value will be * recursively nested inside the parent row values using the `children` property * * You can customize what fields are used for nesting results, by default the * primary key and the `parent_id` fields are used. If you wish to change * these defaults you need to provide the keys `keyField`, `parentField` or `nestingKey` in * `$options`: * * ``` * $table->find('threaded', [ * 'keyField' => 'id', * 'parentField' => 'ancestor_id' * 'nestingKey' => 'children' * ]); * ``` * * @param \Cake\ORM\Query $query The query to find with * @param array $options The options to find with * @return \Cake\ORM\Query The query builder */ public function findThreaded(Query $query, array $options) { $options += [ 'keyField' => $this->getPrimaryKey(), 'parentField' => 'parent_id', 'nestingKey' => 'children' ]; if (isset($options['idField'])) { $options['keyField'] = $options['idField']; unset($options['idField']); trigger_error('Option "idField" is deprecated, use "keyField" instead.', E_USER_DEPRECATED); } $options = $this->_setFieldMatchers($options, ['keyField', 'parentField']); return $query->formatResults(function ($results) use ($options) { return $results->nest($options['keyField'], $options['parentField'], $options['nestingKey']); }); } /** * Out of an options array, check if the keys described in `$keys` are arrays * and change the values for closures that will concatenate the each of the * properties in the value array when passed a row. * * This is an auxiliary function used for result formatters that can accept * composite keys when comparing values. * * @param array $options the original options passed to a finder * @param array $keys the keys to check in $options to build matchers from * the associated value * @return array */ protected function _setFieldMatchers($options, $keys) { foreach ($keys as $field) { if (!is_array($options[$field])) { continue; } if (count($options[$field]) === 1) { $options[$field] = current($options[$field]); continue; } $fields = $options[$field]; $options[$field] = function ($row) use ($fields) { $matches = []; foreach ($fields as $field) { $matches[] = $row[$field]; } return implode(';', $matches); }; } return $options; } /** * {@inheritDoc} * * ### Usage * * Get an article and some relationships: * * ``` * $article = $articles->get(1, ['contain' => ['Users', 'Comments']]); * ``` * * @throws \Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an * incorrect number of elements. */ public function get($primaryKey, $options = []) { $key = (array)$this->getPrimaryKey(); $alias = $this->getAlias(); foreach ($key as $index => $keyname) { $key[$index] = $alias . '.' . $keyname; } $primaryKey = (array)$primaryKey; if (count($key) !== count($primaryKey)) { $primaryKey = $primaryKey ?: [null]; $primaryKey = array_map(function ($key) { return var_export($key, true); }, $primaryKey); throw new InvalidPrimaryKeyException(sprintf( 'Record not found in table "%s" with primary key [%s]', $this->getTable(), implode($primaryKey, ', ') )); } $conditions = array_combine($key, $primaryKey); $cacheConfig = isset($options['cache']) ? $options['cache'] : false; $cacheKey = isset($options['key']) ? $options['key'] : false; $finder = isset($options['finder']) ? $options['finder'] : 'all'; unset($options['key'], $options['cache'], $options['finder']); $query = $this->find($finder, $options)->where($conditions); if ($cacheConfig) { if (!$cacheKey) { $cacheKey = sprintf( "get:%s.%s%s", $this->getConnection()->configName(), $this->getTable(), json_encode($primaryKey) ); } $query->cache($cacheKey, $cacheConfig); } return $query->firstOrFail(); } /** * Handles the logic executing of a worker inside a transaction. * * @param callable $worker The worker that will run inside the transaction. * @param bool $atomic Whether to execute the worker inside a database transaction. * @return mixed */ protected function _executeTransaction(callable $worker, $atomic = true) { if ($atomic) { return $this->getConnection()->transactional(function () use ($worker) { return $worker(); }); } return $worker(); } /** * Checks if the caller would have executed a commit on a transaction. * * @param bool $atomic True if an atomic transaction was used. * @param bool $primary True if a primary was used. * @return bool Returns true if a transaction was committed. */ protected function _transactionCommitted($atomic, $primary) { return !$this->getConnection()->inTransaction() && ($atomic || (!$atomic && $primary)); } /** * Finds an existing record or creates a new one. * * A find() will be done to locate an existing record using the attributes * defined in $search. If records matches the conditions, the first record * will be returned. * * If no record can be found, a new entity will be created * with the $search properties. If a callback is provided, it will be * called allowing you to define additional default values. The new * entity will be saved and returned. * * If your find conditions require custom order, associations or conditions, then the $search * parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed * as the $search parameter. Allowing you to customize the find results. * * ### Options * * The options array is passed to the save method with exception to the following keys: * * - atomic: Whether to execute the methods for find, save and callbacks inside a database * transaction (default: true) * - defaults: Whether to use the search criteria as default values for the new entity (default: true) * * @param array|\Cake\ORM\Query $search The criteria to find existing * records by. Note that when you pass a query object you'll have to use * the 2nd arg of the method to modify the entity data before saving. * @param callable|null $callback A callback that will be invoked for newly * created entities. This callback will be called *before* the entity * is persisted. * @param array $options The options to use when saving. * @return \Cake\Datasource\EntityInterface An entity. */ public function findOrCreate($search, callable $callback = null, $options = []) { $options += [ 'atomic' => true, 'defaults' => true ]; return $this->_executeTransaction(function () use ($search, $callback, $options) { return $this->_processFindOrCreate($search, $callback, $options); }, $options['atomic']); } /** * Performs the actual find and/or create of an entity based on the passed options. * * @param array|callable $search The criteria to find an existing record by, or a callable tha will * customize the find query. * @param callable|null $callback A callback that will be invoked for newly * created entities. This callback will be called *before* the entity * is persisted. * @param array $options The options to use when saving. * @return \Cake\Datasource\EntityInterface An entity. */ protected function _processFindOrCreate($search, callable $callback = null, $options = []) { if (is_callable($search)) { $query = $this->find(); $search($query); } elseif (is_array($search)) { $query = $this->find()->where($search); } elseif ($search instanceof Query) { $query = $search; } else { throw new InvalidArgumentException('Search criteria must be an array, callable or Query'); } $row = $query->first(); if ($row !== null) { return $row; } $entity = $this->newEntity(); if ($options['defaults'] && is_array($search)) { $entity->set($search, ['guard' => false]); } if ($callback !== null) { $entity = $callback($entity) ?: $entity; } unset($options['defaults']); return $this->save($entity, $options) ?: $entity; } /** * Gets the query object for findOrCreate(). * * @param array|\Cake\ORM\Query|string $search The criteria to find existing records by. * @return \Cake\ORM\Query */ protected function _getFindOrCreateQuery($search) { if ($search instanceof Query) { return $search; } return $this->find()->where($search); } /** * {@inheritDoc} */ public function query() { return new Query($this->getConnection(), $this); } /** * {@inheritDoc} */ public function updateAll($fields, $conditions) { $query = $this->query(); $query->update() ->set($fields) ->where($conditions); $statement = $query->execute(); $statement->closeCursor(); return $statement->rowCount(); } /** * {@inheritDoc} */ public function deleteAll($conditions) { $query = $this->query() ->delete() ->where($conditions); $statement = $query->execute(); $statement->closeCursor(); return $statement->rowCount(); } /** * {@inheritDoc} */ public function exists($conditions) { return (bool)count( $this->find('all') ->select(['existing' => 1]) ->where($conditions) ->limit(1) ->enableHydration(false) ->toArray() ); } /** * {@inheritDoc} * * ### Options * * The options array accepts the following keys: * * - atomic: Whether to execute the save and callbacks inside a database * transaction (default: true) * - checkRules: Whether or not to check the rules on entity before saving, if the checking * fails, it will abort the save operation. (default:true) * - associated: If `true` it will save 1st level associated entities as they are found * in the passed `$entity` whenever the property defined for the association * is marked as dirty. If an array, it will be interpreted as the list of associations * to be saved. It is possible to provide different options for saving on associated * table objects using this key by making the custom options the array value. * If `false` no associated records will be saved. (default: `true`) * - checkExisting: Whether or not to check if the entity already exists, assuming that the * entity is marked as not new, and the primary key has been set. * * ### Events * * When saving, this method will trigger four events: * * - Model.beforeRules: Will be triggered right before any rule checking is done * for the passed entity if the `checkRules` key in $options is not set to false. * Listeners will receive as arguments the entity, options array and the operation type. * If the event is stopped the rules check result will be set to the result of the event itself. * - Model.afterRules: Will be triggered right after the `checkRules()` method is * called for the entity. Listeners will receive as arguments the entity, * options array, the result of checking the rules and the operation type. * If the event is stopped the checking result will be set to the result of * the event itself. * - Model.beforeSave: Will be triggered just before the list of fields to be * persisted is calculated. It receives both the entity and the options as * arguments. The options array is passed as an ArrayObject, so any changes in * it will be reflected in every listener and remembered at the end of the event * so it can be used for the rest of the save operation. Returning false in any * of the listeners will abort the saving process. If the event is stopped * using the event API, the event object's `result` property will be returned. * This can be useful when having your own saving strategy implemented inside a * listener. * - Model.afterSave: Will be triggered after a successful insert or save, * listeners will receive the entity and the options array as arguments. The type * of operation performed (insert or update) can be determined by checking the * entity's method `isNew`, true meaning an insert and false an update. * - Model.afterSaveCommit: Will be triggered after the transaction is commited * for atomic save, listeners will receive the entity and the options array * as arguments. * * This method will determine whether the passed entity needs to be * inserted or updated in the database. It does that by checking the `isNew` * method on the entity. If the entity to be saved returns a non-empty value from * its `errors()` method, it will not be saved. * * ### Saving on associated tables * * This method will by default persist entities belonging to associated tables, * whenever a dirty property matching the name of the property name set for an * association in this table. It is possible to control what associations will * be saved and to pass additional option for saving them. * * ``` * // Only save the comments association * $articles->save($entity, ['associated' => ['Comments']); * * // Save the company, the employees and related addresses for each of them. * // For employees do not check the entity rules * $companies->save($entity, [ * 'associated' => [ * 'Employees' => [ * 'associated' => ['Addresses'], * 'checkRules' => false * ] * ] * ]); * * // Save no associations * $articles->save($entity, ['associated' => false]); * ``` * * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction * is aborted in the afterSave event. */ public function save(EntityInterface $entity, $options = []) { if ($options instanceof SaveOptionsBuilder) { $options = $options->toArray(); } $options = new ArrayObject($options + [ 'atomic' => true, 'associated' => true, 'checkRules' => true, 'checkExisting' => true, '_primary' => true ]); if ($entity->errors()) { return false; } if ($entity->isNew() === false && !$entity->dirty()) { return $entity; } $success = $this->_executeTransaction(function () use ($entity, $options) { return $this->_processSave($entity, $options); }, $options['atomic']); if ($success) { if ($this->_transactionCommitted($options['atomic'], $options['_primary'])) { $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options')); } if ($options['atomic'] || $options['_primary']) { $entity->clean(); $entity->isNew(false); $entity->source($this->getRegistryAlias()); } } return $success; } /** * Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, * the entity contains errors or the save was aborted by a callback. * * @param \Cake\Datasource\EntityInterface $entity the entity to be saved * @param array|\ArrayAccess $options The options to use when saving. * @return \Cake\Datasource\EntityInterface * @throws \Cake\ORM\Exception\PersistenceFailedException When the entity couldn't be saved * @see \Cake\ORM\Table::save() */ public function saveOrFail(EntityInterface $entity, $options = []) { $saved = $this->save($entity, $options); if ($saved === false) { throw new PersistenceFailedException($entity, ['save']); } return $saved; } /** * Performs the actual saving of an entity based on the passed options. * * @param \Cake\Datasource\EntityInterface $entity the entity to be saved * @param \ArrayObject $options the options to use for the save operation * @return \Cake\Datasource\EntityInterface|bool * @throws \RuntimeException When an entity is missing some of the primary keys. * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction * is aborted in the afterSave event. */ protected function _processSave($entity, $options) { $primaryColumns = (array)$this->getPrimaryKey(); if ($options['checkExisting'] && $primaryColumns && $entity->isNew() && $entity->has($primaryColumns)) { $alias = $this->getAlias(); $conditions = []; foreach ($entity->extract($primaryColumns) as $k => $v) { $conditions["$alias.$k"] = $v; } $entity->isNew(!$this->exists($conditions)); } $mode = $entity->isNew() ? RulesChecker::CREATE : RulesChecker::UPDATE; if ($options['checkRules'] && !$this->checkRules($entity, $mode, $options)) { return false; } $options['associated'] = $this->_associations->normalizeKeys($options['associated']); $event = $this->dispatchEvent('Model.beforeSave', compact('entity', 'options')); if ($event->isStopped()) { return $event->getResult(); } $saved = $this->_associations->saveParents( $this, $entity, $options['associated'], ['_primary' => false] + $options->getArrayCopy() ); if (!$saved && $options['atomic']) { return false; } $data = $entity->extract($this->getSchema()->columns(), true); $isNew = $entity->isNew(); if ($isNew) { $success = $this->_insert($entity, $data); } else { $success = $this->_update($entity, $data); } if ($success) { $success = $this->_onSaveSuccess($entity, $options); } if (!$success && $isNew) { $entity->unsetProperty($this->getPrimaryKey()); $entity->isNew(true); } return $success ? $entity : false; } /** * Handles the saving of children associations and executing the afterSave logic * once the entity for this table has been saved successfully. * * @param \Cake\Datasource\EntityInterface $entity the entity to be saved * @param \ArrayObject $options the options to use for the save operation * @return bool True on success * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction * is aborted in the afterSave event. */ protected function _onSaveSuccess($entity, $options) { $success = $this->_associations->saveChildren( $this, $entity, $options['associated'], ['_primary' => false] + $options->getArrayCopy() ); if (!$success && $options['atomic']) { return false; } $this->dispatchEvent('Model.afterSave', compact('entity', 'options')); if ($options['atomic'] && !$this->getConnection()->inTransaction()) { throw new RolledbackTransactionException(['table' => get_class($this)]); } if (!$options['atomic'] && !$options['_primary']) { $entity->clean(); $entity->isNew(false); $entity->source($this->getRegistryAlias()); } return true; } /** * Auxiliary function to handle the insert of an entity's data in the table * * @param \Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted * @param array $data The actual data that needs to be saved * @return \Cake\Datasource\EntityInterface|bool * @throws \RuntimeException if not all the primary keys where supplied or could * be generated when the table has composite primary keys. Or when the table has no primary key. */ protected function _insert($entity, $data) { $primary = (array)$this->getPrimaryKey(); if (empty($primary)) { $msg = sprintf( 'Cannot insert row in "%s" table, it has no primary key.', $this->getTable() ); throw new RuntimeException($msg); } $keys = array_fill(0, count($primary), null); $id = (array)$this->_newId($primary) + $keys; // Generate primary keys preferring values in $data. $primary = array_combine($primary, $id); $primary = array_intersect_key($data, $primary) + $primary; $filteredKeys = array_filter($primary, 'strlen'); $data = $data + $filteredKeys; if (count($primary) > 1) { $schema = $this->getSchema(); foreach ($primary as $k => $v) { if (!isset($data[$k]) && empty($schema->column($k)['autoIncrement'])) { $msg = 'Cannot insert row, some of the primary key values are missing. '; $msg .= sprintf( 'Got (%s), expecting (%s)', implode(', ', $filteredKeys + $entity->extract(array_keys($primary))), implode(', ', array_keys($primary)) ); throw new RuntimeException($msg); } } } $success = false; if (empty($data)) { return $success; } $statement = $this->query()->insert(array_keys($data)) ->values($data) ->execute(); if ($statement->rowCount() !== 0) { $success = $entity; $entity->set($filteredKeys, ['guard' => false]); $schema = $this->getSchema(); $driver = $this->getConnection()->driver(); foreach ($primary as $key => $v) { if (!isset($data[$key])) { $id = $statement->lastInsertId($this->getTable(), $key); $type = $schema->columnType($key); $entity->set($key, Type::build($type)->toPHP($id, $driver)); break; } } } $statement->closeCursor(); return $success; } /** * Generate a primary key value for a new record. * * By default, this uses the type system to generate a new primary key * value if possible. You can override this method if you have specific requirements * for id generation. * * @param array $primary The primary key columns to get a new ID for. * @return mixed Either null or the new primary key value. */ protected function _newId($primary) { if (!$primary || count((array)$primary) > 1) { return null; } $typeName = $this->getSchema()->columnType($primary[0]); $type = Type::build($typeName); return $type->newId(); } /** * Auxiliary function to handle the update of an entity's data in the table * * @param \Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted * @param array $data The actual data that needs to be saved * @return \Cake\Datasource\EntityInterface|bool * @throws \InvalidArgumentException When primary key data is missing. */ protected function _update($entity, $data) { $primaryColumns = (array)$this->getPrimaryKey(); $primaryKey = $entity->extract($primaryColumns); $data = array_diff_key($data, $primaryKey); if (empty($data)) { return $entity; } if (!$entity->has($primaryColumns)) { $message = 'All primary key value(s) are needed for updating, '; $message .= get_class($entity) . ' is missing ' . implode(', ', $primaryColumns); throw new InvalidArgumentException($message); } $query = $this->query(); $statement = $query->update() ->set($data) ->where($primaryKey) ->execute(); $success = false; if ($statement->errorCode() === '00000') { $success = $entity; } $statement->closeCursor(); return $success; } /** * Persists multiple entities of a table. * * The records will be saved in a transaction which will be rolled back if * any one of the records fails to save due to failed validation or database * error. * * @param array|\Cake\ORM\ResultSet $entities Entities to save. * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity. * @return bool|array|\Cake\ORM\ResultSet False on failure, entities list on success. */ public function saveMany($entities, $options = []) { $isNew = []; $return = $this->getConnection()->transactional( function () use ($entities, $options, &$isNew) { foreach ($entities as $key => $entity) { $isNew[$key] = $entity->isNew(); if ($this->save($entity, $options) === false) { return false; } } } ); if ($return === false) { foreach ($entities as $key => $entity) { if (isset($isNew[$key]) && $isNew[$key]) { $entity->unsetProperty($this->getPrimaryKey()); $entity->isNew(true); } } return false; } return $entities; } /** * {@inheritDoc} * * For HasMany and HasOne associations records will be removed based on * the dependent option. Join table records in BelongsToMany associations * will always be removed. You can use the `cascadeCallbacks` option * when defining associations to change how associated data is deleted. * * ### Options * * - `atomic` Defaults to true. When true the deletion happens within a transaction. * - `checkRules` Defaults to true. Check deletion rules before deleting the record. * * ### Events * * - `Model.beforeDelete` Fired before the delete occurs. If stopped the delete * will be aborted. Receives the event, entity, and options. * - `Model.afterDelete` Fired after the delete has been successful. Receives * the event, entity, and options. * - `Model.afterDeleteCommit` Fired after the transaction is committed for * an atomic delete. Receives the event, entity, and options. * * The options argument will be converted into an \ArrayObject instance * for the duration of the callbacks, this allows listeners to modify * the options used in the delete operation. * */ public function delete(EntityInterface $entity, $options = []) { $options = new ArrayObject($options + [ 'atomic' => true, 'checkRules' => true, '_primary' => true, ]); $success = $this->_executeTransaction(function () use ($entity, $options) { return $this->_processDelete($entity, $options); }, $options['atomic']); if ($success && $this->_transactionCommitted($options['atomic'], $options['_primary'])) { $this->dispatchEvent('Model.afterDeleteCommit', [ 'entity' => $entity, 'options' => $options ]); } return $success; } /** * Try to delete an entity or throw a PersistenceFailedException if the entity is new, * has no primary key value, application rules checks failed or the delete was aborted by a callback. * * @param \Cake\Datasource\EntityInterface $entity The entity to remove. * @param array|\ArrayAccess $options The options for the delete. * @return bool success * @throws \Cake\ORM\Exception\PersistenceFailedException * @see \Cake\ORM\Table::delete() */ public function deleteOrFail(EntityInterface $entity, $options = []) { $deleted = $this->delete($entity, $options); if ($deleted === false) { throw new PersistenceFailedException($entity, ['delete']); } return $deleted; } /** * Perform the delete operation. * * Will delete the entity provided. Will remove rows from any * dependent associations, and clear out join tables for BelongsToMany associations. * * @param \Cake\Datasource\EntityInterface $entity The entity to delete. * @param \ArrayObject $options The options for the delete. * @throws \InvalidArgumentException if there are no primary key values of the * passed entity * @return bool success */ protected function _processDelete($entity, $options) { if ($entity->isNew()) { return false; } $primaryKey = (array)$this->getPrimaryKey(); if (!$entity->has($primaryKey)) { $msg = 'Deleting requires all primary key values.'; throw new InvalidArgumentException($msg); } if ($options['checkRules'] && !$this->checkRules($entity, RulesChecker::DELETE, $options)) { return false; } $event = $this->dispatchEvent('Model.beforeDelete', [ 'entity' => $entity, 'options' => $options ]); if ($event->isStopped()) { return $event->getResult(); } $this->_associations->cascadeDelete( $entity, ['_primary' => false] + $options->getArrayCopy() ); $query = $this->query(); $conditions = (array)$entity->extract($primaryKey); $statement = $query->delete() ->where($conditions) ->execute(); $success = $statement->rowCount() > 0; if (!$success) { return $success; } $this->dispatchEvent('Model.afterDelete', [ 'entity' => $entity, 'options' => $options ]); return $success; } /** * Returns true if the finder exists for the table * * @param string $type name of finder to check * * @return bool */ public function hasFinder($type) { $finder = 'find' . $type; return method_exists($this, $finder) || ($this->_behaviors && $this->_behaviors->hasFinder($type)); } /** * Calls a finder method directly and applies it to the passed query, * if no query is passed a new one will be created and returned * * @param string $type name of the finder to be called * @param \Cake\ORM\Query $query The query object to apply the finder options to * @param array $options List of options to pass to the finder * @return \Cake\ORM\Query * @throws \BadMethodCallException */ public function callFinder($type, Query $query, array $options = []) { $query->applyOptions($options); $options = $query->getOptions(); $finder = 'find' . $type; if (method_exists($this, $finder)) { return $this->{$finder}($query, $options); } if ($this->_behaviors && $this->_behaviors->hasFinder($type)) { return $this->_behaviors->callFinder($type, [$query, $options]); } throw new BadMethodCallException( sprintf('Unknown finder method "%s"', $type) ); } /** * Provides the dynamic findBy and findByAll methods. * * @param string $method The method name that was fired. * @param array $args List of arguments passed to the function. * @return mixed * @throws \BadMethodCallException when there are missing arguments, or when * and & or are combined. */ protected function _dynamicFinder($method, $args) { $method = Inflector::underscore($method); preg_match('/^find_([\w]+)_by_/', $method, $matches); if (empty($matches)) { // find_by_ is 8 characters. $fields = substr($method, 8); $findType = 'all'; } else { $fields = substr($method, strlen($matches[0])); $findType = Inflector::variable($matches[1]); } $hasOr = strpos($fields, '_or_'); $hasAnd = strpos($fields, '_and_'); $makeConditions = function ($fields, $args) { $conditions = []; if (count($args) < count($fields)) { throw new BadMethodCallException(sprintf( 'Not enough arguments for magic finder. Got %s required %s', count($args), count($fields) )); } foreach ($fields as $field) { $conditions[$this->aliasField($field)] = array_shift($args); } return $conditions; }; if ($hasOr !== false && $hasAnd !== false) { throw new BadMethodCallException( 'Cannot mix "and" & "or" in a magic finder. Use find() instead.' ); } $conditions = []; if ($hasOr === false && $hasAnd === false) { $conditions = $makeConditions([$fields], $args); } elseif ($hasOr !== false) { $fields = explode('_or_', $fields); $conditions = [ 'OR' => $makeConditions($fields, $args) ]; } elseif ($hasAnd !== false) { $fields = explode('_and_', $fields); $conditions = $makeConditions($fields, $args); } return $this->find($findType, [ 'conditions' => $conditions, ]); } /** * Handles behavior delegation + dynamic finders. * * If your Table uses any behaviors you can call them as if * they were on the table object. * * @param string $method name of the method to be invoked * @param array $args List of arguments passed to the function * @return mixed * @throws \BadMethodCallException */ public function __call($method, $args) { if ($this->_behaviors && $this->_behaviors->hasMethod($method)) { return $this->_behaviors->call($method, $args); } if (preg_match('/^find(?:\w+)?By/', $method) > 0) { return $this->_dynamicFinder($method, $args); } throw new BadMethodCallException( sprintf('Unknown method "%s"', $method) ); } /** * Returns the association named after the passed value if exists, otherwise * throws an exception. * * @param string $property the association name * @return \Cake\ORM\Association * @throws \RuntimeException if no association with such name exists */ public function __get($property) { $association = $this->_associations->get($property); if (!$association) { throw new RuntimeException(sprintf( 'Table "%s" is not associated with "%s"', get_class($this), $property )); } return $association; } /** * Returns whether an association named after the passed value * exists for this table. * * @param string $property the association name * @return bool */ public function __isset($property) { return $this->_associations->has($property); } /** * Get the object used to marshal/convert array data into objects. * * Override this method if you want a table object to use custom * marshalling logic. * * @return \Cake\ORM\Marshaller * @see \Cake\ORM\Marshaller */ public function marshaller() { return new Marshaller($this); } /** * {@inheritDoc} * * By default all the associations on this table will be hydrated. You can * limit which associations are built, or include deeper associations * using the options parameter: * * ``` * $article = $this->Articles->newEntity( * $this->request->getData(), * ['associated' => ['Tags', 'Comments.Users']] * ); * ``` * * You can limit fields that will be present in the constructed entity by * passing the `fieldList` option, which is also accepted for associations: * * ``` * $article = $this->Articles->newEntity($this->request->getData(), [ * 'fieldList' => ['title', 'body', 'tags', 'comments'], * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] * ] * ); * ``` * * The `fieldList` option lets remove or restrict input data from ending up in * the entity. If you'd like to relax the entity's default accessible fields, * you can use the `accessibleFields` option: * * ``` * $article = $this->Articles->newEntity( * $this->request->getData(), * ['accessibleFields' => ['protected_field' => true]] * ); * ``` * * By default, the data is validated before being passed to the new entity. In * the case of invalid fields, those will not be present in the resulting object. * The `validate` option can be used to disable validation on the passed data: * * ``` * $article = $this->Articles->newEntity( * $this->request->getData(), * ['validate' => false] * ); * ``` * * You can also pass the name of the validator to use in the `validate` option. * If `null` is passed to the first param of this function, no validation will * be performed. * * You can use the `Model.beforeMarshal` event to modify request data * before it is converted into entities. */ public function newEntity($data = null, array $options = []) { if ($data === null) { $class = $this->getEntityClass(); $entity = new $class([], ['source' => $this->getRegistryAlias()]); return $entity; } if (!isset($options['associated'])) { $options['associated'] = $this->_associations->keys(); } $marshaller = $this->marshaller(); return $marshaller->one($data, $options); } /** * {@inheritDoc} * * By default all the associations on this table will be hydrated. You can * limit which associations are built, or include deeper associations * using the options parameter: * * ``` * $articles = $this->Articles->newEntities( * $this->request->getData(), * ['associated' => ['Tags', 'Comments.Users']] * ); * ``` * * You can limit fields that will be present in the constructed entities by * passing the `fieldList` option, which is also accepted for associations: * * ``` * $articles = $this->Articles->newEntities($this->request->getData(), [ * 'fieldList' => ['title', 'body', 'tags', 'comments'], * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] * ] * ); * ``` * * You can use the `Model.beforeMarshal` event to modify request data * before it is converted into entities. */ public function newEntities(array $data, array $options = []) { if (!isset($options['associated'])) { $options['associated'] = $this->_associations->keys(); } $marshaller = $this->marshaller(); return $marshaller->many($data, $options); } /** * {@inheritDoc} * * When merging HasMany or BelongsToMany associations, all the entities in the * `$data` array will appear, those that can be matched by primary key will get * the data merged, but those that cannot, will be discarded. * * You can limit fields that will be present in the merged entity by * passing the `fieldList` option, which is also accepted for associations: * * ``` * $article = $this->Articles->patchEntity($article, $this->request->getData(), [ * 'fieldList' => ['title', 'body', 'tags', 'comments'], * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] * ] * ); * ``` * * By default, the data is validated before being passed to the entity. In * the case of invalid fields, those will not be assigned to the entity. * The `validate` option can be used to disable validation on the passed data: * * ``` * $article = $this->patchEntity($article, $this->request->getData(),[ * 'validate' => false * ]); * ``` * * You can use the `Model.beforeMarshal` event to modify request data * before it is converted into entities. */ public function patchEntity(EntityInterface $entity, array $data, array $options = []) { if (!isset($options['associated'])) { $options['associated'] = $this->_associations->keys(); } $marshaller = $this->marshaller(); return $marshaller->merge($entity, $data, $options); } /** * {@inheritDoc} * * Those entries in `$entities` that cannot be matched to any record in * `$data` will be discarded. Records in `$data` that could not be matched will * be marshalled as a new entity. * * When merging HasMany or BelongsToMany associations, all the entities in the * `$data` array will appear, those that can be matched by primary key will get * the data merged, but those that cannot, will be discarded. * * You can limit fields that will be present in the merged entities by * passing the `fieldList` option, which is also accepted for associations: * * ``` * $articles = $this->Articles->patchEntities($articles, $this->request->getData(), [ * 'fieldList' => ['title', 'body', 'tags', 'comments'], * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] * ] * ); * ``` * * You can use the `Model.beforeMarshal` event to modify request data * before it is converted into entities. */ public function patchEntities($entities, array $data, array $options = []) { if (!isset($options['associated'])) { $options['associated'] = $this->_associations->keys(); } $marshaller = $this->marshaller(); return $marshaller->mergeMany($entities, $data, $options); } /** * Validator method used to check the uniqueness of a value for a column. * This is meant to be used with the validation API and not to be called * directly. * * ### Example: * * ``` * $validator->add('email', [ * 'unique' => ['rule' => 'validateUnique', 'provider' => 'table'] * ]) * ``` * * Unique validation can be scoped to the value of another column: * * ``` * $validator->add('email', [ * 'unique' => [ * 'rule' => ['validateUnique', ['scope' => 'site_id']], * 'provider' => 'table' * ] * ]); * ``` * * In the above example, the email uniqueness will be scoped to only rows having * the same site_id. Scoping will only be used if the scoping field is present in * the data to be validated. * * @param mixed $value The value of column to be checked for uniqueness. * @param array $options The options array, optionally containing the 'scope' key. * May also be the validation context, if there are no options. * @param array|null $context Either the validation context or null. * @return bool True if the value is unique, or false if a non-scalar, non-unique value was given. */ public function validateUnique($value, array $options, array $context = null) { if ($context === null) { $context = $options; } $entity = new Entity( $context['data'], [ 'useSetters' => false, 'markNew' => $context['newRecord'], 'source' => $this->getRegistryAlias() ] ); $fields = array_merge( [$context['field']], isset($options['scope']) ? (array)$options['scope'] : [] ); $values = $entity->extract($fields); foreach ($values as $field) { if ($field !== null && !is_scalar($field)) { return false; } } $rule = new IsUnique($fields, $options); return $rule($entity, ['repository' => $this]); } /** * Get the Model callbacks this table is interested in. * * By implementing the conventional methods a table class is assumed * to be interested in the related event. * * Override this method if you need to add non-conventional event listeners. * Or if you want you table to listen to non-standard events. * * The conventional method map is: * * - Model.beforeMarshal => beforeMarshal * - Model.buildValidator => buildValidator * - Model.beforeFind => beforeFind * - Model.beforeSave => beforeSave * - Model.afterSave => afterSave * - Model.afterSaveCommit => afterSaveCommit * - Model.beforeDelete => beforeDelete * - Model.afterDelete => afterDelete * - Model.afterDeleteCommit => afterDeleteCommit * - Model.beforeRules => beforeRules * - Model.afterRules => afterRules * * @return array */ public function implementedEvents() { $eventMap = [ 'Model.beforeMarshal' => 'beforeMarshal', 'Model.buildValidator' => 'buildValidator', 'Model.beforeFind' => 'beforeFind', 'Model.beforeSave' => 'beforeSave', 'Model.afterSave' => 'afterSave', 'Model.afterSaveCommit' => 'afterSaveCommit', 'Model.beforeDelete' => 'beforeDelete', 'Model.afterDelete' => 'afterDelete', 'Model.afterDeleteCommit' => 'afterDeleteCommit', 'Model.beforeRules' => 'beforeRules', 'Model.afterRules' => 'afterRules', ]; $events = []; foreach ($eventMap as $event => $method) { if (!method_exists($this, $method)) { continue; } $events[$event] = $method; } return $events; } /** * {@inheritDoc} * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { return $rules; } /** * Gets a SaveOptionsBuilder instance. * * @param array $options Options to parse by the builder. * @return \Cake\ORM\SaveOptionsBuilder */ public function getSaveOptionsBuilder(array $options = []) { return new SaveOptionsBuilder($this, $options); } /** * Loads the specified associations in the passed entity or list of entities * by executing extra queries in the database and merging the results in the * appropriate properties. * * ### Example: * * ``` * $user = $usersTable->get(1); * $user = $usersTable->loadInto($user, ['Articles.Tags', 'Articles.Comments']); * echo $user->articles[0]->title; * ``` * * You can also load associations for multiple entities at once * * ### Example: * * ``` * $users = $usersTable->find()->where([...])->toList(); * $users = $usersTable->loadInto($users, ['Articles.Tags', 'Articles.Comments']); * echo $user[1]->articles[0]->title; * ``` * * The properties for the associations to be loaded will be overwritten on each entity. * * @param \Cake\Datasource\EntityInterface|array $entities a single entity or list of entities * @param array $contain A `contain()` compatible array. * @see \Cake\ORM\Query::contain() * @return \Cake\Datasource\EntityInterface|array */ public function loadInto($entities, array $contain) { return (new LazyEagerLoader)->loadInto($entities, $contain, $this); } /** * Returns an array that can be used to describe the internal state of this * object. * * @return array */ public function __debugInfo() { $conn = $this->getConnection(); $associations = $this->_associations; $behaviors = $this->_behaviors; return [ 'registryAlias' => $this->getRegistryAlias(), 'table' => $this->getTable(), 'alias' => $this->getAlias(), 'entityClass' => $this->getEntityClass(), 'associations' => $associations ? $associations->keys() : false, 'behaviors' => $behaviors ? $behaviors->loaded() : false, 'defaultConnection' => $this->defaultConnectionName(), 'connectionName' => $conn ? $conn->configName() : null ]; } }
spskeen/wgdb
vendor/cakephp/cakephp/src/ORM/Table.php
PHP
mit
93,471
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function(){function a(b,c){var d=b.lang.placeholder,e=b.lang.common.generalTab;return{title:d.title,minWidth:300,minHeight:80,contents:[{id:'info',label:e,title:e,elements:[{id:'text',type:'text',style:'width: 100%;',label:d.text,'default':'',required:true,validate:CKEDITOR.dialog.validate.notEmpty(d.textMissing),setup:function(f){if(c)this.setValue(f.getText().slice(2,-2));},commit:function(f){var g='[['+this.getValue()+']]';CKEDITOR.plugins.placeholder.createPlaceholder(b,f,g);}}]}],onShow:function(){if(c)this._element=CKEDITOR.plugins.placeholder.getSelectedPlaceHoder(b);this.setupContent(this._element);},onOk:function(){this.commitContent(this._element);delete this._element;}};};CKEDITOR.dialog.add('createplaceholder',function(b){return a(b);});CKEDITOR.dialog.add('editplaceholder',function(b){return a(b,1);});})();
evansd-archive/kohana-module--ckeditor
vendor/ckeditor/plugins/placeholder/dialogs/placeholder.js
JavaScript
mit
985
using System; using System.Collections; using System.Linq; namespace umbraco.macroRenderings { /// <summary> /// Summary description for propertyTypePicker. /// </summary> public class propertyTypePicker : System.Web.UI.WebControls.ListBox, interfaces.IMacroGuiRendering { string _value = ""; bool _multiple = false; public bool ShowCaption { get {return true;} } public virtual bool Multiple { set {_multiple = value;} get {return _multiple;} } public string Value { get { string retVal = ""; foreach(System.Web.UI.WebControls.ListItem i in base.Items) if (i.Selected) retVal += i.Value + ","; if (retVal != "") retVal = retVal.Substring(0, retVal.Length-1); return retVal; } set { _value = value; } } public propertyTypePicker() { // // TODO: Add constructor logic here // } protected override void OnInit(EventArgs e) { base.OnInit (e); this.CssClass = "guiInputTextStandard"; // Check for multiple choises if (_multiple) { this.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple; this.Rows = 5; this.Multiple =true; } else { this.Rows = 1; this.Items.Add(new System.Web.UI.WebControls.ListItem("", "")); this.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Single; } Hashtable ht = new Hashtable(); foreach(cms.businesslogic.propertytype.PropertyType pt in cms.businesslogic.propertytype.PropertyType.GetAll().OrderBy(x => x.Name)) { if (!ht.ContainsKey(pt.Alias)) { System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(pt.Alias); if (((string) (", "+_value+",")).IndexOf(", "+pt.Alias+",") > -1) li.Selected = true; ht.Add(pt.Alias, ""); this.Items.Add(li); } } } } }
dampee/Umbraco-CMS
src/umbraco.macroRenderings/propertyTypePicker.cs
C#
mit
1,959
if(!dojo._hasResource["tests.rpc"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["tests.rpc"] = true; dojo.provide("tests.rpc"); dojo.require("dojo.rpc.RpcService"); dojo.require("dojo.rpc.JsonService"); dojo.require("dojo.rpc.JsonpService"); doh.register("tests.rpc", [ { name: "JsonRPC-EchoTest", timeout: 2000, setUp: function(){ var testSmd = { serviceURL:"../../dojo/tests/resources/test_JsonRPCMediator.php", methods:[ { name:"myecho", parameters:[ { name:"somestring", type:"STRING" } ] } ] } this.svc = new dojo.rpc.JsonService(testSmd); }, runTest: function(){ var d = new doh.Deferred(); var td = this.svc.myecho("RPC TEST"); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and PHP and will fail intentionally if loaded from file://"); d.errback(err); return d; } td.addCallbacks(function(result) { if(result=="<P>RPC TEST</P>"){ return true; }else{ return new Error("JsonRpc-EchoTest test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } }, { name: "JsonRPC-EmptyParamTest", timeout: 2000, setUp: function(){ var testSmd={ serviceURL:"../../dojo/tests/resources/test_JsonRPCMediator.php", methods:[ { name:"contentB" } ] } this.svc = new dojo.rpc.JsonService(testSmd); }, runTest: function(){ var d = new doh.Deferred(); var td = this.svc.contentB(); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and PHP and will fail intentionally if loaded from file://"); d.errback(err); return d; } td.addCallbacks(function(result){ if(result=="<P>Content B</P>"){ return true; }else{ return new Error("JsonRpc-EmpytParamTest test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } }, { name: "JsonRPC_SMD_Loading_test", setUp: function(){ this.svc = new dojo.rpc.JsonService("../../dojo/tests/resources/testClass.smd"); }, runTest: function(){ if (this.svc.objectName=="testClass") { return true; } else { return new Error("Error loading and/or parsing an smd file"); } } }, { name: "JsonP_test", timeout: 10000, setUp: function(){ this.svc = new dojo.rpc.JsonpService(dojo.moduleUrl("dojo.tests.resources","yahoo_smd_v1.smd"), {appid: "foo"}); }, runTest: function(){ var d = new doh.Deferred(); if (window.location.protocol=="file:") { var err= new Error("This Test requires a webserver and will fail intentionally if loaded from file://"); d.errback(err); return d; } var td = this.svc.webSearch({query:"dojotoolkit"}); td.addCallbacks(function(result){ return true; if (result["ResultSet"]["Result"][0]["DisplayUrl"]=="dojotoolkit.org/") { return true; }else{ return new Error("JsonRpc_SMD_Loading_Test failed, resultant content didn't match"); } }, function(result){ return new Error(result); }); td.addBoth(d, "callback"); return d; } } ] ); }
Goldcap/TAHealth
web/js/dojo/dojo/tests/rpc.js
JavaScript
mit
3,491
// Type definitions for multer-s3 2.7 // Project: https://github.com/badunk/multer-s3 // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <https://github.com/tcaesvk> // Gal Talmor <https://github.com/galtalmor> // Matt Terski <https://github.com/terski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as AWS from "aws-sdk"; import { StorageEngine } from "multer"; interface Options { s3: AWS.S3; bucket: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, bucket?: string) => void) => void) | string; key?(req: Express.Request, file: Express.Multer.File, callback: (error: any, key?: string) => void): void; acl?: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, acl?: string) => void) => void) | string | undefined; contentType?(req: Express.Request, file: Express.Multer.File, callback: (error: any, mime?: string, stream?: NodeJS.ReadableStream) => void): void; contentDisposition?: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, contentDisposition?: string) => void) => void) | string | undefined; metadata?(req: Express.Request, file: Express.Multer.File, callback: (error: any, metadata?: any) => void): void; cacheControl?: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, cacheControl?: string) => void) => void) | string | undefined; serverSideEncryption?: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, serverSideEncryption?: string) => void) => void) | string | undefined; } declare global { namespace Express { namespace MulterS3 { interface File extends Multer.File { bucket: string; key: string; acl: string; contentType: string; contentDisposition: null; storageClass: string; serverSideEncryption: null; metadata: any; location: string; etag: string; } } } } interface S3Storage { (options?: Options): StorageEngine; AUTO_CONTENT_TYPE( req: Express.Request, file: Express.Multer.File, callback: (error: any, mime?: string, stream?: NodeJS.ReadableStream) => void): void; DEFAULT_CONTENT_TYPE( req: Express.Request, file: Express.Multer.File, callback: (error: any, mime?: string) => void): void; } declare const s3Storage: S3Storage; export = s3Storage;
markogresak/DefinitelyTyped
types/multer-s3/index.d.ts
TypeScript
mit
2,593
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of imagesAlignSeq</title> <meta name="keywords" content="imagesAlignSeq"> <meta name="description" content="Stabilize image sequence using coarse optical flow estimation."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html &copy; 2003 Guillaume Flandin"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <!-- menu.html videos --> <h1>imagesAlignSeq </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>Stabilize image sequence using coarse optical flow estimation.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function [J,Vxs,Vys] = imagesAlignSeq( I, pFlow, type, bndThr ) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> Stabilize image sequence using coarse optical flow estimation. Perform weak image sequence stabilization as described in: D. Park, C. Zitnick, D. Ramanan and P. Dollár &quot;Exploring Weak Stabilization for Motion Feature Extraction&quot;, CVPR 2013. The approach stabilizes coarse motion due to camera movement but leaves independent object motions intact. This code performs weak sequence stabilization only (no feature extraction), see section 3.1 of the paper. Please cite the above paper if you end up using the stabilization code. Optical flow is computed between all pairs of frames using opticalFlow.m with params 'pFlow'. Flow across multiple frames is accumulated and flow at integer locations at each stage is obtained either using either nearest neighbor (if type==1) or bilinear interpolation (if type==2) which is slightly more accurate but slower. Finally, all images in I are warped to the last frame of the sequence using the accumulated flows. If type==-1, a homography computed via imagesAlign.m with params pFlow is used instead. If videos have black boundaries use bndThr to ignore dark boundaries for flow estimation (with average pixel values under bndThr). USAGE [J,Vxs,Vys] = imagesAlignSeq( I, pFlow, [type], [bndThr] ) INPUTS I - HxWxN or HxWx3xN input image sequence pFlow - parameters to use for optical flow computation type - [1] interpolation type 1:nearest, 2:bilinear bndThr - [0] fill in black areas around image boundaries OUTPUTS J - HxWxN or HxWx3xN stabilized image sequence Vxs - HxWxN-1 x-components of flow fields Vys - HxWxN-1 y-components of flow fields EXAMPLE I = seqIo(which('peds30.seq'),'toImgs'); I=I(:,:,:,1:15); pFlow={'smooth',1,'radius',25,'type','LK','maxScale',1}; tic, J = imagesAlignSeq( I, pFlow, 1, 20 ); toc playMovie([I J],15,-10,struct('hasChn',1)) EXAMPLE % Requires Caltech Pedestrian Dataset to be installed [pth,ss,vs]=dbInfo; s=randi(length(ss)); v=randi(length(vs{s})); nm=sprintf('%s/videos/set%02i/V%03i.seq',pth,ss(s),vs{s}(v)); f=seqIo(nm,'getinfo'); f=f.numFrames; f=randi(f-30); I=seqIo(nm,'toImgs',[],1,f,f+9); pFlow={'smooth',1,'radius',25,'type','LK','maxScale',1}; tic, J = imagesAlignSeq( I, pFlow, 1, 20 ); toc playMovie([I J],15,-10,struct('hasChn',1)) See also <a href="opticalFlow.html" class="code" title="function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin )">opticalFlow</a>, imtransform2, <a href="imagesAlign.html" class="code" title="function [H,Ip] = imagesAlign( I, Iref, varargin )">imagesAlign</a> Piotr's Computer Vision Matlab Toolbox Version 3.24 Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] Licensed under the Simplified BSD License [see external/bsd.txt]</pre></div> <!-- Start of Google Analytics Code --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-4884268-1"); pageTracker._initData(); pageTracker._trackPageview(); </script> <!-- end of Google Analytics Code --> <hr><address>Generated by <strong><a href="http://www.artefact.tk/software/matlab/m2html/" target="_parent">m2html</a></strong> &copy; 2003</address> </body> </html>
subtri/streaming_VOP_clustering
object_proposals/piotr_toolbox/doc/videos/imagesAlignSeq.html
HTML
mit
4,811
<div id="bx-uploader-file-{storage_object}-{file_id}" class="bx-uploader-ghost bx-def-margin-sec-top bx-clearfix"> <input type="hidden" name="__name__[]" value="{file_id}" /> <div class="bx-base-general-icon-wrapper bx-def-margin-sec-right"> <img src="{file_icon}" class="bx-def-round-corners bx-base-general-icon bx-base-general-icon-{file_id}" /> </div> <span class="bx-base-general-uploader-ghost"> <b><bx_text:_sys_txt_form_entry_input_picture_pic_url /></b><br /> <input class="bx-def-font-inputs bx-form-input-text bx-def-margin-sec-bottom" type="text" value="{file_url}" readonly="1" /> <br /> <span id="bx-base-general-intert-to-post-link-{file_id}" style="display:none;"> <a class="bx-btn bx-btn-small bx-def-margin-sec-right" href="javascript:void(0);" onclick="bx_base_general_insert_to_post('{file_id}', '{file_url}', '__editor_id__');"><bx_text:_sys_txt_form_entry_input_picture_insert /></a> </span> <a class="bx-btn bx-btn-small bx-def-margin-sec-right" href="javascript:void(0);" onclick="bx_base_general_delete_ghost('{file_id}', '{file_url}', '{file_icon}', ['__editor_id__'], {js_instance_name});"><bx_text:_sys_txt_form_entry_input_picture_delete /></a> <bx_if:set_thumb> <span class="bx-base-general-use-as-thumb"> <input type="checkbox" name="__name_thumb__[]" value="{file_id}" onclick="bx_base_general_select_thumb(this)" id="__name_thumb__-{file_id}" /> <label for="__name_thumb__-{file_id}">__txt_pict_use_as_thumb__</label> </span> </bx_if:set_thumb> </span> </div> <script> $('#bx-base-general-intert-to-post-link-{file_id}').show(); $('#bx-uploader-file-{storage_object}-{file_id} .bx-base-general-use-as-thumb input[value="__thumb_id__"]').attr('checked', true); // disable images drag&drop, because resized images address can be reset after some time $(".bx-base-general-icon-{file_id}").bind('dragstart', function(){ return false; }); // select first image as a thumb by default if (!__content_id__ && 1 == $('input[name="__name_thumb__[]"]').length) $('input[name="__name_thumb__[]"]').attr('checked', true); </script>
camperjz/trident
upgrade/files/9.0.0.RC8-9.0.0.RC9/files/modules/base/text/template/form_ghost_template.html
HTML
mit
2,255
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_COMPILER_UNITTESTS_INSTRUCTION_SELECTOR_UNITTEST_H_ #define V8_COMPILER_UNITTESTS_INSTRUCTION_SELECTOR_UNITTEST_H_ #include <deque> #include "src/compiler/instruction-selector.h" #include "src/compiler/raw-machine-assembler.h" #include "test/compiler-unittests/compiler-unittests.h" namespace v8 { namespace internal { namespace compiler { class InstructionSelectorTest : public CompilerTest { public: InstructionSelectorTest() {} virtual ~InstructionSelectorTest() {} protected: class Stream; enum StreamBuilderMode { kAllInstructions, kTargetInstructions }; class StreamBuilder V8_FINAL : public RawMachineAssembler { public: StreamBuilder(InstructionSelectorTest* test, MachineType return_type) : RawMachineAssembler(new (test->zone()) Graph(test->zone()), CallDescriptorBuilder(test->zone(), return_type)), test_(test) {} StreamBuilder(InstructionSelectorTest* test, MachineType return_type, MachineType parameter0_type) : RawMachineAssembler(new (test->zone()) Graph(test->zone()), CallDescriptorBuilder(test->zone(), return_type, parameter0_type)), test_(test) {} StreamBuilder(InstructionSelectorTest* test, MachineType return_type, MachineType parameter0_type, MachineType parameter1_type) : RawMachineAssembler( new (test->zone()) Graph(test->zone()), CallDescriptorBuilder(test->zone(), return_type, parameter0_type, parameter1_type)), test_(test) {} Stream Build(CpuFeature feature) { return Build(InstructionSelector::Features(feature)); } Stream Build(CpuFeature feature1, CpuFeature feature2) { return Build(InstructionSelector::Features(feature1, feature2)); } Stream Build(StreamBuilderMode mode = kTargetInstructions) { return Build(InstructionSelector::Features(), mode); } Stream Build(InstructionSelector::Features features, StreamBuilderMode mode = kTargetInstructions); private: MachineCallDescriptorBuilder* CallDescriptorBuilder( Zone* zone, MachineType return_type) { return new (zone) MachineCallDescriptorBuilder(return_type, 0, NULL); } MachineCallDescriptorBuilder* CallDescriptorBuilder( Zone* zone, MachineType return_type, MachineType parameter0_type) { MachineType* parameter_types = zone->NewArray<MachineType>(1); parameter_types[0] = parameter0_type; return new (zone) MachineCallDescriptorBuilder(return_type, 1, parameter_types); } MachineCallDescriptorBuilder* CallDescriptorBuilder( Zone* zone, MachineType return_type, MachineType parameter0_type, MachineType parameter1_type) { MachineType* parameter_types = zone->NewArray<MachineType>(2); parameter_types[0] = parameter0_type; parameter_types[1] = parameter1_type; return new (zone) MachineCallDescriptorBuilder(return_type, 2, parameter_types); } private: InstructionSelectorTest* test_; }; class Stream V8_FINAL { public: size_t size() const { return instructions_.size(); } const Instruction* operator[](size_t index) const { EXPECT_LT(index, size()); return instructions_[index]; } int32_t ToInt32(const InstructionOperand* operand) const { return ToConstant(operand).ToInt32(); } private: Constant ToConstant(const InstructionOperand* operand) const { ConstantMap::const_iterator i; if (operand->IsConstant()) { i = constants_.find(operand->index()); EXPECT_NE(constants_.end(), i); } else { EXPECT_EQ(InstructionOperand::IMMEDIATE, operand->kind()); i = immediates_.find(operand->index()); EXPECT_NE(immediates_.end(), i); } EXPECT_EQ(operand->index(), i->first); return i->second; } friend class StreamBuilder; typedef std::map<int, Constant> ConstantMap; ConstantMap constants_; ConstantMap immediates_; std::deque<Instruction*> instructions_; }; }; } // namespace compiler } // namespace internal } // namespace v8 #endif // V8_COMPILER_UNITTESTS_INSTRUCTION_SELECTOR_UNITTEST_H_
kingland/go-v8
v8-3.28/test/compiler-unittests/instruction-selector-unittest.h
C
mit
4,530
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - integrate_function_adapt_simpson_abstract.h</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2013 Steve Taylor (steve98654@gmail.com) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#undef</font> DLIB_INTEGRATE_FUNCTION_ADAPT_SIMPSON_ABSTRACTh_ <font color='#0000FF'>#ifdef</font> DLIB_INTEGRATE_FUNCTION_ADAPT_SIMPSON_ABSTRACTh_ <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> T, <font color='#0000FF'>typename</font> funct<font color='#5555FF'>&gt;</font> T <b><a name='integrate_function_adapt_simp'></a>integrate_function_adapt_simp</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> funct<font color='#5555FF'>&amp;</font> f, T a, T b, T tol <font color='#5555FF'>=</font> <font color='#979000'>1e</font><font color='#5555FF'>-</font><font color='#979000'>10</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - b &gt; a - tol &gt; 0 - T should be either float, double, or long double - The expression f(a) should be a valid expression that evaluates to a T. I.e. f() should be a real valued function of a single variable. ensures - returns an approximation of the integral of f over the domain [a,b] using the adaptive Simpson method outlined in Gander, W. and W. Gautshi, "Adaptive Quadrature -- Revisited" BIT, Vol. 40, (2000), pp.84-101 - tol is a tolerance parameter that determines the overall accuracy of approximated integral. We suggest a default value of 1e-10 for tol. !*/</font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_INTEGRATE_FUNCTION_ADAPT_SIMPSON_ABSTRACTh_ </font> </pre></body></html>
ruby-dlib/ruby-dlib
ext/dlib-19.4/docs/dlib/numerical_integration/integrate_function_adapt_simpson_abstract.h.html
HTML
mit
2,177
// set default source and build directories var dest = './build'; var src = './src'; module.exports = { // options for Gulp tasks go here markup: { /* there most likely won't be a need for any markup other than a main index.html but you can add more configuration here if necessary */ src: src + '/index.html', dest: dest }, server: { script: 'server/main.js', ext: 'js html', watch: 'server/**/*.*', nodeArgs: ['--debug'], }, };
zelliott/intrn
gulp/config.js
JavaScript
mit
473
/* * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2013-2014 Cocos2D Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #import "../../ccMacros.h" #ifdef __CC_PLATFORM_IOS #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "CCDirectorIOS.h" NSString* const CCSetupPixelFormat; NSString* const CCSetupScreenMode; NSString* const CCSetupScreenOrientation; NSString* const CCSetupAnimationInterval; NSString* const CCSetupFixedUpdateInterval; NSString* const CCSetupShowDebugStats; NSString* const CCSetupTabletScale2X; // Landscape screen orientation. Used with CCSetupScreenOrientation. NSString* const CCScreenOrientationLandscape; // Portrait screen orientation. Used with CCSetupScreenOrientation. NSString* const CCScreenOrientationPortrait; // The flexible screen mode is Cocos2d's default. It will give you an area that can vary slightly in size. In landscape mode the height will be 320 points for mobiles and 384 points for tablets. The width of the area can vary from 480 to 568 points. NSString* const CCScreenModeFlexible; // The fixed screen mode will setup the working area to be 568 x 384 points. Depending on the device, the outer edges may be cropped. The safe area, that will be displayed on all sorts of devices, is 480 x 320 points and placed in the center of the working area. NSString* const CCScreenModeFixed; @class CCAppDelegate; @class CCScene; @interface CCNavigationController : UINavigationController <CCDirectorDelegate> { } @end /** * Most Cocos2d apps should override the CCAppDelegate, it serves as the apps starting point. By the very least, the startScene method should be overridden to return the first scene the app should display. To further customize the behavior of Cocos2d, such as the screen mode of pixel format, override the applicaton:didFinishLaunchingWithOptions: method. */ @interface CCAppDelegate : NSObject <UIApplicationDelegate, CCDirectorDelegate> { UIWindow *window_; CCNavigationController *navController_; } // ----------------------------------------------------------------------- /** @name Accessing Window and Navigation Controller */ // ----------------------------------------------------------------------- /** * The window used to display the Cocos2d content. */ @property (nonatomic, strong) UIWindow *window; /** * The navigation controller that Cocos2d is using. */ @property (atomic, readonly) CCNavigationController *navController; // ----------------------------------------------------------------------- /** @name Setting Up the Start Scene */ // ----------------------------------------------------------------------- /** * Override this method to return the first scene that Cocos2d should display. * * @return Starting scene for your app. */ - (CCScene*) startScene; // ----------------------------------------------------------------------- /** @name Cocos2d Configuration */ // ----------------------------------------------------------------------- /** * This method is normally called from the applicaton:didFinishLaunchingWithOptions: method. It will configure Cocos2d with the options that you provide. You can leave out any of the options and Cocos2d will use the default values. * * Currently supported keys for the configuration dictionary are: * * - CCSetupPixelFormat NSString with the pixel format, normally kEAGLColorFormatRGBA8 or kEAGLColorFormatRGB565. The RGB565 option is faster, but will allow less colors. * - CCSetupScreenMode NSString value that accepts either CCScreenModeFlexible or CCScreenModeFixed. * - CCSetupScreenOrientation NSString value that accepts either CCScreenOrientationLandscape or CCScreenOrientationPortrait. * - CCSetupAnimationInterval NSNumber with double. Specifies the desired interval between animation frames. Supported values are 1.0/60.0 (default) and 1.0/30.0. * - CCSetupFixedUpdateInterval NSNumber with double. Specifies the desired interval between fixed updates.Should be smaller than CCSetupAnimationInterval. Defaults to 1/60.0. * - CCSetupShowDebugStats NSNumber with bool. Specifies if the stats (FPS, frame time and draw call count) should be shown. Defaults to NO. * - CCSetupTabletScale2X NSNumber with bool. If true, the iPad will be setup to act like it has a 512x384 "retina" screen. This makes it much easier to make universal iOS games. This value is ignored when using the fixed screen mode. * * @param config Dictionary with options for configuring Cocos2d. */ - (void) setupCocos2dWithOptions:(NSDictionary*)config; @end #endif
leanlyne/ShootColor
ShootColor/Libraries/cocos2d/Platforms/iOS/CCAppDelegate.h
C
mit
5,626
using System.Linq; using Stratis.SmartContracts.CLR.Validation.Policy; namespace Stratis.SmartContracts.CLR.Validation { /// <summary> /// Validates a namespace/type/member for whitelisting /// </summary> public class WhitelistPolicyFilter { public WhitelistPolicyFilter(WhitelistPolicy policy) { this.Policy = policy; } public WhitelistPolicy Policy { get; } public PolicyValidationResult Filter(string ns, string typeName, string memberName = null) { // If there's no rule for this namespace if (!this.Policy.Namespaces.TryGetValue(ns, out NamespacePolicy namespaceRule)) return new PolicyValidationResult(PolicyValidatorResultKind.DeniedNamespace); // If there's no rule for this Type, use the Namespace's permissivity if (!namespaceRule.Types.TryGetValue(typeName, out TypePolicy typeRule)) { return namespaceRule.AccessPolicy == AccessPolicy.Allowed ? new PolicyValidationResult(PolicyValidatorResultKind.Allowed) : new PolicyValidationResult(PolicyValidatorResultKind.DeniedType); } if (typeRule.AccessPolicy == AccessPolicy.Denied && !typeRule.Members.Any()) return new PolicyValidationResult(PolicyValidatorResultKind.DeniedType); if (memberName == null) return new PolicyValidationResult(PolicyValidatorResultKind.Allowed); if (!typeRule.Members.TryGetValue(memberName, out MemberPolicy memberRule)) { return typeRule.AccessPolicy == AccessPolicy.Allowed ? new PolicyValidationResult(PolicyValidatorResultKind.Allowed) : new PolicyValidationResult(PolicyValidatorResultKind.DeniedMember); } if (memberRule.AccessPolicy == AccessPolicy.Denied) return new PolicyValidationResult(PolicyValidatorResultKind.DeniedMember, memberRule); return new PolicyValidationResult(PolicyValidatorResultKind.Allowed, memberRule); } } }
mikedennis/StratisBitcoinFullNode
src/Stratis.SmartContracts.CLR.Validation/WhitelistPolicyFilter.cs
C#
mit
2,178
local TestIAPScene = class("TestIAPScene",function() return cc.Scene:create() end) function TestIAPScene.create() local scene = TestIAPScene.new() scene:addChild(scene:createLayerMenu()) return scene end function TestIAPScene:ctor() self.iap = plugin.PluginManager:getInstance():loadPlugin("IOSIAP") self.iap:setDebugMode(true) self.iap:callFuncWithParam("requestProducts", "YOUR_PRODUCT_ID") end function TestIAPScene:createLayerMenu() local back = cc.MenuItemFont:create("back") back:registerScriptTapHandler(function() cc.Director:getInstance():replaceScene(require("HelloWorldScene").create()) end) local pay = cc.MenuItemFont:create("pay") pay:setPositionY(50) pay:registerScriptTapHandler(function() self.iap:payForProduct({productId = "YOUR_PRODUCT_ID"}, function(ret, products) cclog("%d, %s", ret, products) end) end) return cc.Menu:create(back, pay) end return TestIAPScene
dios-game/dios-cocos
src/oslibs/cocos/cocos-src/plugin/samples/HelloPluginsLua/src/TestIAPScene.lua
Lua
mit
984
let helpers = { formatPrice : function(cents) { return '$' + ( (cents / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") ); }, rando : function(arr) { return arr[Math.floor(Math.random() * arr.length)]; }, slugify : function(text) { return text.toString().toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }, getFunName : function() { var adjectives = ['adorable', 'beautiful', 'clean', 'drab', 'elegant', 'fancy', 'glamorous', 'handsome', 'long', 'magnificent', 'old-fashioned', 'plain', 'quaint', 'sparkling', 'ugliest', 'unsightly', 'angry', 'bewildered', 'clumsy', 'defeated', 'embarrassed', 'fierce', 'grumpy', 'helpless', 'itchy', 'jealous', 'lazy', 'mysterious', 'nervous', 'obnoxious', 'panicky', 'repulsive', 'scary', 'thoughtless', 'uptight', 'worried']; var nouns = ['women', 'men', 'children', 'teeth', 'feet', 'people', 'leaves', 'mice', 'geese', 'halves', 'knives', 'wives', 'lives', 'elves', 'loaves', 'potatoes', 'tomatoes', 'cacti', 'foci', 'fungi', 'nuclei', 'syllabuses', 'analyses', 'diagnoses', 'oases', 'theses', 'crises', 'phenomena', 'criteria', 'data']; return `${this.rando(adjectives)}-${this.rando(adjectives)}-${this.rando(nouns)}`; } } export default helpers;
nicholasbair/react-todo
scripts/helpers.js
JavaScript
mit
1,548
/// \file /// \brief A simple TCP based server allowing sends and receives. Can be connected by any TCP client, including telnet. /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. #include "NativeFeatureIncludes.h" #if _RAKNET_SUPPORT_PacketizedTCP==1 && _RAKNET_SUPPORT_TCPInterface==1 #ifndef __PACKETIZED_TCP #define __PACKETIZED_TCP #include "TCPInterface.h" #include "DS_ByteQueue.h" #include "DS_Map.h" namespace RakNet { class RAK_DLL_EXPORT PacketizedTCP : public TCPInterface { public: // GetInstance() and DestroyInstance(instance*) STATIC_FACTORY_DECLARATIONS(PacketizedTCP) PacketizedTCP(); virtual ~PacketizedTCP(); /// Stops the TCP server void Stop(void); /// Sends a byte stream void Send( const char *data, unsigned length, const SystemAddress &systemAddress, bool broadcast ); // Sends a concatenated list of byte streams bool SendList( const char **data, const unsigned int *lengths, const int numParameters, const SystemAddress &systemAddress, bool broadcast ); /// Returns data received Packet* Receive( void ); /// Disconnects a player/address void CloseConnection( SystemAddress systemAddress ); /// Has a previous call to connect succeeded? /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. SystemAddress HasCompletedConnectionAttempt(void); /// Has a previous call to connect failed? /// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes. SystemAddress HasFailedConnectionAttempt(void); /// Queued events of new incoming connections SystemAddress HasNewIncomingConnection(void); /// Queued events of lost connections SystemAddress HasLostConnection(void); protected: void ClearAllConnections(void); void RemoveFromConnectionList(const SystemAddress &sa); void AddToConnectionList(const SystemAddress &sa); void PushNotificationsToQueues(void); Packet *ReturnOutgoingPacket(void); // A single TCP recieve may generate multiple split packets. They are stored in the waitingPackets list until Receive is called DataStructures::Queue<Packet*> waitingPackets; DataStructures::Map<SystemAddress, DataStructures::ByteQueue *> connections; // Mirrors single producer / consumer, but processes them in Receive() before returning to user DataStructures::Queue<SystemAddress> _newIncomingConnections, _lostConnections, _failedConnectionAttempts, _completedConnectionAttempts; }; } // namespace RakNet #endif #endif // _RAKNET_SUPPORT_*
emlowry/AIEFramework
dep/raknet/include/PacketizedTCP.h
C
mit
2,534
def test(): for i in xrange(int(5e3)): t = [] for j in xrange(int(1e4)): #t[j] = 'x' t.append('x') t = ''.join(t) test()
svaarala/duktape
tests/perf/test-string-array-concat.py
Python
mit
174
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.JSEncrypt = {}))); }(this, (function (exports) { 'use strict'; var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; function int2char(n) { return BI_RM.charAt(n); } //#region BIT_OPERATIONS // (public) this & a function op_and(x, y) { return x & y; } // (public) this | a function op_or(x, y) { return x | y; } // (public) this ^ a function op_xor(x, y) { return x ^ y; } // (public) this & ~a function op_andnot(x, y) { return x & ~y; } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if (x == 0) { return -1; } var r = 0; if ((x & 0xffff) == 0) { x >>= 16; r += 16; } if ((x & 0xff) == 0) { x >>= 8; r += 8; } if ((x & 0xf) == 0) { x >>= 4; r += 4; } if ((x & 3) == 0) { x >>= 2; r += 2; } if ((x & 1) == 0) { ++r; } return r; } // return number of 1 bits in x function cbit(x) { var r = 0; while (x != 0) { x &= x - 1; ++r; } return r; } //#endregion BIT_OPERATIONS var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var b64pad = "="; function hex2b64(h) { var i; var c; var ret = ""; for (i = 0; i + 3 <= h.length; i += 3) { c = parseInt(h.substring(i, i + 3), 16); ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); } if (i + 1 == h.length) { c = parseInt(h.substring(i, i + 1), 16); ret += b64map.charAt(c << 2); } else if (i + 2 == h.length) { c = parseInt(h.substring(i, i + 2), 16); ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); } while ((ret.length & 3) > 0) { ret += b64pad; } return ret; } // convert a base64 string to hex function b64tohex(s) { var ret = ""; var i; var k = 0; // b64 state, 0-3 var slop = 0; for (i = 0; i < s.length; ++i) { if (s.charAt(i) == b64pad) { break; } var v = b64map.indexOf(s.charAt(i)); if (v < 0) { continue; } if (k == 0) { ret += int2char(v >> 2); slop = v & 3; k = 1; } else if (k == 1) { ret += int2char((slop << 2) | (v >> 4)); slop = v & 0xf; k = 2; } else if (k == 2) { ret += int2char(slop); ret += int2char(v >> 2); slop = v & 3; k = 3; } else { ret += int2char((slop << 2) | (v >> 4)); ret += int2char(v & 0xf); k = 0; } } if (k == 1) { ret += int2char(slop << 2); } return ret; } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } // Hex JavaScript decoder // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var decoder; var Hex = { decode: function (a) { var i; if (decoder === undefined) { var hex = "0123456789ABCDEF"; var ignore = " \f\n\r\t\u00A0\u2028\u2029"; decoder = {}; for (i = 0; i < 16; ++i) { decoder[hex.charAt(i)] = i; } hex = hex.toLowerCase(); for (i = 10; i < 16; ++i) { decoder[hex.charAt(i)] = i; } for (i = 0; i < ignore.length; ++i) { decoder[ignore.charAt(i)] = -1; } } var out = []; var bits = 0; var char_count = 0; for (i = 0; i < a.length; ++i) { var c = a.charAt(i); if (c == "=") { break; } c = decoder[c]; if (c == -1) { continue; } if (c === undefined) { throw new Error("Illegal character at offset " + i); } bits |= c; if (++char_count >= 2) { out[out.length] = bits; bits = 0; char_count = 0; } else { bits <<= 4; } } if (char_count) { throw new Error("Hex encoding incomplete: 4 bits missing"); } return out; } }; // Base64 JavaScript decoder // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var decoder$1; var Base64 = { decode: function (a) { var i; if (decoder$1 === undefined) { var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; decoder$1 = Object.create(null); for (i = 0; i < 64; ++i) { decoder$1[b64.charAt(i)] = i; } for (i = 0; i < ignore.length; ++i) { decoder$1[ignore.charAt(i)] = -1; } } var out = []; var bits = 0; var char_count = 0; for (i = 0; i < a.length; ++i) { var c = a.charAt(i); if (c == "=") { break; } c = decoder$1[c]; if (c == -1) { continue; } if (c === undefined) { throw new Error("Illegal character at offset " + i); } bits |= c; if (++char_count >= 4) { out[out.length] = (bits >> 16); out[out.length] = (bits >> 8) & 0xFF; out[out.length] = bits & 0xFF; bits = 0; char_count = 0; } else { bits <<= 6; } } switch (char_count) { case 1: throw new Error("Base64 encoding incomplete: at least 2 bits missing"); case 2: out[out.length] = (bits >> 10); break; case 3: out[out.length] = (bits >> 16); out[out.length] = (bits >> 8) & 0xFF; break; } return out; }, re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, unarmor: function (a) { var m = Base64.re.exec(a); if (m) { if (m[1]) { a = m[1]; } else if (m[2]) { a = m[2]; } else { throw new Error("RegExp out of sync"); } } return Base64.decode(a); } }; // Big integer base-10 printing library // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it> // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 var Int10 = /** @class */ (function () { function Int10(value) { this.buf = [+value || 0]; } Int10.prototype.mulAdd = function (m, c) { // assert(m <= 256) var b = this.buf; var l = b.length; var i; var t; for (i = 0; i < l; ++i) { t = b[i] * m + c; if (t < max) { c = 0; } else { c = 0 | (t / max); t -= c * max; } b[i] = t; } if (c > 0) { b[i] = c; } }; Int10.prototype.sub = function (c) { // assert(m <= 256) var b = this.buf; var l = b.length; var i; var t; for (i = 0; i < l; ++i) { t = b[i] - c; if (t < 0) { t += max; c = 1; } else { c = 0; } b[i] = t; } while (b[b.length - 1] === 0) { b.pop(); } }; Int10.prototype.toString = function (base) { if ((base || 10) != 10) { throw new Error("only base 10 is supported"); } var b = this.buf; var s = b[b.length - 1].toString(); for (var i = b.length - 2; i >= 0; --i) { s += (max + b[i]).toString().substring(1); } return s; }; Int10.prototype.valueOf = function () { var b = this.buf; var v = 0; for (var i = b.length - 1; i >= 0; --i) { v = v * max + b[i]; } return v; }; Int10.prototype.simplify = function () { var b = this.buf; return (b.length == 1) ? b[0] : this; }; return Int10; }()); // ASN.1 JavaScript decoder var ellipsis = "\u2026"; var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; function stringCut(str, len) { if (str.length > len) { str = str.substring(0, len) + ellipsis; } return str; } var Stream = /** @class */ (function () { function Stream(enc, pos) { this.hexDigits = "0123456789ABCDEF"; if (enc instanceof Stream) { this.enc = enc.enc; this.pos = enc.pos; } else { // enc should be an array or a binary string this.enc = enc; this.pos = pos; } } Stream.prototype.get = function (pos) { if (pos === undefined) { pos = this.pos++; } if (pos >= this.enc.length) { throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length); } return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; }; Stream.prototype.hexByte = function (b) { return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); }; Stream.prototype.hexDump = function (start, end, raw) { var s = ""; for (var i = start; i < end; ++i) { s += this.hexByte(this.get(i)); if (raw !== true) { switch (i & 0xF) { case 0x7: s += " "; break; case 0xF: s += "\n"; break; default: s += " "; } } } return s; }; Stream.prototype.isASCII = function (start, end) { for (var i = start; i < end; ++i) { var c = this.get(i); if (c < 32 || c > 176) { return false; } } return true; }; Stream.prototype.parseStringISO = function (start, end) { var s = ""; for (var i = start; i < end; ++i) { s += String.fromCharCode(this.get(i)); } return s; }; Stream.prototype.parseStringUTF = function (start, end) { var s = ""; for (var i = start; i < end;) { var c = this.get(i++); if (c < 128) { s += String.fromCharCode(c); } else if ((c > 191) && (c < 224)) { s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); } else { s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); } } return s; }; Stream.prototype.parseStringBMP = function (start, end) { var str = ""; var hi; var lo; for (var i = start; i < end;) { hi = this.get(i++); lo = this.get(i++); str += String.fromCharCode((hi << 8) | lo); } return str; }; Stream.prototype.parseTime = function (start, end, shortYear) { var s = this.parseStringISO(start, end); var m = (shortYear ? reTimeS : reTimeL).exec(s); if (!m) { return "Unrecognized time: " + s; } if (shortYear) { // to avoid querying the timer, use the fixed range [1970, 2069] // it will conform with ITU X.400 [-10, +40] sliding window until 2030 m[1] = +m[1]; m[1] += (+m[1] < 70) ? 2000 : 1900; } s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; if (m[5]) { s += ":" + m[5]; if (m[6]) { s += ":" + m[6]; if (m[7]) { s += "." + m[7]; } } } if (m[8]) { s += " UTC"; if (m[8] != "Z") { s += m[8]; if (m[9]) { s += ":" + m[9]; } } } return s; }; Stream.prototype.parseInteger = function (start, end) { var v = this.get(start); var neg = (v > 127); var pad = neg ? 255 : 0; var len; var s = ""; // skip unuseful bits (not allowed in DER) while (v == pad && ++start < end) { v = this.get(start); } len = end - start; if (len === 0) { return neg ? -1 : 0; } // show bit length of huge integers if (len > 4) { s = v; len <<= 3; while (((+s ^ pad) & 0x80) == 0) { s = +s << 1; --len; } s = "(" + len + " bit)\n"; } // decode the integer if (neg) { v = v - 256; } var n = new Int10(v); for (var i = start + 1; i < end; ++i) { n.mulAdd(256, this.get(i)); } return s + n.toString(); }; Stream.prototype.parseBitString = function (start, end, maxLength) { var unusedBit = this.get(start); var lenBit = ((end - start - 1) << 3) - unusedBit; var intro = "(" + lenBit + " bit)\n"; var s = ""; for (var i = start + 1; i < end; ++i) { var b = this.get(i); var skip = (i == end - 1) ? unusedBit : 0; for (var j = 7; j >= skip; --j) { s += (b >> j) & 1 ? "1" : "0"; } if (s.length > maxLength) { return intro + stringCut(s, maxLength); } } return intro + s; }; Stream.prototype.parseOctetString = function (start, end, maxLength) { if (this.isASCII(start, end)) { return stringCut(this.parseStringISO(start, end), maxLength); } var len = end - start; var s = "(" + len + " byte)\n"; maxLength /= 2; // we work in bytes if (len > maxLength) { end = start + maxLength; } for (var i = start; i < end; ++i) { s += this.hexByte(this.get(i)); } if (len > maxLength) { s += ellipsis; } return s; }; Stream.prototype.parseOID = function (start, end, maxLength) { var s = ""; var n = new Int10(); var bits = 0; for (var i = start; i < end; ++i) { var v = this.get(i); n.mulAdd(128, v & 0x7F); bits += 7; if (!(v & 0x80)) { // finished if (s === "") { n = n.simplify(); if (n instanceof Int10) { n.sub(80); s = "2." + n.toString(); } else { var m = n < 80 ? n < 40 ? 0 : 1 : 2; s = m + "." + (n - m * 40); } } else { s += "." + n.toString(); } if (s.length > maxLength) { return stringCut(s, maxLength); } n = new Int10(); bits = 0; } } if (bits > 0) { s += ".incomplete"; } return s; }; return Stream; }()); var ASN1 = /** @class */ (function () { function ASN1(stream, header, length, tag, sub) { if (!(tag instanceof ASN1Tag)) { throw new Error("Invalid tag value."); } this.stream = stream; this.header = header; this.length = length; this.tag = tag; this.sub = sub; } ASN1.prototype.typeName = function () { switch (this.tag.tagClass) { case 0: // universal switch (this.tag.tagNumber) { case 0x00: return "EOC"; case 0x01: return "BOOLEAN"; case 0x02: return "INTEGER"; case 0x03: return "BIT_STRING"; case 0x04: return "OCTET_STRING"; case 0x05: return "NULL"; case 0x06: return "OBJECT_IDENTIFIER"; case 0x07: return "ObjectDescriptor"; case 0x08: return "EXTERNAL"; case 0x09: return "REAL"; case 0x0A: return "ENUMERATED"; case 0x0B: return "EMBEDDED_PDV"; case 0x0C: return "UTF8String"; case 0x10: return "SEQUENCE"; case 0x11: return "SET"; case 0x12: return "NumericString"; case 0x13: return "PrintableString"; // ASCII subset case 0x14: return "TeletexString"; // aka T61String case 0x15: return "VideotexString"; case 0x16: return "IA5String"; // ASCII case 0x17: return "UTCTime"; case 0x18: return "GeneralizedTime"; case 0x19: return "GraphicString"; case 0x1A: return "VisibleString"; // ASCII subset case 0x1B: return "GeneralString"; case 0x1C: return "UniversalString"; case 0x1E: return "BMPString"; } return "Universal_" + this.tag.tagNumber.toString(); case 1: return "Application_" + this.tag.tagNumber.toString(); case 2: return "[" + this.tag.tagNumber.toString() + "]"; // Context case 3: return "Private_" + this.tag.tagNumber.toString(); } }; ASN1.prototype.content = function (maxLength) { if (this.tag === undefined) { return null; } if (maxLength === undefined) { maxLength = Infinity; } var content = this.posContent(); var len = Math.abs(this.length); if (!this.tag.isUniversal()) { if (this.sub !== null) { return "(" + this.sub.length + " elem)"; } return this.stream.parseOctetString(content, content + len, maxLength); } switch (this.tag.tagNumber) { case 0x01: // BOOLEAN return (this.stream.get(content) === 0) ? "false" : "true"; case 0x02: // INTEGER return this.stream.parseInteger(content, content + len); case 0x03: // BIT_STRING return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseBitString(content, content + len, maxLength); case 0x04: // OCTET_STRING return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseOctetString(content, content + len, maxLength); // case 0x05: // NULL case 0x06: // OBJECT_IDENTIFIER return this.stream.parseOID(content, content + len, maxLength); // case 0x07: // ObjectDescriptor // case 0x08: // EXTERNAL // case 0x09: // REAL // case 0x0A: // ENUMERATED // case 0x0B: // EMBEDDED_PDV case 0x10: // SEQUENCE case 0x11: // SET if (this.sub !== null) { return "(" + this.sub.length + " elem)"; } else { return "(no elem)"; } case 0x0C: // UTF8String return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); case 0x12: // NumericString case 0x13: // PrintableString case 0x14: // TeletexString case 0x15: // VideotexString case 0x16: // IA5String // case 0x19: // GraphicString case 0x1A: // VisibleString // case 0x1B: // GeneralString // case 0x1C: // UniversalString return stringCut(this.stream.parseStringISO(content, content + len), maxLength); case 0x1E: // BMPString return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); case 0x17: // UTCTime case 0x18: // GeneralizedTime return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); } return null; }; ASN1.prototype.toString = function () { return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]"; }; ASN1.prototype.toPrettyString = function (indent) { if (indent === undefined) { indent = ""; } var s = indent + this.typeName() + " @" + this.stream.pos; if (this.length >= 0) { s += "+"; } s += this.length; if (this.tag.tagConstructed) { s += " (constructed)"; } else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) { s += " (encapsulates)"; } s += "\n"; if (this.sub !== null) { indent += " "; for (var i = 0, max = this.sub.length; i < max; ++i) { s += this.sub[i].toPrettyString(indent); } } return s; }; ASN1.prototype.posStart = function () { return this.stream.pos; }; ASN1.prototype.posContent = function () { return this.stream.pos + this.header; }; ASN1.prototype.posEnd = function () { return this.stream.pos + this.header + Math.abs(this.length); }; ASN1.prototype.toHexString = function () { return this.stream.hexDump(this.posStart(), this.posEnd(), true); }; ASN1.decodeLength = function (stream) { var buf = stream.get(); var len = buf & 0x7F; if (len == buf) { return len; } // no reason to use Int10, as it would be a huge buffer anyways if (len > 6) { throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1)); } if (len === 0) { return null; } // undefined buf = 0; for (var i = 0; i < len; ++i) { buf = (buf * 256) + stream.get(); } return buf; }; /** * Retrieve the hexadecimal value (as a string) of the current ASN.1 element * @returns {string} * @public */ ASN1.prototype.getHexStringValue = function () { var hexString = this.toHexString(); var offset = this.header * 2; var length = this.length * 2; return hexString.substr(offset, length); }; ASN1.decode = function (str) { var stream; if (!(str instanceof Stream)) { stream = new Stream(str, 0); } else { stream = str; } var streamStart = new Stream(stream); var tag = new ASN1Tag(stream); var len = ASN1.decodeLength(stream); var start = stream.pos; var header = start - streamStart.pos; var sub = null; var getSub = function () { var ret = []; if (len !== null) { // definite length var end = start + len; while (stream.pos < end) { ret[ret.length] = ASN1.decode(stream); } if (stream.pos != end) { throw new Error("Content size is not correct for container starting at offset " + start); } } else { // undefined length try { for (;;) { var s = ASN1.decode(stream); if (s.tag.isEOC()) { break; } ret[ret.length] = s; } len = start - stream.pos; // undefined lengths are represented as negative values } catch (e) { throw new Error("Exception while decoding undefined length content: " + e); } } return ret; }; if (tag.tagConstructed) { // must have valid content sub = getSub(); } else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { // sometimes BitString and OctetString are used to encapsulate ASN.1 try { if (tag.tagNumber == 0x03) { if (stream.get() != 0) { throw new Error("BIT STRINGs with unused bits cannot encapsulate."); } } sub = getSub(); for (var i = 0; i < sub.length; ++i) { if (sub[i].tag.isEOC()) { throw new Error("EOC is not supposed to be actual content."); } } } catch (e) { // but silently ignore when they don't sub = null; } } if (sub === null) { if (len === null) { throw new Error("We can't skip over an invalid tag with undefined length at offset " + start); } stream.pos = start + Math.abs(len); } return new ASN1(streamStart, header, len, tag, sub); }; return ASN1; }()); var ASN1Tag = /** @class */ (function () { function ASN1Tag(stream) { var buf = stream.get(); this.tagClass = buf >> 6; this.tagConstructed = ((buf & 0x20) !== 0); this.tagNumber = buf & 0x1F; if (this.tagNumber == 0x1F) { // long tag var n = new Int10(); do { buf = stream.get(); n.mulAdd(128, buf & 0x7F); } while (buf & 0x80); this.tagNumber = n.simplify(); } } ASN1Tag.prototype.isUniversal = function () { return this.tagClass === 0x00; }; ASN1Tag.prototype.isEOC = function () { return this.tagClass === 0x00 && this.tagNumber === 0x00; }; return ASN1Tag; }()); // Copyright (c) 2005 Tom Wu // Bits per digit var dbits; // JavaScript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary & 0xffffff) == 0xefcafe); //#region var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; //#endregion // (public) Constructor var BigInteger = /** @class */ (function () { function BigInteger(a, b, c) { if (a != null) { if ("number" == typeof a) { this.fromNumber(a, b, c); } else if (b == null && "string" != typeof a) { this.fromString(a, 256); } else { this.fromString(a, b); } } } //#region PUBLIC // BigInteger.prototype.toString = bnToString; // (public) return string representation in given radix BigInteger.prototype.toString = function (b) { if (this.s < 0) { return "-" + this.negate().toString(b); } var k; if (b == 16) { k = 4; } else if (b == 8) { k = 3; } else if (b == 2) { k = 1; } else if (b == 32) { k = 5; } else if (b == 4) { k = 2; } else { return this.toRadix(b); } var km = (1 << k) - 1; var d; var m = false; var r = ""; var i = this.t; var p = this.DB - (i * this.DB) % k; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) > 0) { m = true; r = int2char(d); } while (i >= 0) { if (p < k) { d = (this[i] & ((1 << p) - 1)) << (k - p); d |= this[--i] >> (p += this.DB - k); } else { d = (this[i] >> (p -= k)) & km; if (p <= 0) { p += this.DB; --i; } } if (d > 0) { m = true; } if (m) { r += int2char(d); } } } return m ? r : "0"; }; // BigInteger.prototype.negate = bnNegate; // (public) -this BigInteger.prototype.negate = function () { var r = nbi(); BigInteger.ZERO.subTo(this, r); return r; }; // BigInteger.prototype.abs = bnAbs; // (public) |this| BigInteger.prototype.abs = function () { return (this.s < 0) ? this.negate() : this; }; // BigInteger.prototype.compareTo = bnCompareTo; // (public) return + if this > a, - if this < a, 0 if equal BigInteger.prototype.compareTo = function (a) { var r = this.s - a.s; if (r != 0) { return r; } var i = this.t; r = i - a.t; if (r != 0) { return (this.s < 0) ? -r : r; } while (--i >= 0) { if ((r = this[i] - a[i]) != 0) { return r; } } return 0; }; // BigInteger.prototype.bitLength = bnBitLength; // (public) return the number of bits in "this" BigInteger.prototype.bitLength = function () { if (this.t <= 0) { return 0; } return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); }; // BigInteger.prototype.mod = bnMod; // (public) this mod a BigInteger.prototype.mod = function (a) { var r = nbi(); this.abs().divRemTo(a, null, r); if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { a.subTo(r, r); } return r; }; // BigInteger.prototype.modPowInt = bnModPowInt; // (public) this^e % m, 0 <= e < 2^32 BigInteger.prototype.modPowInt = function (e, m) { var z; if (e < 256 || m.isEven()) { z = new Classic(m); } else { z = new Montgomery(m); } return this.exp(e, z); }; // BigInteger.prototype.clone = bnClone; // (public) BigInteger.prototype.clone = function () { var r = nbi(); this.copyTo(r); return r; }; // BigInteger.prototype.intValue = bnIntValue; // (public) return value as integer BigInteger.prototype.intValue = function () { if (this.s < 0) { if (this.t == 1) { return this[0] - this.DV; } else if (this.t == 0) { return -1; } } else if (this.t == 1) { return this[0]; } else if (this.t == 0) { return 0; } // assumes 16 < DB < 32 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; }; // BigInteger.prototype.byteValue = bnByteValue; // (public) return value as byte BigInteger.prototype.byteValue = function () { return (this.t == 0) ? this.s : (this[0] << 24) >> 24; }; // BigInteger.prototype.shortValue = bnShortValue; // (public) return value as short (assumes DB>=16) BigInteger.prototype.shortValue = function () { return (this.t == 0) ? this.s : (this[0] << 16) >> 16; }; // BigInteger.prototype.signum = bnSigNum; // (public) 0 if this == 0, 1 if this > 0 BigInteger.prototype.signum = function () { if (this.s < 0) { return -1; } else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { return 0; } else { return 1; } }; // BigInteger.prototype.toByteArray = bnToByteArray; // (public) convert to bigendian byte array BigInteger.prototype.toByteArray = function () { var i = this.t; var r = []; r[0] = this.s; var p = this.DB - (i * this.DB) % 8; var d; var k = 0; if (i-- > 0) { if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { r[k++] = d | (this.s << (this.DB - p)); } while (i >= 0) { if (p < 8) { d = (this[i] & ((1 << p) - 1)) << (8 - p); d |= this[--i] >> (p += this.DB - 8); } else { d = (this[i] >> (p -= 8)) & 0xff; if (p <= 0) { p += this.DB; --i; } } if ((d & 0x80) != 0) { d |= -256; } if (k == 0 && (this.s & 0x80) != (d & 0x80)) { ++k; } if (k > 0 || d != this.s) { r[k++] = d; } } } return r; }; // BigInteger.prototype.equals = bnEquals; BigInteger.prototype.equals = function (a) { return (this.compareTo(a) == 0); }; // BigInteger.prototype.min = bnMin; BigInteger.prototype.min = function (a) { return (this.compareTo(a) < 0) ? this : a; }; // BigInteger.prototype.max = bnMax; BigInteger.prototype.max = function (a) { return (this.compareTo(a) > 0) ? this : a; }; // BigInteger.prototype.and = bnAnd; BigInteger.prototype.and = function (a) { var r = nbi(); this.bitwiseTo(a, op_and, r); return r; }; // BigInteger.prototype.or = bnOr; BigInteger.prototype.or = function (a) { var r = nbi(); this.bitwiseTo(a, op_or, r); return r; }; // BigInteger.prototype.xor = bnXor; BigInteger.prototype.xor = function (a) { var r = nbi(); this.bitwiseTo(a, op_xor, r); return r; }; // BigInteger.prototype.andNot = bnAndNot; BigInteger.prototype.andNot = function (a) { var r = nbi(); this.bitwiseTo(a, op_andnot, r); return r; }; // BigInteger.prototype.not = bnNot; // (public) ~this BigInteger.prototype.not = function () { var r = nbi(); for (var i = 0; i < this.t; ++i) { r[i] = this.DM & ~this[i]; } r.t = this.t; r.s = ~this.s; return r; }; // BigInteger.prototype.shiftLeft = bnShiftLeft; // (public) this << n BigInteger.prototype.shiftLeft = function (n) { var r = nbi(); if (n < 0) { this.rShiftTo(-n, r); } else { this.lShiftTo(n, r); } return r; }; // BigInteger.prototype.shiftRight = bnShiftRight; // (public) this >> n BigInteger.prototype.shiftRight = function (n) { var r = nbi(); if (n < 0) { this.lShiftTo(-n, r); } else { this.rShiftTo(n, r); } return r; }; // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; // (public) returns index of lowest 1-bit (or -1 if none) BigInteger.prototype.getLowestSetBit = function () { for (var i = 0; i < this.t; ++i) { if (this[i] != 0) { return i * this.DB + lbit(this[i]); } } if (this.s < 0) { return this.t * this.DB; } return -1; }; // BigInteger.prototype.bitCount = bnBitCount; // (public) return number of set bits BigInteger.prototype.bitCount = function () { var r = 0; var x = this.s & this.DM; for (var i = 0; i < this.t; ++i) { r += cbit(this[i] ^ x); } return r; }; // BigInteger.prototype.testBit = bnTestBit; // (public) true iff nth bit is set BigInteger.prototype.testBit = function (n) { var j = Math.floor(n / this.DB); if (j >= this.t) { return (this.s != 0); } return ((this[j] & (1 << (n % this.DB))) != 0); }; // BigInteger.prototype.setBit = bnSetBit; // (public) this | (1<<n) BigInteger.prototype.setBit = function (n) { return this.changeBit(n, op_or); }; // BigInteger.prototype.clearBit = bnClearBit; // (public) this & ~(1<<n) BigInteger.prototype.clearBit = function (n) { return this.changeBit(n, op_andnot); }; // BigInteger.prototype.flipBit = bnFlipBit; // (public) this ^ (1<<n) BigInteger.prototype.flipBit = function (n) { return this.changeBit(n, op_xor); }; // BigInteger.prototype.add = bnAdd; // (public) this + a BigInteger.prototype.add = function (a) { var r = nbi(); this.addTo(a, r); return r; }; // BigInteger.prototype.subtract = bnSubtract; // (public) this - a BigInteger.prototype.subtract = function (a) { var r = nbi(); this.subTo(a, r); return r; }; // BigInteger.prototype.multiply = bnMultiply; // (public) this * a BigInteger.prototype.multiply = function (a) { var r = nbi(); this.multiplyTo(a, r); return r; }; // BigInteger.prototype.divide = bnDivide; // (public) this / a BigInteger.prototype.divide = function (a) { var r = nbi(); this.divRemTo(a, r, null); return r; }; // BigInteger.prototype.remainder = bnRemainder; // (public) this % a BigInteger.prototype.remainder = function (a) { var r = nbi(); this.divRemTo(a, null, r); return r; }; // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; // (public) [this/a,this%a] BigInteger.prototype.divideAndRemainder = function (a) { var q = nbi(); var r = nbi(); this.divRemTo(a, q, r); return [q, r]; }; // BigInteger.prototype.modPow = bnModPow; // (public) this^e % m (HAC 14.85) BigInteger.prototype.modPow = function (e, m) { var i = e.bitLength(); var k; var r = nbv(1); var z; if (i <= 0) { return r; } else if (i < 18) { k = 1; } else if (i < 48) { k = 3; } else if (i < 144) { k = 4; } else if (i < 768) { k = 5; } else { k = 6; } if (i < 8) { z = new Classic(m); } else if (m.isEven()) { z = new Barrett(m); } else { z = new Montgomery(m); } // precomputation var g = []; var n = 3; var k1 = k - 1; var km = (1 << k) - 1; g[1] = z.convert(this); if (k > 1) { var g2 = nbi(); z.sqrTo(g[1], g2); while (n <= km) { g[n] = nbi(); z.mulTo(g2, g[n - 2], g[n]); n += 2; } } var j = e.t - 1; var w; var is1 = true; var r2 = nbi(); var t; i = nbits(e[j]) - 1; while (j >= 0) { if (i >= k1) { w = (e[j] >> (i - k1)) & km; } else { w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); if (j > 0) { w |= e[j - 1] >> (this.DB + i - k1); } } n = k; while ((w & 1) == 0) { w >>= 1; --n; } if ((i -= n) < 0) { i += this.DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n > 1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n > 0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j >= 0 && (e[j] & (1 << i)) == 0) { z.sqrTo(r, r2); t = r; r = r2; r2 = t; if (--i < 0) { i = this.DB - 1; --j; } } } return z.revert(r); }; // BigInteger.prototype.modInverse = bnModInverse; // (public) 1/this % m (HAC 14.61) BigInteger.prototype.modInverse = function (m) { var ac = m.isEven(); if ((this.isEven() && ac) || m.signum() == 0) { return BigInteger.ZERO; } var u = m.clone(); var v = this.clone(); var a = nbv(1); var b = nbv(0); var c = nbv(0); var d = nbv(1); while (u.signum() != 0) { while (u.isEven()) { u.rShiftTo(1, u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this, a); b.subTo(m, b); } a.rShiftTo(1, a); } else if (!b.isEven()) { b.subTo(m, b); } b.rShiftTo(1, b); } while (v.isEven()) { v.rShiftTo(1, v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this, c); d.subTo(m, d); } c.rShiftTo(1, c); } else if (!d.isEven()) { d.subTo(m, d); } d.rShiftTo(1, d); } if (u.compareTo(v) >= 0) { u.subTo(v, u); if (ac) { a.subTo(c, a); } b.subTo(d, b); } else { v.subTo(u, v); if (ac) { c.subTo(a, c); } d.subTo(b, d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.signum() < 0) { d.addTo(m, d); } else { return d; } if (d.signum() < 0) { return d.add(m); } else { return d; } }; // BigInteger.prototype.pow = bnPow; // (public) this^e BigInteger.prototype.pow = function (e) { return this.exp(e, new NullExp()); }; // BigInteger.prototype.gcd = bnGCD; // (public) gcd(this,a) (HAC 14.54) BigInteger.prototype.gcd = function (a) { var x = (this.s < 0) ? this.negate() : this.clone(); var y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(); var g = y.getLowestSetBit(); if (g < 0) { return x; } if (i < g) { g = i; } if (g > 0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.signum() > 0) { if ((i = x.getLowestSetBit()) > 0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) > 0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g > 0) { y.lShiftTo(g, y); } return y; }; // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; // (public) test primality with certainty >= 1-.5^t BigInteger.prototype.isProbablePrime = function (t) { var i; var x = this.abs(); if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) { if (x[0] == lowprimes[i]) { return true; } } return false; } if (x.isEven()) { return false; } i = 1; while (i < lowprimes.length) { var m = lowprimes[i]; var j = i + 1; while (j < lowprimes.length && m < lplim) { m *= lowprimes[j++]; } m = x.modInt(m); while (i < j) { if (m % lowprimes[i++] == 0) { return false; } } } return x.millerRabin(t); }; //#endregion PUBLIC //#region PROTECTED // BigInteger.prototype.copyTo = bnpCopyTo; // (protected) copy this to r BigInteger.prototype.copyTo = function (r) { for (var i = this.t - 1; i >= 0; --i) { r[i] = this[i]; } r.t = this.t; r.s = this.s; }; // BigInteger.prototype.fromInt = bnpFromInt; // (protected) set from integer value x, -DV <= x < DV BigInteger.prototype.fromInt = function (x) { this.t = 1; this.s = (x < 0) ? -1 : 0; if (x > 0) { this[0] = x; } else if (x < -1) { this[0] = x + this.DV; } else { this.t = 0; } }; // BigInteger.prototype.fromString = bnpFromString; // (protected) set from string and radix BigInteger.prototype.fromString = function (s, b) { var k; if (b == 16) { k = 4; } else if (b == 8) { k = 3; } else if (b == 256) { k = 8; /* byte array */ } else if (b == 2) { k = 1; } else if (b == 32) { k = 5; } else if (b == 4) { k = 2; } else { this.fromRadix(s, b); return; } this.t = 0; this.s = 0; var i = s.length; var mi = false; var sh = 0; while (--i >= 0) { var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); if (x < 0) { if (s.charAt(i) == "-") { mi = true; } continue; } mi = false; if (sh == 0) { this[this.t++] = x; } else if (sh + k > this.DB) { this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; this[this.t++] = (x >> (this.DB - sh)); } else { this[this.t - 1] |= x << sh; } sh += k; if (sh >= this.DB) { sh -= this.DB; } } if (k == 8 && ((+s[0]) & 0x80) != 0) { this.s = -1; if (sh > 0) { this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; } } this.clamp(); if (mi) { BigInteger.ZERO.subTo(this, this); } }; // BigInteger.prototype.clamp = bnpClamp; // (protected) clamp off excess high words BigInteger.prototype.clamp = function () { var c = this.s & this.DM; while (this.t > 0 && this[this.t - 1] == c) { --this.t; } }; // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; // (protected) r = this << n*DB BigInteger.prototype.dlShiftTo = function (n, r) { var i; for (i = this.t - 1; i >= 0; --i) { r[i + n] = this[i]; } for (i = n - 1; i >= 0; --i) { r[i] = 0; } r.t = this.t + n; r.s = this.s; }; // BigInteger.prototype.drShiftTo = bnpDRShiftTo; // (protected) r = this >> n*DB BigInteger.prototype.drShiftTo = function (n, r) { for (var i = n; i < this.t; ++i) { r[i - n] = this[i]; } r.t = Math.max(this.t - n, 0); r.s = this.s; }; // BigInteger.prototype.lShiftTo = bnpLShiftTo; // (protected) r = this << n BigInteger.prototype.lShiftTo = function (n, r) { var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << cbs) - 1; var ds = Math.floor(n / this.DB); var c = (this.s << bs) & this.DM; for (var i = this.t - 1; i >= 0; --i) { r[i + ds + 1] = (this[i] >> cbs) | c; c = (this[i] & bm) << bs; } for (var i = ds - 1; i >= 0; --i) { r[i] = 0; } r[ds] = c; r.t = this.t + ds + 1; r.s = this.s; r.clamp(); }; // BigInteger.prototype.rShiftTo = bnpRShiftTo; // (protected) r = this >> n BigInteger.prototype.rShiftTo = function (n, r) { r.s = this.s; var ds = Math.floor(n / this.DB); if (ds >= this.t) { r.t = 0; return; } var bs = n % this.DB; var cbs = this.DB - bs; var bm = (1 << bs) - 1; r[0] = this[ds] >> bs; for (var i = ds + 1; i < this.t; ++i) { r[i - ds - 1] |= (this[i] & bm) << cbs; r[i - ds] = this[i] >> bs; } if (bs > 0) { r[this.t - ds - 1] |= (this.s & bm) << cbs; } r.t = this.t - ds; r.clamp(); }; // BigInteger.prototype.subTo = bnpSubTo; // (protected) r = this - a BigInteger.prototype.subTo = function (a, r) { var i = 0; var c = 0; var m = Math.min(a.t, this.t); while (i < m) { c += this[i] - a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c -= a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c -= a[i]; r[i++] = c & this.DM; c >>= this.DB; } c -= a.s; } r.s = (c < 0) ? -1 : 0; if (c < -1) { r[i++] = this.DV + c; } else if (c > 0) { r[i++] = c; } r.t = i; r.clamp(); }; // BigInteger.prototype.multiplyTo = bnpMultiplyTo; // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyTo = function (a, r) { var x = this.abs(); var y = a.abs(); var i = x.t; r.t = i + y.t; while (--i >= 0) { r[i] = 0; } for (i = 0; i < y.t; ++i) { r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); } r.s = 0; r.clamp(); if (this.s != a.s) { BigInteger.ZERO.subTo(r, r); } }; // BigInteger.prototype.squareTo = bnpSquareTo; // (protected) r = this^2, r != this (HAC 14.16) BigInteger.prototype.squareTo = function (r) { var x = this.abs(); var i = r.t = 2 * x.t; while (--i >= 0) { r[i] = 0; } for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1); if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV; r[i + x.t + 1] = 1; } } if (r.t > 0) { r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); } r.s = 0; r.clamp(); }; // BigInteger.prototype.divRemTo = bnpDivRemTo; // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. BigInteger.prototype.divRemTo = function (m, q, r) { var pm = m.abs(); if (pm.t <= 0) { return; } var pt = this.abs(); if (pt.t < pm.t) { if (q != null) { q.fromInt(0); } if (r != null) { this.copyTo(r); } return; } if (r == null) { r = nbi(); } var y = nbi(); var ts = this.s; var ms = m.s; var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys = y.t; var y0 = y[ys - 1]; if (y0 == 0) { return; } var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); var d1 = this.FV / yt; var d2 = (1 << this.F1) / yt; var e = 1 << this.F2; var i = r.t; var j = i - ys; var t = (q == null) ? nbi() : q; y.dlShiftTo(j, t); if (r.compareTo(t) >= 0) { r[r.t++] = 1; r.subTo(t, r); } BigInteger.ONE.dlShiftTo(ys, t); t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) { y[y.t++] = 0; } while (--j >= 0) { // Estimate quotient digit var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t); r.subTo(t, r); while (r[i] < --qd) { r.subTo(t, r); } } } if (q != null) { r.drShiftTo(ys, q); if (ts != ms) { BigInteger.ZERO.subTo(q, q); } } r.t = ys; r.clamp(); if (nsh > 0) { r.rShiftTo(nsh, r); } // Denormalize remainder if (ts < 0) { BigInteger.ZERO.subTo(r, r); } }; // BigInteger.prototype.invDigit = bnpInvDigit; // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. BigInteger.prototype.invDigit = function () { if (this.t < 1) { return 0; } var x = this[0]; if ((x & 1) == 0) { return 0; } var y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y > 0) ? this.DV - y : -y; }; // BigInteger.prototype.isEven = bnpIsEven; // (protected) true iff this is even BigInteger.prototype.isEven = function () { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; }; // BigInteger.prototype.exp = bnpExp; // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) BigInteger.prototype.exp = function (e, z) { if (e > 0xffffffff || e < 1) { return BigInteger.ONE; } var r = nbi(); var r2 = nbi(); var g = z.convert(this); var i = nbits(e) - 1; g.copyTo(r); while (--i >= 0) { z.sqrTo(r, r2); if ((e & (1 << i)) > 0) { z.mulTo(r2, g, r); } else { var t = r; r = r2; r2 = t; } } return z.revert(r); }; // BigInteger.prototype.chunkSize = bnpChunkSize; // (protected) return x s.t. r^x < DV BigInteger.prototype.chunkSize = function (r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)); }; // BigInteger.prototype.toRadix = bnpToRadix; // (protected) convert to radix string BigInteger.prototype.toRadix = function (b) { if (b == null) { b = 10; } if (this.signum() == 0 || b < 2 || b > 36) { return "0"; } var cs = this.chunkSize(b); var a = Math.pow(b, cs); var d = nbv(a); var y = nbi(); var z = nbi(); var r = ""; this.divRemTo(d, y, z); while (y.signum() > 0) { r = (a + z.intValue()).toString(b).substr(1) + r; y.divRemTo(d, y, z); } return z.intValue().toString(b) + r; }; // BigInteger.prototype.fromRadix = bnpFromRadix; // (protected) convert from radix string BigInteger.prototype.fromRadix = function (s, b) { this.fromInt(0); if (b == null) { b = 10; } var cs = this.chunkSize(b); var d = Math.pow(b, cs); var mi = false; var j = 0; var w = 0; for (var i = 0; i < s.length; ++i) { var x = intAt(s, i); if (x < 0) { if (s.charAt(i) == "-" && this.signum() == 0) { mi = true; } continue; } w = b * w + x; if (++j >= cs) { this.dMultiply(d); this.dAddOffset(w, 0); j = 0; w = 0; } } if (j > 0) { this.dMultiply(Math.pow(b, j)); this.dAddOffset(w, 0); } if (mi) { BigInteger.ZERO.subTo(this, this); } }; // BigInteger.prototype.fromNumber = bnpFromNumber; // (protected) alternate constructor BigInteger.prototype.fromNumber = function (a, b, c) { if ("number" == typeof b) { // new BigInteger(int,int,RNG) if (a < 2) { this.fromInt(1); } else { this.fromNumber(a, c); if (!this.testBit(a - 1)) { // force MSB set this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); } if (this.isEven()) { this.dAddOffset(1, 0); } // force odd while (!this.isProbablePrime(b)) { this.dAddOffset(2, 0); if (this.bitLength() > a) { this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); } } } } else { // new BigInteger(int,RNG) var x = []; var t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); if (t > 0) { x[0] &= ((1 << t) - 1); } else { x[0] = 0; } this.fromString(x, 256); } }; // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; // (protected) r = this op a (bitwise) BigInteger.prototype.bitwiseTo = function (a, op, r) { var i; var f; var m = Math.min(a.t, this.t); for (i = 0; i < m; ++i) { r[i] = op(this[i], a[i]); } if (a.t < this.t) { f = a.s & this.DM; for (i = m; i < this.t; ++i) { r[i] = op(this[i], f); } r.t = this.t; } else { f = this.s & this.DM; for (i = m; i < a.t; ++i) { r[i] = op(f, a[i]); } r.t = a.t; } r.s = op(this.s, a.s); r.clamp(); }; // BigInteger.prototype.changeBit = bnpChangeBit; // (protected) this op (1<<n) BigInteger.prototype.changeBit = function (n, op) { var r = BigInteger.ONE.shiftLeft(n); this.bitwiseTo(r, op, r); return r; }; // BigInteger.prototype.addTo = bnpAddTo; // (protected) r = this + a BigInteger.prototype.addTo = function (a, r) { var i = 0; var c = 0; var m = Math.min(a.t, this.t); while (i < m) { c += this[i] + a[i]; r[i++] = c & this.DM; c >>= this.DB; } if (a.t < this.t) { c += a.s; while (i < this.t) { c += this[i]; r[i++] = c & this.DM; c >>= this.DB; } c += this.s; } else { c += this.s; while (i < a.t) { c += a[i]; r[i++] = c & this.DM; c >>= this.DB; } c += a.s; } r.s = (c < 0) ? -1 : 0; if (c > 0) { r[i++] = c; } else if (c < -1) { r[i++] = this.DV + c; } r.t = i; r.clamp(); }; // BigInteger.prototype.dMultiply = bnpDMultiply; // (protected) this *= n, this >= 0, 1 < n < DV BigInteger.prototype.dMultiply = function (n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); ++this.t; this.clamp(); }; // BigInteger.prototype.dAddOffset = bnpDAddOffset; // (protected) this += n << w words, this >= 0 BigInteger.prototype.dAddOffset = function (n, w) { if (n == 0) { return; } while (this.t <= w) { this[this.t++] = 0; } this[w] += n; while (this[w] >= this.DV) { this[w] -= this.DV; if (++w >= this.t) { this[this.t++] = 0; } ++this[w]; } }; // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyLowerTo = function (a, n, r) { var i = Math.min(this.t + a.t, n); r.s = 0; // assumes a,this >= 0 r.t = i; while (i > 0) { r[--i] = 0; } for (var j = r.t - this.t; i < j; ++i) { r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); } for (var j = Math.min(a.t, n); i < j; ++i) { this.am(0, a[i], r, i, 0, n - i); } r.clamp(); }; // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. BigInteger.prototype.multiplyUpperTo = function (a, n, r) { --n; var i = r.t = this.t + a.t - n; r.s = 0; // assumes a,this >= 0 while (--i >= 0) { r[i] = 0; } for (i = Math.max(n - this.t, 0); i < a.t; ++i) { r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); } r.clamp(); r.drShiftTo(1, r); }; // BigInteger.prototype.modInt = bnpModInt; // (protected) this % n, n < 2^26 BigInteger.prototype.modInt = function (n) { if (n <= 0) { return 0; } var d = this.DV % n; var r = (this.s < 0) ? n - 1 : 0; if (this.t > 0) { if (d == 0) { r = this[0] % n; } else { for (var i = this.t - 1; i >= 0; --i) { r = (d * r + this[i]) % n; } } } return r; }; // BigInteger.prototype.millerRabin = bnpMillerRabin; // (protected) true if probably prime (HAC 4.24, Miller-Rabin) BigInteger.prototype.millerRabin = function (t) { var n1 = this.subtract(BigInteger.ONE); var k = n1.getLowestSetBit(); if (k <= 0) { return false; } var r = n1.shiftRight(k); t = (t + 1) >> 1; if (t > lowprimes.length) { t = lowprimes.length; } var a = nbi(); for (var i = 0; i < t; ++i) { // Pick bases at random, instead of starting at 2 a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); var y = a.modPow(r, this); if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1; while (j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2, this); if (y.compareTo(BigInteger.ONE) == 0) { return false; } } if (y.compareTo(n1) != 0) { return false; } } } return true; }; // BigInteger.prototype.square = bnSquare; // (public) this^2 BigInteger.prototype.square = function () { var r = nbi(); this.squareTo(r); return r; }; //#region ASYNC // Public API method BigInteger.prototype.gcda = function (a, callback) { var x = (this.s < 0) ? this.negate() : this.clone(); var y = (a.s < 0) ? a.negate() : a.clone(); if (x.compareTo(y) < 0) { var t = x; x = y; y = t; } var i = x.getLowestSetBit(); var g = y.getLowestSetBit(); if (g < 0) { callback(x); return; } if (i < g) { g = i; } if (g > 0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. var gcda1 = function () { if ((i = x.getLowestSetBit()) > 0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) > 0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } if (!(x.signum() > 0)) { if (g > 0) { y.lShiftTo(g, y); } setTimeout(function () { callback(y); }, 0); // escape } else { setTimeout(gcda1, 0); } }; setTimeout(gcda1, 10); }; // (protected) alternate constructor BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) { if ("number" == typeof b) { if (a < 2) { this.fromInt(1); } else { this.fromNumber(a, c); if (!this.testBit(a - 1)) { this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); } if (this.isEven()) { this.dAddOffset(1, 0); } var bnp_1 = this; var bnpfn1_1 = function () { bnp_1.dAddOffset(2, 0); if (bnp_1.bitLength() > a) { bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); } if (bnp_1.isProbablePrime(b)) { setTimeout(function () { callback(); }, 0); // escape } else { setTimeout(bnpfn1_1, 0); } }; setTimeout(bnpfn1_1, 0); } } else { var x = []; var t = a & 7; x.length = (a >> 3) + 1; b.nextBytes(x); if (t > 0) { x[0] &= ((1 << t) - 1); } else { x[0] = 0; } this.fromString(x, 256); } }; return BigInteger; }()); //#region REDUCERS //#region NullExp var NullExp = /** @class */ (function () { function NullExp() { } // NullExp.prototype.convert = nNop; NullExp.prototype.convert = function (x) { return x; }; // NullExp.prototype.revert = nNop; NullExp.prototype.revert = function (x) { return x; }; // NullExp.prototype.mulTo = nMulTo; NullExp.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); }; // NullExp.prototype.sqrTo = nSqrTo; NullExp.prototype.sqrTo = function (x, r) { x.squareTo(r); }; return NullExp; }()); // Modular reduction using "classic" algorithm var Classic = /** @class */ (function () { function Classic(m) { this.m = m; } // Classic.prototype.convert = cConvert; Classic.prototype.convert = function (x) { if (x.s < 0 || x.compareTo(this.m) >= 0) { return x.mod(this.m); } else { return x; } }; // Classic.prototype.revert = cRevert; Classic.prototype.revert = function (x) { return x; }; // Classic.prototype.reduce = cReduce; Classic.prototype.reduce = function (x) { x.divRemTo(this.m, null, x); }; // Classic.prototype.mulTo = cMulTo; Classic.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Classic.prototype.sqrTo = cSqrTo; Classic.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Classic; }()); //#endregion //#region Montgomery // Montgomery reduction var Montgomery = /** @class */ (function () { function Montgomery(m) { this.m = m; this.mp = m.invDigit(); this.mpl = this.mp & 0x7fff; this.mph = this.mp >> 15; this.um = (1 << (m.DB - 15)) - 1; this.mt2 = 2 * m.t; } // Montgomery.prototype.convert = montConvert; // xR mod m Montgomery.prototype.convert = function (x) { var r = nbi(); x.abs().dlShiftTo(this.m.t, r); r.divRemTo(this.m, null, r); if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { this.m.subTo(r, r); } return r; }; // Montgomery.prototype.revert = montRevert; // x/R mod m Montgomery.prototype.revert = function (x) { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }; // Montgomery.prototype.reduce = montReduce; // x = x/R mod m (HAC 14.32) Montgomery.prototype.reduce = function (x) { while (x.t <= this.mt2) { // pad x so am has enough room later x[x.t++] = 0; } for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff; var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; // use am to combine the multiply-shift-add into one call j = i + this.m.t; x[j] += this.m.am(0, u0, x, i, 0, this.m.t); // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } } x.clamp(); x.drShiftTo(this.m.t, x); if (x.compareTo(this.m) >= 0) { x.subTo(this.m, x); } }; // Montgomery.prototype.mulTo = montMulTo; // r = "xy/R mod m"; x,y != r Montgomery.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Montgomery.prototype.sqrTo = montSqrTo; // r = "x^2/R mod m"; x != r Montgomery.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Montgomery; }()); //#endregion Montgomery //#region Barrett // Barrett modular reduction var Barrett = /** @class */ (function () { function Barrett(m) { this.m = m; // setup Barrett this.r2 = nbi(); this.q3 = nbi(); BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); this.mu = this.r2.divide(m); } // Barrett.prototype.convert = barrettConvert; Barrett.prototype.convert = function (x) { if (x.s < 0 || x.t > 2 * this.m.t) { return x.mod(this.m); } else if (x.compareTo(this.m) < 0) { return x; } else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } }; // Barrett.prototype.revert = barrettRevert; Barrett.prototype.revert = function (x) { return x; }; // Barrett.prototype.reduce = barrettReduce; // x = x mod m (HAC 14.42) Barrett.prototype.reduce = function (x) { x.drShiftTo(this.m.t - 1, this.r2); if (x.t > this.m.t + 1) { x.t = this.m.t + 1; x.clamp(); } this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); while (x.compareTo(this.r2) < 0) { x.dAddOffset(1, this.m.t + 1); } x.subTo(this.r2, x); while (x.compareTo(this.m) >= 0) { x.subTo(this.m, x); } }; // Barrett.prototype.mulTo = barrettMulTo; // r = x*y mod m; x,y != r Barrett.prototype.mulTo = function (x, y, r) { x.multiplyTo(y, r); this.reduce(r); }; // Barrett.prototype.sqrTo = barrettSqrTo; // r = x^2 mod m; x != r Barrett.prototype.sqrTo = function (x, r) { x.squareTo(r); this.reduce(r); }; return Barrett; }()); //#endregion //#endregion REDUCERS // return new, unset BigInteger function nbi() { return new BigInteger(null); } function parseBigInt(str, r) { return new BigInteger(str, r); } // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c; c = Math.floor(v / 0x4000000); w[j++] = v & 0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff; var xh = x >> 15; while (--n >= 0) { var l = this[i] & 0x7fff; var h = this[i++] >> 15; var m = xh * l + h * xl; l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); w[j++] = l & 0x3fffffff; } return c; } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff; var xh = x >> 14; while (--n >= 0) { var l = this[i] & 0x3fff; var h = this[i++] >> 14; var m = xh * l + h * xl; l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; c = (l >> 28) + (m >> 14) + xh * h; w[j++] = l & 0xfffffff; } return c; } if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { BigInteger.prototype.am = am2; dbits = 30; } else if (j_lm && (navigator.appName != "Netscape")) { BigInteger.prototype.am = am1; dbits = 26; } else { // Mozilla/Netscape seems to prefer am3 BigInteger.prototype.am = am3; dbits = 28; } BigInteger.prototype.DB = dbits; BigInteger.prototype.DM = ((1 << dbits) - 1); BigInteger.prototype.DV = (1 << dbits); var BI_FP = 52; BigInteger.prototype.FV = Math.pow(2, BI_FP); BigInteger.prototype.F1 = BI_FP - dbits; BigInteger.prototype.F2 = 2 * dbits - BI_FP; // Digit conversions var BI_RC = []; var rr; var vv; rr = "0".charCodeAt(0); for (vv = 0; vv <= 9; ++vv) { BI_RC[rr++] = vv; } rr = "a".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; } rr = "A".charCodeAt(0); for (vv = 10; vv < 36; ++vv) { BI_RC[rr++] = vv; } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)]; return (c == null) ? -1 : c; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromInt(i); return r; } // returns bit length of the integer x function nbits(x) { var r = 1; var t; if ((t = x >>> 16) != 0) { x = t; r += 16; } if ((t = x >> 8) != 0) { x = t; r += 8; } if ((t = x >> 4) != 0) { x = t; r += 4; } if ((t = x >> 2) != 0) { x = t; r += 2; } if ((t = x >> 1) != 0) { x = t; r += 1; } return r; } // "constants" BigInteger.ZERO = nbv(0); BigInteger.ONE = nbv(1); // prng4.js - uses Arcfour as a PRNG var Arcfour = /** @class */ (function () { function Arcfour() { this.i = 0; this.j = 0; this.S = []; } // Arcfour.prototype.init = ARC4init; // Initialize arcfour context from key, an array of ints, each from [0..255] Arcfour.prototype.init = function (key) { var i; var j; var t; for (i = 0; i < 256; ++i) { this.S[i] = i; } j = 0; for (i = 0; i < 256; ++i) { j = (j + this.S[i] + key[i % key.length]) & 255; t = this.S[i]; this.S[i] = this.S[j]; this.S[j] = t; } this.i = 0; this.j = 0; }; // Arcfour.prototype.next = ARC4next; Arcfour.prototype.next = function () { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.S[this.i]) & 255; t = this.S[this.i]; this.S[this.i] = this.S[this.j]; this.S[this.j] = t; return this.S[(t + this.S[this.i]) & 255]; }; return Arcfour; }()); // Plug in your RNG constructor here function prng_newstate() { return new Arcfour(); } // Pool size must be a multiple of 4 and greater than 32. // An array of bytes the size of the pool will be passed to init() var rng_psize = 256; // Random number generator - requires a PRNG backend, e.g. prng4.js var rng_state; var rng_pool = null; var rng_pptr; // Initialize the pool with junk if needed. if (rng_pool == null) { rng_pool = []; rng_pptr = 0; var t = void 0; if (window.crypto && window.crypto.getRandomValues) { // Extract entropy (2048 bits) from RNG if available var z = new Uint32Array(256); window.crypto.getRandomValues(z); for (t = 0; t < z.length; ++t) { rng_pool[rng_pptr++] = z[t] & 255; } } // Use mouse events for entropy, if we do not have enough entropy by the time // we need it, entropy will be generated by Math.random. var onMouseMoveListener_1 = function (ev) { this.count = this.count || 0; if (this.count >= 256 || rng_pptr >= rng_psize) { if (window.removeEventListener) { window.removeEventListener("mousemove", onMouseMoveListener_1, false); } else if (window.detachEvent) { window.detachEvent("onmousemove", onMouseMoveListener_1); } return; } try { var mouseCoordinates = ev.x + ev.y; rng_pool[rng_pptr++] = mouseCoordinates & 255; this.count += 1; } catch (e) { // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. } }; if (window.addEventListener) { window.addEventListener("mousemove", onMouseMoveListener_1, false); } else if (window.attachEvent) { window.attachEvent("onmousemove", onMouseMoveListener_1); } } function rng_get_byte() { if (rng_state == null) { rng_state = prng_newstate(); // At this point, we may not have collected enough entropy. If not, fall back to Math.random while (rng_pptr < rng_psize) { var random = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = random & 255; } rng_state.init(rng_pool); for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { rng_pool[rng_pptr] = 0; } rng_pptr = 0; } // TODO: allow reseeding after first request return rng_state.next(); } var SecureRandom = /** @class */ (function () { function SecureRandom() { } SecureRandom.prototype.nextBytes = function (ba) { for (var i = 0; i < ba.length; ++i) { ba[i] = rng_get_byte(); } }; return SecureRandom; }()); // Depends on jsbn.js and rng.js // function linebrk(s,n) { // var ret = ""; // var i = 0; // while(i + n < s.length) { // ret += s.substring(i,i+n) + "\n"; // i += n; // } // return ret + s.substring(i,s.length); // } // function byte2Hex(b) { // if(b < 0x10) // return "0" + b.toString(16); // else // return b.toString(16); // } function pkcs1pad1(s, n) { if (n < s.length + 22) { console.error("Message too long for RSA"); return null; } var len = n - s.length - 6; var filler = ""; for (var f = 0; f < len; f += 2) { filler += "ff"; } var m = "0001" + filler + "00" + s; return parseBigInt(m, 16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s, n) { if (n < s.length + 11) { // TODO: fix for utf-8 console.error("Message too long for RSA"); return null; } var ba = []; var i = s.length - 1; while (i >= 0 && n > 0) { var c = s.charCodeAt(i--); if (c < 128) { // encode using utf-8 ba[--n] = c; } else if ((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new SecureRandom(); var x = []; while (n > 2) { // random non-zero pad x[0] = 0; while (x[0] == 0) { rng.nextBytes(x); } ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor var RSAKey = /** @class */ (function () { function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } //#region PROTECTED // protected // RSAKey.prototype.doPublic = RSADoPublic; // Perform raw public operation on "x": return x^e (mod n) RSAKey.prototype.doPublic = function (x) { return x.modPowInt(this.e, this.n); }; // RSAKey.prototype.doPrivate = RSADoPrivate; // Perform raw private operation on "x": return x^d (mod n) RSAKey.prototype.doPrivate = function (x) { if (this.p == null || this.q == null) { return x.modPow(this.d, this.n); } // TODO: re-calculate any missing CRT params var xp = x.mod(this.p).modPow(this.dmp1, this.p); var xq = x.mod(this.q).modPow(this.dmq1, this.q); while (xp.compareTo(xq) < 0) { xp = xp.add(this.p); } return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); }; //#endregion PROTECTED //#region PUBLIC // RSAKey.prototype.setPublic = RSASetPublic; // Set the public key fields N and e from hex strings RSAKey.prototype.setPublic = function (N, E) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); } else { console.error("Invalid RSA public key"); } }; // RSAKey.prototype.encrypt = RSAEncrypt; // Return the PKCS#1 RSA encryption of "text" as an even-length hex string RSAKey.prototype.encrypt = function (text) { var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); if (m == null) { return null; } var c = this.doPublic(m); if (c == null) { return null; } var h = c.toString(16); if ((h.length & 1) == 0) { return h; } else { return "0" + h; } }; // RSAKey.prototype.setPrivate = RSASetPrivate; // Set the private key fields N, e, and d from hex strings RSAKey.prototype.setPrivate = function (N, E, D) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); } else { console.error("Invalid RSA private key"); } }; // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; // Set the private key fields N, e, d and CRT params from hex strings RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); this.p = parseBigInt(P, 16); this.q = parseBigInt(Q, 16); this.dmp1 = parseBigInt(DP, 16); this.dmq1 = parseBigInt(DQ, 16); this.coeff = parseBigInt(C, 16); } else { console.error("Invalid RSA private key"); } }; // RSAKey.prototype.generate = RSAGenerate; // Generate a new random private key B bits long, using public expt E RSAKey.prototype.generate = function (B, E) { var rng = new SecureRandom(); var qs = B >> 1; this.e = parseInt(E, 16); var ee = new BigInteger(E, 16); for (;;) { for (;;) { this.p = new BigInteger(B - qs, 1, rng); if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) { break; } } for (;;) { this.q = new BigInteger(qs, 1, rng); if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) { break; } } if (this.p.compareTo(this.q) <= 0) { var t = this.p; this.p = this.q; this.q = t; } var p1 = this.p.subtract(BigInteger.ONE); var q1 = this.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } }; // RSAKey.prototype.decrypt = RSADecrypt; // Return the PKCS#1 RSA decryption of "ctext". // "ctext" is an even-length hex string and the output is a plain string. RSAKey.prototype.decrypt = function (ctext) { var c = parseBigInt(ctext, 16); var m = this.doPrivate(c); if (m == null) { return null; } return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); }; // Generate a new random private key B bits long, using public expt E RSAKey.prototype.generateAsync = function (B, E, callback) { var rng = new SecureRandom(); var qs = B >> 1; this.e = parseInt(E, 16); var ee = new BigInteger(E, 16); var rsa = this; // These functions have non-descript names because they were originally for(;;) loops. // I don't know about cryptography to give them better names than loop1-4. var loop1 = function () { var loop4 = function () { if (rsa.p.compareTo(rsa.q) <= 0) { var t = rsa.p; rsa.p = rsa.q; rsa.q = t; } var p1 = rsa.p.subtract(BigInteger.ONE); var q1 = rsa.q.subtract(BigInteger.ONE); var phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { rsa.n = rsa.p.multiply(rsa.q); rsa.d = ee.modInverse(phi); rsa.dmp1 = rsa.d.mod(p1); rsa.dmq1 = rsa.d.mod(q1); rsa.coeff = rsa.q.modInverse(rsa.p); setTimeout(function () { callback(); }, 0); // escape } else { setTimeout(loop1, 0); } }; var loop3 = function () { rsa.q = nbi(); rsa.q.fromNumberAsync(qs, 1, rng, function () { rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) { if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) { setTimeout(loop4, 0); } else { setTimeout(loop3, 0); } }); }); }; var loop2 = function () { rsa.p = nbi(); rsa.p.fromNumberAsync(B - qs, 1, rng, function () { rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) { if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) { setTimeout(loop3, 0); } else { setTimeout(loop2, 0); } }); }); }; setTimeout(loop2, 0); }; setTimeout(loop1, 0); }; RSAKey.prototype.sign = function (text, digestMethod, digestName) { var header = getDigestHeader(digestName); var digest = header + digestMethod(text).toString(); var m = pkcs1pad1(digest, this.n.bitLength() / 4); if (m == null) { return null; } var c = this.doPrivate(m); if (c == null) { return null; } var h = c.toString(16); if ((h.length & 1) == 0) { return h; } else { return "0" + h; } }; RSAKey.prototype.verify = function (text, signature, digestMethod) { var c = parseBigInt(signature, 16); var m = this.doPublic(c); if (m == null) { return null; } var unpadded = m.toString(16).replace(/^1f+00/, ""); var digest = removeDigestHeader(unpadded); return digest == digestMethod(text).toString(); }; return RSAKey; }()); // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext function pkcs1unpad2(d, n) { var b = d.toByteArray(); var i = 0; while (i < b.length && b[i] == 0) { ++i; } if (b.length - i != n - 1 || b[i] != 2) { return null; } ++i; while (b[i] != 0) { if (++i >= b.length) { return null; } } var ret = ""; while (++i < b.length) { var c = b[i] & 255; if (c < 128) { // utf-8 decode ret += String.fromCharCode(c); } else if ((c > 191) && (c < 224)) { ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63)); ++i; } else { ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)); i += 2; } } return ret; } // https://tools.ietf.org/html/rfc3447#page-43 var DIGEST_HEADERS = { md2: "3020300c06082a864886f70d020205000410", md5: "3020300c06082a864886f70d020505000410", sha1: "3021300906052b0e03021a05000414", sha224: "302d300d06096086480165030402040500041c", sha256: "3031300d060960864801650304020105000420", sha384: "3041300d060960864801650304020205000430", sha512: "3051300d060960864801650304020305000440", ripemd160: "3021300906052b2403020105000414", }; function getDigestHeader(name) { return DIGEST_HEADERS[name] || ""; } function removeDigestHeader(str) { for (var name_1 in DIGEST_HEADERS) { if (DIGEST_HEADERS.hasOwnProperty(name_1)) { var header = DIGEST_HEADERS[name_1]; var len = header.length; if (str.substr(0, len) == header) { return str.substr(len); } } } return str; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string // function RSAEncryptB64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; // } // public // RSAKey.prototype.encrypt_b64 = RSAEncryptB64; /*! Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ var YAHOO = {}; YAHOO.lang = { /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @static * @param {Function} subc the object to modify * @param {Function} superc the object to inherit * @param {Object} overrides additional properties/methods to add to the * subclass prototype. These will override the * matching items obtained from the superclass * if present. */ extend: function(subc, superc, overrides) { if (! superc || ! subc) { throw new Error("YAHOO.lang.extend failed, please check that " + "all dependencies are included."); } var F = function() {}; F.prototype = superc.prototype; subc.prototype = new F(); subc.prototype.constructor = subc; subc.superclass = superc.prototype; if (superc.prototype.constructor == Object.prototype.constructor) { superc.prototype.constructor = superc; } if (overrides) { var i; for (i in overrides) { subc.prototype[i] = overrides[i]; } /* * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _IEEnumFix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @static * @private */ var _IEEnumFix = function() {}, ADD = ["toString", "valueOf"]; try { if (/MSIE/.test(navigator.userAgent)) { _IEEnumFix = function(r, s) { for (i = 0; i < ADD.length; i = i + 1) { var fname = ADD[i], f = s[fname]; if (typeof f === 'function' && f != Object.prototype[fname]) { r[fname] = f; } } }; } } catch (ex) {} _IEEnumFix(subc.prototype, overrides); } } }; /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license */ /** * @fileOverview * @name asn1-1.0.js * @author Kenji Urushima kenji.urushima@gmail.com * @version asn1 1.0.13 (2017-Jun-02) * @since jsrsasign 2.1 * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a> */ /** * kjur's class library name space * <p> * This name space provides following name spaces: * <ul> * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li> * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li> * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature * class and utilities</li> * </ul> * </p> * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. * @name KJUR * @namespace kjur's class library name space */ var KJUR = {}; /** * kjur's ASN.1 class library name space * <p> * This is ITU-T X.690 ASN.1 DER encoder class library and * class structure and methods is very similar to * org.bouncycastle.asn1 package of * well known BouncyCaslte Cryptography Library. * <h4>PROVIDING ASN.1 PRIMITIVES</h4> * Here are ASN.1 DER primitive classes. * <ul> * <li>0x01 {@link KJUR.asn1.DERBoolean}</li> * <li>0x02 {@link KJUR.asn1.DERInteger}</li> * <li>0x03 {@link KJUR.asn1.DERBitString}</li> * <li>0x04 {@link KJUR.asn1.DEROctetString}</li> * <li>0x05 {@link KJUR.asn1.DERNull}</li> * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li> * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li> * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li> * <li>0x12 {@link KJUR.asn1.DERNumericString}</li> * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li> * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li> * <li>0x16 {@link KJUR.asn1.DERIA5String}</li> * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li> * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li> * <li>0x30 {@link KJUR.asn1.DERSequence}</li> * <li>0x31 {@link KJUR.asn1.DERSet}</li> * </ul> * <h4>OTHER ASN.1 CLASSES</h4> * <ul> * <li>{@link KJUR.asn1.ASN1Object}</li> * <li>{@link KJUR.asn1.DERAbstractString}</li> * <li>{@link KJUR.asn1.DERAbstractTime}</li> * <li>{@link KJUR.asn1.DERAbstractStructured}</li> * <li>{@link KJUR.asn1.DERTaggedObject}</li> * </ul> * <h4>SUB NAME SPACES</h4> * <ul> * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li> * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li> * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li> * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li> * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li> * </ul> * </p> * NOTE: Please ignore method summary and document of this namespace. * This caused by a bug of jsdoc2. * @name KJUR.asn1 * @namespace */ if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; /** * ASN1 utilities class * @name KJUR.asn1.ASN1Util * @class ASN1 utilities class * @since asn1 1.0.2 */ KJUR.asn1.ASN1Util = new function() { this.integerToByteHex = function(i) { var h = i.toString(16); if ((h.length % 2) == 1) h = '0' + h; return h; }; this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { var h = bigIntegerValue.toString(16); if (h.substr(0, 1) != '-') { if (h.length % 2 == 1) { h = '0' + h; } else { if (! h.match(/^[0-7]/)) { h = '00' + h; } } } else { var hPos = h.substr(1); var xorLen = hPos.length; if (xorLen % 2 == 1) { xorLen += 1; } else { if (! h.match(/^[0-7]/)) { xorLen += 2; } } var hMask = ''; for (var i = 0; i < xorLen; i++) { hMask += 'f'; } var biMask = new BigInteger(hMask, 16); var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); h = biNeg.toString(16).replace(/^-/, ''); } return h; }; /** * get PEM string from hexadecimal data and header string * @name getPEMStringFromHex * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} dataHex hexadecimal string of PEM body * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') * @return {String} PEM formatted string of input data * @description * This method converts a hexadecimal string to a PEM string with * a specified header. Its line break will be CRLF("\r\n"). * @example * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); * // value of pem will be: * -----BEGIN PRIVATE KEY----- * YWFh * -----END PRIVATE KEY----- */ this.getPEMStringFromHex = function(dataHex, pemHeader) { return hextopem(dataHex, pemHeader); }; /** * generate ASN1Object specifed by JSON parameters * @name newObject * @memberOf KJUR.asn1.ASN1Util * @function * @param {Array} param JSON parameter to generate ASN1Object * @return {KJUR.asn1.ASN1Object} generated object * @since asn1 1.0.3 * @description * generate any ASN1Object specified by JSON param * including ASN.1 primitive or structured. * Generally 'param' can be described as follows: * <blockquote> * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} * </blockquote> * 'TYPE-OF-ASN1OBJ' can be one of following symbols: * <ul> * <li>'bool' - DERBoolean</li> * <li>'int' - DERInteger</li> * <li>'bitstr' - DERBitString</li> * <li>'octstr' - DEROctetString</li> * <li>'null' - DERNull</li> * <li>'oid' - DERObjectIdentifier</li> * <li>'enum' - DEREnumerated</li> * <li>'utf8str' - DERUTF8String</li> * <li>'numstr' - DERNumericString</li> * <li>'prnstr' - DERPrintableString</li> * <li>'telstr' - DERTeletexString</li> * <li>'ia5str' - DERIA5String</li> * <li>'utctime' - DERUTCTime</li> * <li>'gentime' - DERGeneralizedTime</li> * <li>'seq' - DERSequence</li> * <li>'set' - DERSet</li> * <li>'tag' - DERTaggedObject</li> * </ul> * @example * newObject({'prnstr': 'aaa'}); * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) * // ASN.1 Tagged Object * newObject({'tag': {'tag': 'a1', * 'explicit': true, * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); * // more simple representation of ASN.1 Tagged Object * newObject({'tag': ['a1', * true, * {'seq': [ * {'int': 3}, * {'prnstr': 'aaa'}]} * ]}); */ this.newObject = function(param) { var _KJUR = KJUR, _KJUR_asn1 = _KJUR.asn1, _DERBoolean = _KJUR_asn1.DERBoolean, _DERInteger = _KJUR_asn1.DERInteger, _DERBitString = _KJUR_asn1.DERBitString, _DEROctetString = _KJUR_asn1.DEROctetString, _DERNull = _KJUR_asn1.DERNull, _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, _DEREnumerated = _KJUR_asn1.DEREnumerated, _DERUTF8String = _KJUR_asn1.DERUTF8String, _DERNumericString = _KJUR_asn1.DERNumericString, _DERPrintableString = _KJUR_asn1.DERPrintableString, _DERTeletexString = _KJUR_asn1.DERTeletexString, _DERIA5String = _KJUR_asn1.DERIA5String, _DERUTCTime = _KJUR_asn1.DERUTCTime, _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, _DERSequence = _KJUR_asn1.DERSequence, _DERSet = _KJUR_asn1.DERSet, _DERTaggedObject = _KJUR_asn1.DERTaggedObject, _newObject = _KJUR_asn1.ASN1Util.newObject; var keys = Object.keys(param); if (keys.length != 1) throw "key of param shall be only one."; var key = keys[0]; if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1) throw "undefined key: " + key; if (key == "bool") return new _DERBoolean(param[key]); if (key == "int") return new _DERInteger(param[key]); if (key == "bitstr") return new _DERBitString(param[key]); if (key == "octstr") return new _DEROctetString(param[key]); if (key == "null") return new _DERNull(param[key]); if (key == "oid") return new _DERObjectIdentifier(param[key]); if (key == "enum") return new _DEREnumerated(param[key]); if (key == "utf8str") return new _DERUTF8String(param[key]); if (key == "numstr") return new _DERNumericString(param[key]); if (key == "prnstr") return new _DERPrintableString(param[key]); if (key == "telstr") return new _DERTeletexString(param[key]); if (key == "ia5str") return new _DERIA5String(param[key]); if (key == "utctime") return new _DERUTCTime(param[key]); if (key == "gentime") return new _DERGeneralizedTime(param[key]); if (key == "seq") { var paramList = param[key]; var a = []; for (var i = 0; i < paramList.length; i++) { var asn1Obj = _newObject(paramList[i]); a.push(asn1Obj); } return new _DERSequence({'array': a}); } if (key == "set") { var paramList = param[key]; var a = []; for (var i = 0; i < paramList.length; i++) { var asn1Obj = _newObject(paramList[i]); a.push(asn1Obj); } return new _DERSet({'array': a}); } if (key == "tag") { var tagParam = param[key]; if (Object.prototype.toString.call(tagParam) === '[object Array]' && tagParam.length == 3) { var obj = _newObject(tagParam[2]); return new _DERTaggedObject({tag: tagParam[0], explicit: tagParam[1], obj: obj}); } else { var newParam = {}; if (tagParam.explicit !== undefined) newParam.explicit = tagParam.explicit; if (tagParam.tag !== undefined) newParam.tag = tagParam.tag; if (tagParam.obj === undefined) throw "obj shall be specified for 'tag'."; newParam.obj = _newObject(tagParam.obj); return new _DERTaggedObject(newParam); } } }; /** * get encoded hexadecimal string of ASN1Object specifed by JSON parameters * @name jsonToASN1HEX * @memberOf KJUR.asn1.ASN1Util * @function * @param {Array} param JSON parameter to generate ASN1Object * @return hexadecimal string of ASN1Object * @since asn1 1.0.4 * @description * As for ASN.1 object representation of JSON object, * please see {@link newObject}. * @example * jsonToASN1HEX({'prnstr': 'aaa'}); */ this.jsonToASN1HEX = function(param) { var asn1Obj = this.newObject(param); return asn1Obj.getEncodedHex(); }; }; /** * get dot noted oid number string from hexadecimal value of OID * @name oidHexToInt * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} hex hexadecimal value of object identifier * @return {String} dot noted string of object identifier * @since jsrsasign 4.8.3 asn1 1.0.7 * @description * This static method converts from hexadecimal string representation of * ASN.1 value of object identifier to oid number string. * @example * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6" */ KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { var s = ""; var i01 = parseInt(hex.substr(0, 2), 16); var i0 = Math.floor(i01 / 40); var i1 = i01 % 40; var s = i0 + "." + i1; var binbuf = ""; for (var i = 2; i < hex.length; i += 2) { var value = parseInt(hex.substr(i, 2), 16); var bin = ("00000000" + value.toString(2)).slice(- 8); binbuf = binbuf + bin.substr(1, 7); if (bin.substr(0, 1) == "0") { var bi = new BigInteger(binbuf, 2); s = s + "." + bi.toString(10); binbuf = ""; } } return s; }; /** * get hexadecimal value of object identifier from dot noted oid value * @name oidIntToHex * @memberOf KJUR.asn1.ASN1Util * @function * @param {String} oidString dot noted string of object identifier * @return {String} hexadecimal value of object identifier * @since jsrsasign 4.8.3 asn1 1.0.7 * @description * This static method converts from object identifier value string. * to hexadecimal string representation of it. * @example * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406" */ KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { var itox = function(i) { var h = i.toString(16); if (h.length == 1) h = '0' + h; return h; }; var roidtox = function(roid) { var h = ''; var bi = new BigInteger(roid, 10); var b = bi.toString(2); var padLen = 7 - b.length % 7; if (padLen == 7) padLen = 0; var bPad = ''; for (var i = 0; i < padLen; i++) bPad += '0'; b = bPad + b; for (var i = 0; i < b.length - 1; i += 7) { var b8 = b.substr(i, 7); if (i != b.length - 7) b8 = '1' + b8; h += itox(parseInt(b8, 2)); } return h; }; if (! oidString.match(/^[0-9.]+$/)) { throw "malformed oid string: " + oidString; } var h = ''; var a = oidString.split('.'); var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); h += itox(i0); a.splice(0, 2); for (var i = 0; i < a.length; i++) { h += roidtox(a[i]); } return h; }; // ******************************************************************** // Abstract ASN.1 Classes // ******************************************************************** // ******************************************************************** /** * base class for ASN.1 DER encoder object * @name KJUR.asn1.ASN1Object * @class base class for ASN.1 DER encoder object * @property {Boolean} isModified flag whether internal data was changed * @property {String} hTLV hexadecimal string of ASN.1 TLV * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) * @property {String} hL hexadecimal string of ASN.1 TLV length(L) * @property {String} hV hexadecimal string of ASN.1 TLV value(V) * @description */ KJUR.asn1.ASN1Object = function() { var hV = ''; /** * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) * @name getLengthHexFromValue * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV length(L) */ this.getLengthHexFromValue = function() { if (typeof this.hV == "undefined" || this.hV == null) { throw "this.hV is null or undefined."; } if (this.hV.length % 2 == 1) { throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; } var n = this.hV.length / 2; var hN = n.toString(16); if (hN.length % 2 == 1) { hN = "0" + hN; } if (n < 128) { return hN; } else { var hNlen = hN.length / 2; if (hNlen > 15) { throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); } var head = 128 + hNlen; return head.toString(16) + hN; } }; /** * get hexadecimal string of ASN.1 TLV bytes * @name getEncodedHex * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV */ this.getEncodedHex = function() { if (this.hTLV == null || this.isModified) { this.hV = this.getFreshValueHex(); this.hL = this.getLengthHexFromValue(); this.hTLV = this.hT + this.hL + this.hV; this.isModified = false; //alert("first time: " + this.hTLV); } return this.hTLV; }; /** * get hexadecimal string of ASN.1 TLV value(V) bytes * @name getValueHex * @memberOf KJUR.asn1.ASN1Object# * @function * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes */ this.getValueHex = function() { this.getEncodedHex(); return this.hV; }; this.getFreshValueHex = function() { return ''; }; }; // == BEGIN DERAbstractString ================================================ /** * base class for ASN.1 DER string classes * @name KJUR.asn1.DERAbstractString * @class base class for ASN.1 DER string classes * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @property {String} s internal string of value * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERAbstractString = function(params) { KJUR.asn1.DERAbstractString.superclass.constructor.call(this); /** * get string value of this string object * @name getString * @memberOf KJUR.asn1.DERAbstractString# * @function * @return {String} string value of this string object */ this.getString = function() { return this.s; }; /** * set value by a string * @name setString * @memberOf KJUR.asn1.DERAbstractString# * @function * @param {String} newS value by a string to set */ this.setString = function(newS) { this.hTLV = null; this.isModified = true; this.s = newS; this.hV = stohex(this.s); }; /** * set value by a hexadecimal string * @name setStringHex * @memberOf KJUR.asn1.DERAbstractString# * @function * @param {String} newHexString value by a hexadecimal string to set */ this.setStringHex = function(newHexString) { this.hTLV = null; this.isModified = true; this.s = null; this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params == "string") { this.setString(params); } else if (typeof params['str'] != "undefined") { this.setString(params['str']); } else if (typeof params['hex'] != "undefined") { this.setStringHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); // == END DERAbstractString ================================================ // == BEGIN DERAbstractTime ================================================== /** * base class for ASN.1 DER Generalized/UTCTime class * @name KJUR.asn1.DERAbstractTime * @class base class for ASN.1 DER Generalized/UTCTime class * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERAbstractTime = function(params) { KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); // --- PRIVATE METHODS -------------------- this.localDateToUTC = function(d) { utc = d.getTime() + (d.getTimezoneOffset() * 60000); var utcDate = new Date(utc); return utcDate; }; /* * format date string by Data object * @name formatDate * @memberOf KJUR.asn1.AbstractTime; * @param {Date} dateObject * @param {string} type 'utc' or 'gen' * @param {boolean} withMillis flag for with millisections or not * @description * 'withMillis' flag is supported from asn1 1.0.6. */ this.formatDate = function(dateObject, type, withMillis) { var pad = this.zeroPadding; var d = this.localDateToUTC(dateObject); var year = String(d.getFullYear()); if (type == 'utc') year = year.substr(2, 2); var month = pad(String(d.getMonth() + 1), 2); var day = pad(String(d.getDate()), 2); var hour = pad(String(d.getHours()), 2); var min = pad(String(d.getMinutes()), 2); var sec = pad(String(d.getSeconds()), 2); var s = year + month + day + hour + min + sec; if (withMillis === true) { var millis = d.getMilliseconds(); if (millis != 0) { var sMillis = pad(String(millis), 3); sMillis = sMillis.replace(/[0]+$/, ""); s = s + "." + sMillis; } } return s + "Z"; }; this.zeroPadding = function(s, len) { if (s.length >= len) return s; return new Array(len - s.length + 1).join('0') + s; }; // --- PUBLIC METHODS -------------------- /** * get string value of this string object * @name getString * @memberOf KJUR.asn1.DERAbstractTime# * @function * @return {String} string value of this time object */ this.getString = function() { return this.s; }; /** * set value by a string * @name setString * @memberOf KJUR.asn1.DERAbstractTime# * @function * @param {String} newS value by a string to set such like "130430235959Z" */ this.setString = function(newS) { this.hTLV = null; this.isModified = true; this.s = newS; this.hV = stohex(newS); }; /** * set value by a Date object * @name setByDateValue * @memberOf KJUR.asn1.DERAbstractTime# * @function * @param {Integer} year year of date (ex. 2013) * @param {Integer} month month of date between 1 and 12 (ex. 12) * @param {Integer} day day of month * @param {Integer} hour hours of date * @param {Integer} min minutes of date * @param {Integer} sec seconds of date */ this.setByDateValue = function(year, month, day, hour, min, sec) { var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); this.setByDate(dateObject); }; this.getFreshValueHex = function() { return this.hV; }; }; YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); // == END DERAbstractTime ================================================== // == BEGIN DERAbstractStructured ============================================ /** * base class for ASN.1 DER structured class * @name KJUR.asn1.DERAbstractStructured * @class base class for ASN.1 DER structured class * @property {Array} asn1Array internal array of ASN1Object * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERAbstractStructured = function(params) { KJUR.asn1.DERAbstractString.superclass.constructor.call(this); /** * set value by array of ASN1Object * @name setByASN1ObjectArray * @memberOf KJUR.asn1.DERAbstractStructured# * @function * @param {array} asn1ObjectArray array of ASN1Object to set */ this.setByASN1ObjectArray = function(asn1ObjectArray) { this.hTLV = null; this.isModified = true; this.asn1Array = asn1ObjectArray; }; /** * append an ASN1Object to internal array * @name appendASN1Object * @memberOf KJUR.asn1.DERAbstractStructured# * @function * @param {ASN1Object} asn1Object to add */ this.appendASN1Object = function(asn1Object) { this.hTLV = null; this.isModified = true; this.asn1Array.push(asn1Object); }; this.asn1Array = new Array(); if (typeof params != "undefined") { if (typeof params['array'] != "undefined") { this.asn1Array = params['array']; } } }; YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); // ******************************************************************** // ASN.1 Object Classes // ******************************************************************** // ******************************************************************** /** * class for ASN.1 DER Boolean * @name KJUR.asn1.DERBoolean * @class class for ASN.1 DER Boolean * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERBoolean = function() { KJUR.asn1.DERBoolean.superclass.constructor.call(this); this.hT = "01"; this.hTLV = "0101ff"; }; YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER Integer * @name KJUR.asn1.DERInteger * @class class for ASN.1 DER Integer * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>int - specify initial ASN.1 value(V) by integer value</li> * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERInteger = function(params) { KJUR.asn1.DERInteger.superclass.constructor.call(this); this.hT = "02"; /** * set value by Tom Wu's BigInteger object * @name setByBigInteger * @memberOf KJUR.asn1.DERInteger# * @function * @param {BigInteger} bigIntegerValue to set */ this.setByBigInteger = function(bigIntegerValue) { this.hTLV = null; this.isModified = true; this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); }; /** * set value by integer value * @name setByInteger * @memberOf KJUR.asn1.DERInteger * @function * @param {Integer} integer value to set */ this.setByInteger = function(intValue) { var bi = new BigInteger(String(intValue), 10); this.setByBigInteger(bi); }; /** * set value by integer value * @name setValueHex * @memberOf KJUR.asn1.DERInteger# * @function * @param {String} hexadecimal string of integer value * @description * <br/> * NOTE: Value shall be represented by minimum octet length of * two's complement representation. * @example * new KJUR.asn1.DERInteger(123); * new KJUR.asn1.DERInteger({'int': 123}); * new KJUR.asn1.DERInteger({'hex': '1fad'}); */ this.setValueHex = function(newHexString) { this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['bigint'] != "undefined") { this.setByBigInteger(params['bigint']); } else if (typeof params['int'] != "undefined") { this.setByInteger(params['int']); } else if (typeof params == "number") { this.setByInteger(params); } else if (typeof params['hex'] != "undefined") { this.setValueHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER encoded BitString primitive * @name KJUR.asn1.DERBitString * @class class for ASN.1 DER encoded BitString primitive * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>bin - specify binary string (ex. '10111')</li> * <li>array - specify array of boolean (ex. [true,false,true,true])</li> * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li> * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject} * argument for "BitString encapsulates" structure.</li> * </ul> * NOTE1: 'params' can be omitted.<br/> * NOTE2: 'obj' parameter have been supported since * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/> * @example * // default constructor * o = new KJUR.asn1.DERBitString(); * // initialize with binary string * o = new KJUR.asn1.DERBitString({bin: "1011"}); * // initialize with boolean array * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); * // initialize with hexadecimal string (04 is unused bits) * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); * // initialize with ASN1Util.newObject argument for encapsulated * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); * // above generates a ASN.1 data like this: * // BIT STRING, encapsulates { * // SEQUENCE { * // INTEGER 3 * // PrintableString 'aaa' * // } * // } */ KJUR.asn1.DERBitString = function(params) { if (params !== undefined && typeof params.obj !== "undefined") { var o = KJUR.asn1.ASN1Util.newObject(params.obj); params.hex = "00" + o.getEncodedHex(); } KJUR.asn1.DERBitString.superclass.constructor.call(this); this.hT = "03"; /** * set ASN.1 value(V) by a hexadecimal string including unused bits * @name setHexValueIncludingUnusedBits * @memberOf KJUR.asn1.DERBitString# * @function * @param {String} newHexStringIncludingUnusedBits */ this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { this.hTLV = null; this.isModified = true; this.hV = newHexStringIncludingUnusedBits; }; /** * set ASN.1 value(V) by unused bit and hexadecimal string of value * @name setUnusedBitsAndHexValue * @memberOf KJUR.asn1.DERBitString# * @function * @param {Integer} unusedBits * @param {String} hValue */ this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { if (unusedBits < 0 || 7 < unusedBits) { throw "unused bits shall be from 0 to 7: u = " + unusedBits; } var hUnusedBits = "0" + unusedBits; this.hTLV = null; this.isModified = true; this.hV = hUnusedBits + hValue; }; /** * set ASN.1 DER BitString by binary string<br/> * @name setByBinaryString * @memberOf KJUR.asn1.DERBitString# * @function * @param {String} binaryString binary value string (i.e. '10111') * @description * Its unused bits will be calculated automatically by length of * 'binaryValue'. <br/> * NOTE: Trailing zeros '0' will be ignored. * @example * o = new KJUR.asn1.DERBitString(); * o.setByBooleanArray("01011"); */ this.setByBinaryString = function(binaryString) { binaryString = binaryString.replace(/0+$/, ''); var unusedBits = 8 - binaryString.length % 8; if (unusedBits == 8) unusedBits = 0; for (var i = 0; i <= unusedBits; i++) { binaryString += '0'; } var h = ''; for (var i = 0; i < binaryString.length - 1; i += 8) { var b = binaryString.substr(i, 8); var x = parseInt(b, 2).toString(16); if (x.length == 1) x = '0' + x; h += x; } this.hTLV = null; this.isModified = true; this.hV = '0' + unusedBits + h; }; /** * set ASN.1 TLV value(V) by an array of boolean<br/> * @name setByBooleanArray * @memberOf KJUR.asn1.DERBitString# * @function * @param {array} booleanArray array of boolean (ex. [true, false, true]) * @description * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. * @example * o = new KJUR.asn1.DERBitString(); * o.setByBooleanArray([false, true, false, true, true]); */ this.setByBooleanArray = function(booleanArray) { var s = ''; for (var i = 0; i < booleanArray.length; i++) { if (booleanArray[i] == true) { s += '1'; } else { s += '0'; } } this.setByBinaryString(s); }; /** * generate an array of falses with specified length<br/> * @name newFalseArray * @memberOf KJUR.asn1.DERBitString * @function * @param {Integer} nLength length of array to generate * @return {array} array of boolean falses * @description * This static method may be useful to initialize boolean array. * @example * o = new KJUR.asn1.DERBitString(); * o.newFalseArray(3) &rarr; [false, false, false] */ this.newFalseArray = function(nLength) { var a = new Array(nLength); for (var i = 0; i < nLength; i++) { a[i] = false; } return a; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { this.setHexValueIncludingUnusedBits(params); } else if (typeof params['hex'] != "undefined") { this.setHexValueIncludingUnusedBits(params['hex']); } else if (typeof params['bin'] != "undefined") { this.setByBinaryString(params['bin']); } else if (typeof params['array'] != "undefined") { this.setByBooleanArray(params['array']); } } }; YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER OctetString<br/> * @name KJUR.asn1.DEROctetString * @class class for ASN.1 DER OctetString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * This class provides ASN.1 OctetString simple type.<br/> * Supported "params" attributes are: * <ul> * <li>str - to set a string as a value</li> * <li>hex - to set a hexadecimal string as a value</li> * <li>obj - to set a encapsulated ASN.1 value by JSON object * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li> * </ul> * NOTE: A parameter 'obj' have been supported * for "OCTET STRING, encapsulates" structure. * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). * @see KJUR.asn1.DERAbstractString - superclass * @example * // default constructor * o = new KJUR.asn1.DEROctetString(); * // initialize with string * o = new KJUR.asn1.DEROctetString({str: "aaa"}); * // initialize with hexadecimal string * o = new KJUR.asn1.DEROctetString({hex: "616161"}); * // initialize with ASN1Util.newObject argument * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); * // above generates a ASN.1 data like this: * // OCTET STRING, encapsulates { * // SEQUENCE { * // INTEGER 3 * // PrintableString 'aaa' * // } * // } */ KJUR.asn1.DEROctetString = function(params) { if (params !== undefined && typeof params.obj !== "undefined") { var o = KJUR.asn1.ASN1Util.newObject(params.obj); params.hex = o.getEncodedHex(); } KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); this.hT = "04"; }; YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER Null * @name KJUR.asn1.DERNull * @class class for ASN.1 DER Null * @extends KJUR.asn1.ASN1Object * @description * @see KJUR.asn1.ASN1Object - superclass */ KJUR.asn1.DERNull = function() { KJUR.asn1.DERNull.superclass.constructor.call(this); this.hT = "05"; this.hTLV = "0500"; }; YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER ObjectIdentifier * @name KJUR.asn1.DERObjectIdentifier * @class class for ASN.1 DER ObjectIdentifier * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERObjectIdentifier = function(params) { var itox = function(i) { var h = i.toString(16); if (h.length == 1) h = '0' + h; return h; }; var roidtox = function(roid) { var h = ''; var bi = new BigInteger(roid, 10); var b = bi.toString(2); var padLen = 7 - b.length % 7; if (padLen == 7) padLen = 0; var bPad = ''; for (var i = 0; i < padLen; i++) bPad += '0'; b = bPad + b; for (var i = 0; i < b.length - 1; i += 7) { var b8 = b.substr(i, 7); if (i != b.length - 7) b8 = '1' + b8; h += itox(parseInt(b8, 2)); } return h; }; KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this); this.hT = "06"; /** * set value by a hexadecimal string * @name setValueHex * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} newHexString hexadecimal value of OID bytes */ this.setValueHex = function(newHexString) { this.hTLV = null; this.isModified = true; this.s = null; this.hV = newHexString; }; /** * set value by a OID string<br/> * @name setValueOidString * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} oidString OID string (ex. 2.5.4.13) * @example * o = new KJUR.asn1.DERObjectIdentifier(); * o.setValueOidString("2.5.4.13"); */ this.setValueOidString = function(oidString) { if (! oidString.match(/^[0-9.]+$/)) { throw "malformed oid string: " + oidString; } var h = ''; var a = oidString.split('.'); var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); h += itox(i0); a.splice(0, 2); for (var i = 0; i < a.length; i++) { h += roidtox(a[i]); } this.hTLV = null; this.isModified = true; this.s = null; this.hV = h; }; /** * set value by a OID name * @name setValueName * @memberOf KJUR.asn1.DERObjectIdentifier# * @function * @param {String} oidName OID name (ex. 'serverAuth') * @since 1.0.1 * @description * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. * Otherwise raise error. * @example * o = new KJUR.asn1.DERObjectIdentifier(); * o.setValueName("serverAuth"); */ this.setValueName = function(oidName) { var oid = KJUR.asn1.x509.OID.name2oid(oidName); if (oid !== '') { this.setValueOidString(oid); } else { throw "DERObjectIdentifier oidName undefined: " + oidName; } }; this.getFreshValueHex = function() { return this.hV; }; if (params !== undefined) { if (typeof params === "string") { if (params.match(/^[0-2].[0-9.]+$/)) { this.setValueOidString(params); } else { this.setValueName(params); } } else if (params.oid !== undefined) { this.setValueOidString(params.oid); } else if (params.hex !== undefined) { this.setValueHex(params.hex); } else if (params.name !== undefined) { this.setValueName(params.name); } } }; YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER Enumerated * @name KJUR.asn1.DEREnumerated * @class class for ASN.1 DER Enumerated * @extends KJUR.asn1.ASN1Object * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>int - specify initial ASN.1 value(V) by integer value</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * </ul> * NOTE: 'params' can be omitted. * @example * new KJUR.asn1.DEREnumerated(123); * new KJUR.asn1.DEREnumerated({int: 123}); * new KJUR.asn1.DEREnumerated({hex: '1fad'}); */ KJUR.asn1.DEREnumerated = function(params) { KJUR.asn1.DEREnumerated.superclass.constructor.call(this); this.hT = "0a"; /** * set value by Tom Wu's BigInteger object * @name setByBigInteger * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {BigInteger} bigIntegerValue to set */ this.setByBigInteger = function(bigIntegerValue) { this.hTLV = null; this.isModified = true; this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); }; /** * set value by integer value * @name setByInteger * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {Integer} integer value to set */ this.setByInteger = function(intValue) { var bi = new BigInteger(String(intValue), 10); this.setByBigInteger(bi); }; /** * set value by integer value * @name setValueHex * @memberOf KJUR.asn1.DEREnumerated# * @function * @param {String} hexadecimal string of integer value * @description * <br/> * NOTE: Value shall be represented by minimum octet length of * two's complement representation. */ this.setValueHex = function(newHexString) { this.hV = newHexString; }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['int'] != "undefined") { this.setByInteger(params['int']); } else if (typeof params == "number") { this.setByInteger(params); } else if (typeof params['hex'] != "undefined") { this.setValueHex(params['hex']); } } }; YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); // ******************************************************************** /** * class for ASN.1 DER UTF8String * @name KJUR.asn1.DERUTF8String * @class class for ASN.1 DER UTF8String * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERUTF8String = function(params) { KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); this.hT = "0c"; }; YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER NumericString * @name KJUR.asn1.DERNumericString * @class class for ASN.1 DER NumericString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERNumericString = function(params) { KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); this.hT = "12"; }; YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER PrintableString * @name KJUR.asn1.DERPrintableString * @class class for ASN.1 DER PrintableString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERPrintableString = function(params) { KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); this.hT = "13"; }; YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER TeletexString * @name KJUR.asn1.DERTeletexString * @class class for ASN.1 DER TeletexString * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERTeletexString = function(params) { KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); this.hT = "14"; }; YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER IA5String * @name KJUR.asn1.DERIA5String * @class class for ASN.1 DER IA5String * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) * @extends KJUR.asn1.DERAbstractString * @description * @see KJUR.asn1.DERAbstractString - superclass */ KJUR.asn1.DERIA5String = function(params) { KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); this.hT = "16"; }; YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); // ******************************************************************** /** * class for ASN.1 DER UTCTime * @name KJUR.asn1.DERUTCTime * @class class for ASN.1 DER UTCTime * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) * @extends KJUR.asn1.DERAbstractTime * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * <li>date - specify Date object.</li> * </ul> * NOTE: 'params' can be omitted. * <h4>EXAMPLES</h4> * @example * d1 = new KJUR.asn1.DERUTCTime(); * d1.setString('130430125959Z'); * * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); */ KJUR.asn1.DERUTCTime = function(params) { KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); this.hT = "17"; /** * set value by a Date object<br/> * @name setByDate * @memberOf KJUR.asn1.DERUTCTime# * @function * @param {Date} dateObject Date object to set ASN.1 value(V) * @example * o = new KJUR.asn1.DERUTCTime(); * o.setByDate(new Date("2016/12/31")); */ this.setByDate = function(dateObject) { this.hTLV = null; this.isModified = true; this.date = dateObject; this.s = this.formatDate(this.date, 'utc'); this.hV = stohex(this.s); }; this.getFreshValueHex = function() { if (typeof this.date == "undefined" && typeof this.s == "undefined") { this.date = new Date(); this.s = this.formatDate(this.date, 'utc'); this.hV = stohex(this.s); } return this.hV; }; if (params !== undefined) { if (params.str !== undefined) { this.setString(params.str); } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { this.setString(params); } else if (params.hex !== undefined) { this.setStringHex(params.hex); } else if (params.date !== undefined) { this.setByDate(params.date); } } }; YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); // ******************************************************************** /** * class for ASN.1 DER GeneralizedTime * @name KJUR.asn1.DERGeneralizedTime * @class class for ASN.1 DER GeneralizedTime * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) * @property {Boolean} withMillis flag to show milliseconds or not * @extends KJUR.asn1.DERAbstractTime * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li> * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li> * <li>date - specify Date object.</li> * <li>millis - specify flag to show milliseconds (from 1.0.6)</li> * </ul> * NOTE1: 'params' can be omitted. * NOTE2: 'withMillis' property is supported from asn1 1.0.6. */ KJUR.asn1.DERGeneralizedTime = function(params) { KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); this.hT = "18"; this.withMillis = false; /** * set value by a Date object * @name setByDate * @memberOf KJUR.asn1.DERGeneralizedTime# * @function * @param {Date} dateObject Date object to set ASN.1 value(V) * @example * When you specify UTC time, use 'Date.UTC' method like this:<br/> * o1 = new DERUTCTime(); * o1.setByDate(date); * * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 */ this.setByDate = function(dateObject) { this.hTLV = null; this.isModified = true; this.date = dateObject; this.s = this.formatDate(this.date, 'gen', this.withMillis); this.hV = stohex(this.s); }; this.getFreshValueHex = function() { if (this.date === undefined && this.s === undefined) { this.date = new Date(); this.s = this.formatDate(this.date, 'gen', this.withMillis); this.hV = stohex(this.s); } return this.hV; }; if (params !== undefined) { if (params.str !== undefined) { this.setString(params.str); } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { this.setString(params); } else if (params.hex !== undefined) { this.setStringHex(params.hex); } else if (params.date !== undefined) { this.setByDate(params.date); } if (params.millis === true) { this.withMillis = true; } } }; YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); // ******************************************************************** /** * class for ASN.1 DER Sequence * @name KJUR.asn1.DERSequence * @class class for ASN.1 DER Sequence * @extends KJUR.asn1.DERAbstractStructured * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>array - specify array of ASN1Object to set elements of content</li> * </ul> * NOTE: 'params' can be omitted. */ KJUR.asn1.DERSequence = function(params) { KJUR.asn1.DERSequence.superclass.constructor.call(this, params); this.hT = "30"; this.getFreshValueHex = function() { var h = ''; for (var i = 0; i < this.asn1Array.length; i++) { var asn1Obj = this.asn1Array[i]; h += asn1Obj.getEncodedHex(); } this.hV = h; return this.hV; }; }; YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); // ******************************************************************** /** * class for ASN.1 DER Set * @name KJUR.asn1.DERSet * @class class for ASN.1 DER Set * @extends KJUR.asn1.DERAbstractStructured * @description * <br/> * As for argument 'params' for constructor, you can specify one of * following properties: * <ul> * <li>array - specify array of ASN1Object to set elements of content</li> * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li> * </ul> * NOTE1: 'params' can be omitted.<br/> * NOTE2: sortflag is supported since 1.0.5. */ KJUR.asn1.DERSet = function(params) { KJUR.asn1.DERSet.superclass.constructor.call(this, params); this.hT = "31"; this.sortFlag = true; // item shall be sorted only in ASN.1 DER this.getFreshValueHex = function() { var a = new Array(); for (var i = 0; i < this.asn1Array.length; i++) { var asn1Obj = this.asn1Array[i]; a.push(asn1Obj.getEncodedHex()); } if (this.sortFlag == true) a.sort(); this.hV = a.join(''); return this.hV; }; if (typeof params != "undefined") { if (typeof params.sortflag != "undefined" && params.sortflag == false) this.sortFlag = false; } }; YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); // ******************************************************************** /** * class for ASN.1 DER TaggedObject * @name KJUR.asn1.DERTaggedObject * @class class for ASN.1 DER TaggedObject * @extends KJUR.asn1.ASN1Object * @description * <br/> * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object. * For example, if you find '[1]' tag in a ASN.1 dump, * 'tagNoHex' will be 'a1'. * <br/> * As for optional argument 'params' for constructor, you can specify *ANY* of * following properties: * <ul> * <li>explicit - specify true if this is explicit tag otherwise false * (default is 'true').</li> * <li>tag - specify tag (default is 'a0' which means [0])</li> * <li>obj - specify ASN1Object which is tagged</li> * </ul> * @example * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); * hex = d2.getEncodedHex(); */ KJUR.asn1.DERTaggedObject = function(params) { KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); this.hT = "a0"; this.hV = ''; this.isExplicit = true; this.asn1Object = null; /** * set value by an ASN1Object * @name setString * @memberOf KJUR.asn1.DERTaggedObject# * @function * @param {Boolean} isExplicitFlag flag for explicit/implicit tag * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag * @param {ASN1Object} asn1Object ASN.1 to encapsulate */ this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { this.hT = tagNoHex; this.isExplicit = isExplicitFlag; this.asn1Object = asn1Object; if (this.isExplicit) { this.hV = this.asn1Object.getEncodedHex(); this.hTLV = null; this.isModified = true; } else { this.hV = null; this.hTLV = asn1Object.getEncodedHex(); this.hTLV = this.hTLV.replace(/^../, tagNoHex); this.isModified = false; } }; this.getFreshValueHex = function() { return this.hV; }; if (typeof params != "undefined") { if (typeof params['tag'] != "undefined") { this.hT = params['tag']; } if (typeof params['explicit'] != "undefined") { this.isExplicit = params['explicit']; } if (typeof params['obj'] != "undefined") { this.asn1Object = params['obj']; this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); } } }; YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); /** * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. * This object is just a decorator for parsing the key parameter * @param {string|Object} key - The key in string format, or an object containing * the parameters needed to build a RSAKey object. * @constructor */ var JSEncryptRSAKey = /** @class */ (function (_super) { __extends(JSEncryptRSAKey, _super); function JSEncryptRSAKey(key) { var _this = _super.call(this) || this; // Call the super constructor. // RSAKey.call(this); // If a key key was provided. if (key) { // If this is a string... if (typeof key === "string") { _this.parseKey(key); } else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || JSEncryptRSAKey.hasPublicKeyProperty(key)) { // Set the values for the key. _this.parsePropertiesFrom(key); } } return _this; } /** * Method to parse a pem encoded string containing both a public or private key. * The method will translate the pem encoded string in a der encoded string and * will parse private key and public key parameters. This method accepts public key * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). * * @todo Check how many rsa formats use the same format of pkcs #1. * * The format is defined as: * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * it's possible to examine the structure of the keys obtained from openssl using * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer * @private */ JSEncryptRSAKey.prototype.parseKey = function (pem) { try { var modulus = 0; var public_exponent = 0; var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); var asn1 = ASN1.decode(der); // Fixes a bug with OpenSSL 1.0+ private keys if (asn1.sub.length === 3) { asn1 = asn1.sub[2].sub[0]; } if (asn1.sub.length === 9) { // Parse the private key. modulus = asn1.sub[1].getHexStringValue(); // bigint this.n = parseBigInt(modulus, 16); public_exponent = asn1.sub[2].getHexStringValue(); // int this.e = parseInt(public_exponent, 16); var private_exponent = asn1.sub[3].getHexStringValue(); // bigint this.d = parseBigInt(private_exponent, 16); var prime1 = asn1.sub[4].getHexStringValue(); // bigint this.p = parseBigInt(prime1, 16); var prime2 = asn1.sub[5].getHexStringValue(); // bigint this.q = parseBigInt(prime2, 16); var exponent1 = asn1.sub[6].getHexStringValue(); // bigint this.dmp1 = parseBigInt(exponent1, 16); var exponent2 = asn1.sub[7].getHexStringValue(); // bigint this.dmq1 = parseBigInt(exponent2, 16); var coefficient = asn1.sub[8].getHexStringValue(); // bigint this.coeff = parseBigInt(coefficient, 16); } else if (asn1.sub.length === 2) { // Parse the public key. var bit_string = asn1.sub[1]; var sequence = bit_string.sub[0]; modulus = sequence.sub[0].getHexStringValue(); this.n = parseBigInt(modulus, 16); public_exponent = sequence.sub[1].getHexStringValue(); this.e = parseInt(public_exponent, 16); } else { return false; } return true; } catch (ex) { return false; } }; /** * Translate rsa parameters in a hex encoded string representing the rsa key. * * The translation follow the ASN.1 notation : * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * } * @returns {string} DER Encoded String representing the rsa private key * @private */ JSEncryptRSAKey.prototype.getPrivateBaseKey = function () { var options = { array: [ new KJUR.asn1.DERInteger({ int: 0 }), new KJUR.asn1.DERInteger({ bigint: this.n }), new KJUR.asn1.DERInteger({ int: this.e }), new KJUR.asn1.DERInteger({ bigint: this.d }), new KJUR.asn1.DERInteger({ bigint: this.p }), new KJUR.asn1.DERInteger({ bigint: this.q }), new KJUR.asn1.DERInteger({ bigint: this.dmp1 }), new KJUR.asn1.DERInteger({ bigint: this.dmq1 }), new KJUR.asn1.DERInteger({ bigint: this.coeff }) ] }; var seq = new KJUR.asn1.DERSequence(options); return seq.getEncodedHex(); }; /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () { return hex2b64(this.getPrivateBaseKey()); }; /** * Translate rsa parameters in a hex encoded string representing the rsa public key. * The representation follow the ASN.1 notation : * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * @returns {string} DER Encoded String representing the rsa public key * @private */ JSEncryptRSAKey.prototype.getPublicBaseKey = function () { var first_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }), new KJUR.asn1.DERNull() ] }); var second_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERInteger({ bigint: this.n }), new KJUR.asn1.DERInteger({ int: this.e }) ] }); var bit_string = new KJUR.asn1.DERBitString({ hex: "00" + second_sequence.getEncodedHex() }); var seq = new KJUR.asn1.DERSequence({ array: [ first_sequence, bit_string ] }); return seq.getEncodedHex(); }; /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () { return hex2b64(this.getPublicBaseKey()); }; /** * wrap the string in block of width chars. The default value for rsa keys is 64 * characters. * @param {string} str the pem encoded string without header and footer * @param {Number} [width=64] - the length the string has to be wrapped at * @returns {string} * @private */ JSEncryptRSAKey.wordwrap = function (str, width) { width = width || 64; if (!str) { return str; } var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; return str.match(RegExp(regex, "g")).join("\n"); }; /** * Retrieve the pem encoded private key * @returns {string} the pem encoded private key with header/footer * @public */ JSEncryptRSAKey.prototype.getPrivateKey = function () { var key = "-----BEGIN RSA PRIVATE KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; key += "-----END RSA PRIVATE KEY-----"; return key; }; /** * Retrieve the pem encoded public key * @returns {string} the pem encoded public key with header/footer * @public */ JSEncryptRSAKey.prototype.getPublicKey = function () { var key = "-----BEGIN PUBLIC KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; key += "-----END PUBLIC KEY-----"; return key; }; /** * Check if the object contains the necessary parameters to populate the rsa modulus * and public exponent parameters. * @param {Object} [obj={}] - An object that may contain the two public key * parameters * @returns {boolean} true if the object contains both the modulus and the public exponent * properties (n and e) * @todo check for types of n and e. N should be a parseable bigInt object, E should * be a parseable integer number * @private */ JSEncryptRSAKey.hasPublicKeyProperty = function (obj) { obj = obj || {}; return (obj.hasOwnProperty("n") && obj.hasOwnProperty("e")); }; /** * Check if the object contains ALL the parameters of an RSA key. * @param {Object} [obj={}] - An object that may contain nine rsa key * parameters * @returns {boolean} true if the object contains all the parameters needed * @todo check for types of the parameters all the parameters but the public exponent * should be parseable bigint objects, the public exponent should be a parseable integer number * @private */ JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) { obj = obj || {}; return (obj.hasOwnProperty("n") && obj.hasOwnProperty("e") && obj.hasOwnProperty("d") && obj.hasOwnProperty("p") && obj.hasOwnProperty("q") && obj.hasOwnProperty("dmp1") && obj.hasOwnProperty("dmq1") && obj.hasOwnProperty("coeff")); }; /** * Parse the properties of obj in the current rsa object. Obj should AT LEAST * include the modulus and public exponent (n, e) parameters. * @param {Object} obj - the object containing rsa parameters * @private */ JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) { this.n = obj.n; this.e = obj.e; if (obj.hasOwnProperty("d")) { this.d = obj.d; this.p = obj.p; this.q = obj.q; this.dmp1 = obj.dmp1; this.dmq1 = obj.dmq1; this.coeff = obj.coeff; } }; return JSEncryptRSAKey; }(RSAKey)); /** * * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour * possible parameters are: * - default_key_size {number} default: 1024 the key size in bit * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent * - log {boolean} default: false whether log warn/error or not * @constructor */ var JSEncrypt = /** @class */ (function () { function JSEncrypt(options) { options = options || {}; this.default_key_size = parseInt(options.default_key_size, 10) || 1024; this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type this.log = options.log || false; // The private and public key. this.key = null; } /** * Method to set the rsa key parameter (one method is enough to set both the public * and the private key, since the private key contains the public key paramenters) * Log a warning if logs are enabled * @param {Object|string} key the pem encoded string or an object (with or without header/footer) * @public */ JSEncrypt.prototype.setKey = function (key) { if (this.log && this.key) { console.warn("A key was already set, overriding existing."); } this.key = new JSEncryptRSAKey(key); }; /** * Proxy method for setKey, for api compatibility * @see setKey * @public */ JSEncrypt.prototype.setPrivateKey = function (privkey) { // Create the key. this.setKey(privkey); }; /** * Proxy method for setKey, for api compatibility * @see setKey * @public */ JSEncrypt.prototype.setPublicKey = function (pubkey) { // Sets the public key. this.setKey(pubkey); }; /** * Proxy method for RSAKey object's decrypt, decrypt the string using the private * components of the rsa key object. Note that if the object was not set will be created * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor * @param {string} str base64 encoded crypted string to decrypt * @return {string} the decrypted string * @public */ JSEncrypt.prototype.decrypt = function (str) { // Return the decrypted string. try { return this.getKey().decrypt(b64tohex(str)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's encrypt, encrypt the string using the public * components of the rsa key object. Note that if the object was not set will be created * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor * @param {string} str the string to encrypt * @return {string} the encrypted string encoded in base64 * @public */ JSEncrypt.prototype.encrypt = function (str) { // Return the encrypted string. try { return hex2b64(this.getKey().encrypt(str)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's sign. * @param {string} str the string to sign * @param {function} digestMethod hash method * @param {string} digestName the name of the hash algorithm * @return {string} the signature encoded in base64 * @public */ JSEncrypt.prototype.sign = function (str, digestMethod, digestName) { // return the RSA signature of 'str' in 'hex' format. try { return hex2b64(this.getKey().sign(str, digestMethod, digestName)); } catch (ex) { return false; } }; /** * Proxy method for RSAKey object's verify. * @param {string} str the string to verify * @param {string} signature the signature encoded in base64 to compare the string to * @param {function} digestMethod hash method * @return {boolean} whether the data and signature match * @public */ JSEncrypt.prototype.verify = function (str, signature, digestMethod) { // Return the decrypted 'digest' of the signature. try { return this.getKey().verify(str, b64tohex(signature), digestMethod); } catch (ex) { return false; } }; /** * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object * will be created and returned * @param {callback} [cb] the callback to be called if we want the key to be generated * in an async fashion * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object * @public */ JSEncrypt.prototype.getKey = function (cb) { // Only create new if it does not exist. if (!this.key) { // Get a new private key. this.key = new JSEncryptRSAKey(); if (cb && {}.toString.call(cb) === "[object Function]") { this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb); return; } // Generate the key. this.key.generate(this.default_key_size, this.default_public_exponent); } return this.key; }; /** * Returns the pem encoded representation of the private key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the private key WITH header and footer * @public */ JSEncrypt.prototype.getPrivateKey = function () { // Return the private representation of this key. return this.getKey().getPrivateKey(); }; /** * Returns the pem encoded representation of the private key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the private key WITHOUT header and footer * @public */ JSEncrypt.prototype.getPrivateKeyB64 = function () { // Return the private representation of this key. return this.getKey().getPrivateBaseKeyB64(); }; /** * Returns the pem encoded representation of the public key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the public key WITH header and footer * @public */ JSEncrypt.prototype.getPublicKey = function () { // Return the private representation of this key. return this.getKey().getPublicKey(); }; /** * Returns the pem encoded representation of the public key * If the key doesn't exists a new key will be created * @returns {string} pem encoded representation of the public key WITHOUT header and footer * @public */ JSEncrypt.prototype.getPublicKeyB64 = function () { // Return the private representation of this key. return this.getKey().getPublicBaseKeyB64(); }; JSEncrypt.version = "3.0.0-rc.1"; return JSEncrypt; }()); window.JSEncrypt = JSEncrypt; exports.JSEncrypt = JSEncrypt; exports.default = JSEncrypt; Object.defineProperty(exports, '__esModule', { value: true }); })));
jonobr1/cdnjs
ajax/libs/jsencrypt/3.0.0-rc.1/jsencrypt.js
JavaScript
mit
177,817
'use strict'; /** * Lazily required module dependencies */ var lazy = require('lazy-cache')(require); var fn = require; require = lazy; require('falsey', 'isFalsey'); require('delimiter-regex', 'delims'); require('get-view'); require = fn; /** * Expose `utils` */ module.exports = lazy;
glg-enterprises/Cms
template/admin/node_modules/layouts/utils.js
JavaScript
mit
296
interface A { 'C': string; } interface B { "D": boolean; }
rattrayalex/prettier
tests/format/flow/generic/interface.js
JavaScript
mit
59
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 0.1.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Bake\Shell\Task; use Bake\Utility\Model\AssociationFilter; use Cake\Console\Shell; use Cake\Core\App; use Cake\Core\Configure; use Cake\ORM\Table; use Cake\ORM\TableRegistry; use Cake\Utility\Inflector; /** * Task class for creating and updating view template files. * */ class TemplateTask extends BakeTask { /** * Tasks to be loaded by this Task * * @var array */ public $tasks = [ 'Bake.Model', 'Bake.BakeTemplate' ]; /** * path to Template directory * * @var array */ public $pathFragment = 'Template/'; /** * Name of the controller being used * * @var string */ public $controllerName = null; /** * Classname of the controller being used * * @var string */ public $controllerClass = null; /** * Name with plugin of the model being used * * @var string */ public $modelName = null; /** * The template file to use * * @var string */ public $template = null; /** * Actions to use for scaffolding * * @var array */ public $scaffoldActions = ['index', 'view', 'add', 'edit']; /** * An array of action names that don't require templates. These * actions will not emit errors when doing bakeActions() * * @var array */ public $noTemplateActions = ['delete']; /** * AssociationFilter utility * * @var AssociationFilter */ protected $_associationFilter = null; /** * Override initialize * * @return void */ public function initialize() { $this->path = current(App::path('Template')); } /** * Execution method always used for tasks * * @param string|null $name The name of the controller to bake view templates for. * @param string|null $template The template to bake with. * @param string|null $action The action to bake with. * @return mixed */ public function main($name = null, $template = null, $action = null) { parent::main(); if (empty($name)) { $this->out('Possible tables to bake view templates for based on your current database:'); $this->Model->connection = $this->connection; foreach ($this->Model->listUnskipped() as $table) { $this->out('- ' . $this->_camelize($table)); } return true; } $name = $this->_getName($name); $controller = null; if (!empty($this->params['controller'])) { $controller = $this->params['controller']; } $this->controller($name, $controller); $this->model($name); if (isset($template)) { $this->template = $template; } if (!$action) { $action = $this->template; } if ($action) { return $this->bake($action, true); } $vars = $this->_loadController(); $methods = $this->_methodsToBake(); foreach ($methods as $method) { $content = $this->getContent($method, $vars); if ($content) { $this->bake($method, $content); } } } /** * Set the model class for the table. * * @param string $table The table/model that is being baked. * @return void */ public function model($table) { $tableName = $this->_camelize($table); $plugin = null; if (!empty($this->params['plugin'])) { $plugin = $this->params['plugin'] . '.'; } $this->modelName = $plugin . $tableName; } /** * Set the controller related properties. * * @param string $table The table/model that is being baked. * @param string|null $controller The controller name if specified. * @return void */ public function controller($table, $controller = null) { $tableName = $this->_camelize($table); if (empty($controller)) { $controller = $tableName; } $this->controllerName = $controller; $plugin = $this->param('plugin'); if ($plugin) { $plugin .= '.'; } $prefix = $this->_getPrefix(); if ($prefix) { $prefix .= '/'; } $this->controllerClass = App::className($plugin . $prefix . $controller, 'Controller', 'Controller'); } /** * Get the path base for view templates. * * @return string */ public function getPath() { $path = parent::getPath(); $path .= $this->controllerName . DS; return $path; } /** * Get a list of actions that can / should have view templates baked for them. * * @return array Array of action names that should be baked */ protected function _methodsToBake() { $base = Configure::read('App.namespace'); $methods = []; if (class_exists($this->controllerClass)) { $methods = array_diff( array_map( 'Cake\Utility\Inflector::underscore', get_class_methods($this->controllerClass) ), array_map( 'Cake\Utility\Inflector::underscore', get_class_methods($base . '\Controller\AppController') ) ); } if (empty($methods)) { $methods = $this->scaffoldActions; } foreach ($methods as $i => $method) { if ($method[0] === '_') { unset($methods[$i]); } } return $methods; } /** * Bake All view templates for all controller actions. * * @return void */ public function all() { $this->Model->connection = $this->connection; $tables = $this->Model->listUnskipped(); foreach ($tables as $table) { $this->main($table); } } /** * Loads Controller and sets variables for the template * Available template variables: * * - 'modelObject' * - 'modelClass' * - 'primaryKey' * - 'displayField' * - 'singularVar' * - 'pluralVar' * - 'singularHumanName' * - 'pluralHumanName' * - 'fields' * - 'keyFields' * - 'schema' * * @return array Returns variables to be made available to a view template */ protected function _loadController() { if (TableRegistry::exists($this->modelName)) { $modelObject = TableRegistry::get($this->modelName); } else { $modelObject = TableRegistry::get($this->modelName, [ 'connectionName' => $this->connection ]); } $primaryKey = (array)$modelObject->getPrimaryKey(); $displayField = $modelObject->getDisplayField(); $singularVar = $this->_singularName($this->controllerName); $singularHumanName = $this->_singularHumanName($this->controllerName); $schema = $modelObject->getSchema(); $fields = $schema->columns(); $modelClass = $this->modelName; $associations = $this->_filteredAssociations($modelObject); $keyFields = []; if (!empty($associations['BelongsTo'])) { foreach ($associations['BelongsTo'] as $assoc) { $keyFields[$assoc['foreignKey']] = $assoc['variable']; } } $pluralVar = Inflector::variable($this->controllerName); $pluralHumanName = $this->_pluralHumanName($this->controllerName); $namespace = Configure::read('App.namespace'); return compact( 'modelObject', 'modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', 'singularHumanName', 'pluralHumanName', 'fields', 'associations', 'keyFields', 'namespace' ); } /** * Bake a view file for each of the supplied actions * * @param array $actions Array of actions to make files for. * @param array $vars The context for generating views. * @return void */ public function bakeActions(array $actions, $vars) { foreach ($actions as $action) { $content = $this->getContent($action, $vars); $this->bake($action, $content); } } /** * handle creation of baking a custom action view file * * @return void */ public function customAction() { $action = ''; while (!$action) { $action = $this->in('Action Name? (use lowercase_underscored function name)'); if (!$action) { $this->out('The action name you supplied was empty. Please try again.'); } } $path = $this->getPath() . $this->controllerName . DS . Inflector::underscore($action) . ".ctp"; $this->out(); $this->hr(); $this->out('The following view will be created:'); $this->hr(); $this->out(sprintf('Controller Name: %s', $this->controllerName)); $this->out(sprintf('Action Name: %s', $action)); $this->out(sprintf('Path: %s', $path)); $this->hr(); $looksGood = $this->in('Look okay?', ['y', 'n'], 'y'); if (strtolower($looksGood) === 'y') { $this->bake($action, ' '); $this->_stop(); return; } $this->out('Bake Aborted.'); } /** * Assembles and writes bakes the view file. * * @param string $action Action to bake. * @param string $content Content to write. * @return string|false Generated file content. */ public function bake($action, $content = '') { if ($content === true) { $content = $this->getContent($action); } if (empty($content)) { $this->err("<warning>No generated content for '{$action}.ctp', not generating template.</warning>"); return false; } $this->out("\n" . sprintf('Baking `%s` view template file...', $action), 1, Shell::QUIET); $path = $this->getPath(); $filename = $path . Inflector::underscore($action) . '.ctp'; $this->createFile($filename, $content); return $content; } /** * Builds content from template and variables * * @param string $action name to generate content to * @param array|null $vars passed for use in templates * @return string|false Content from template */ public function getContent($action, $vars = null) { if (!$vars) { $vars = $this->_loadController(); } if (empty($vars['primaryKey'])) { $this->error('Cannot generate views for models with no primary key'); return false; } if ($action === "index" && !empty($this->params['index-columns'])) { $this->BakeTemplate->set('indexColumns', $this->params['index-columns']); } $this->BakeTemplate->set('action', $action); $this->BakeTemplate->set('plugin', $this->plugin); $this->BakeTemplate->set($vars); return $this->BakeTemplate->generate("Template/$action"); } /** * Gets the option parser instance and configures it. * * @return \Cake\Console\ConsoleOptionParser */ public function getOptionParser() { $parser = parent::getOptionParser(); $parser->setDescription( 'Bake views for a controller, using built-in or custom templates. ' )->addArgument('controller', [ 'help' => 'Name of the controller views to bake. You can use Plugin.name as a shortcut for plugin baking.' ])->addArgument('action', [ 'help' => "Will bake a single action's file. core templates are (index, add, edit, view)" ])->addArgument('alias', [ 'help' => 'Will bake the template in <action> but create the filename after <alias>.' ])->addOption('controller', [ 'help' => 'The controller name if you have a controller that does not follow conventions.' ])->addOption('prefix', [ 'help' => 'The routing prefix to generate views for.', ])->addOption('index-columns', [ 'help' => 'Limit for the number of index columns', 'default' => 0 ])->addSubcommand('all', [ 'help' => '[optional] Bake all CRUD action views for all controllers. Requires models and controllers to exist.' ]); return $parser; } /** * Get filtered associations * To be mocked... * * @param \Cake\ORM\Table $model Table * @return array associations */ protected function _filteredAssociations(Table $model) { if (is_null($this->_associationFilter)) { $this->_associationFilter = new AssociationFilter(); } return $this->_associationFilter->filterAssociations($model); } }
antoniocdff/tree
vendor/cakephp/bake/src/Shell/Task/TemplateTask.php
PHP
mit
13,819
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("VoicemailBoxActorService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VoicemailBoxActorService")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("305f4ce2-e628-4243-b76c-ca7d02469ddd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
JayHCho/servicefabric-samples
samples/Actors/VS2013/VoicemailBox/V2/VoicemailBoxActorServiceV2/Properties/AssemblyInfo.cs
C#
mit
1,385
#clearchat-control { background: transparent url('page_refresh.png') no-repeat; position: relative; }
sriducati/chat.am
vendor_libs/clearchat/candy.css
CSS
mit
109
/* * stencilReduceOCL_macros.hpp * * Created on: Feb 13, 2015 * Author: drocco */ #ifndef STENCILREDUCEOCL_MACROS_HPP_ #define STENCILREDUCEOCL_MACROS_HPP_ #include <string> #include <sstream> namespace ff { #if 1 //explicit input, single-device /* * both indexed and direct elemental function for 1D map. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'basictype' is the element type * 'param' is the value of the input element * 'idx' is the index of the input element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC(name, basictype, param, idx, ...) \ static char name[] =\ "kern_" #name "|"\ #basictype "|"\ #basictype " f" #name "(" #basictype " " #param ",const int " #idx ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #basictype "* input,\n"\ "\t__global " #basictype "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i],i);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * both indexed and direct elemental function for 1D map * with different input/output types. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'outT' is the output element type * 'T' is the input element type * 'param' is the value of the input element * 'idx' is the index of the input element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC_IO(name, outT, T, param, idx, ...)\ static char name[] =\ "kern_" #name "|"\ #outT "|"\ #outT " f" #name "(" #T " " #param ", const int " #idx ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #outT "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i],i);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array * 'idx' is the index of the element * 'in' is the input array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC(name,T,size,idx,in, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n" #T " f" #name "(\n"\ "\t__global " #T "* " #in ",\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ") {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t int i = get_global_id(0);\n"\ "\t int ig = i + offset;\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil with read-only environment. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array * 'idx' is the index of the element * 'in' is the input array * 'env1T' is the element type of the constant environment array * 'env1' is the constant environment array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_ENV(name,T,size,idx,in,env1T,env1, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n" #T " f" #name "(\n"\ "\t__global " #T "* " #in ",\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\t__global const " #env1T "* " #env1 ") {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env1) {\n"\ "\t int i = get_global_id(0);\n"\ "\t int ig = i + offset;\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig,env1);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil with two read-only environments. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array * 'idx' is the index of the input element * 'in' is the input array * 'env1T' is the element type of the constant environment array * 'env1' is the constant environment array * 'env2T' is the element type of the constant environment value * 'env2' is (a pointer to) the constant environment value * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_2ENV(name,T,size,idx,in,env1T,env1,env2T,env2, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n" #T " f" #name "(\n"\ "\t__global " #T "* " #in ",\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\t__global const " #env1T "* " #env1 ",\n"\ "\t__global const " #env2T "* " #env2 ") {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env2T "* env2) {\n"\ "\t int i = get_global_id(0);\n"\ "\t int ig = i + offset;\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig,env1,env2);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* Same as the previous one, but with different input output types * indexed elemental function for 1D stencil with two read-only environments. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array * 'idx' is the index of the input element * 'in' is the input array * 'env1T' is the element type of the constant environment array * 'env1' is the constant environment array * 'env2T' is the element type of the constant environment value * 'env2' is (a pointer to) the constant environment value * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_2ENV_IO(name,T,outT,size,idx,in,env1T,env1,env2T,env2, ...)\ static char name[] =\ "kern_" #name "|"\ #outT "|"\ "\n\n" #outT " f" #name "(\n"\ "\t__global " #T "* " #in ",\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\t__global const " #env1T "* " #env1 ",\n"\ "\t__global const " #env2T "* " #env2 ") {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #outT "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env2T "* env2) {\n"\ "\t int i = get_global_id(0);\n"\ "\t int ig = i + offset;\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig,env1,env2);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" #endif #if 1 //implicit input, multi-device support /* * This file contains macros for defining 1D and 2D elemental functions. * An instance of the elemental function is executed for each element * in the logical input array/matrix of a stencilReduceLoop task. * * An elemental function f can be either: * - direct: input is the value of the element (f: T -> T) * - indexed: input is the index of the element in the input array (f: N -> T) * Direct and indexed functions characterize, respectively, map and stencil tasks. * * Indexed elemental functions access elements via pre-defined macros: * - GET_IN(i) returns the i-th element in the input array * - GET_IN(i,j) returns the (i,j)-th element in the input matrix * * Some elemental functions are defined for working with read-only environments. * Macros are provided for accessing the environment from indexed * elemental functions: * - GET_ENV(i) for single-environment functions * - GET_ENV1(i), GET_ENV2(i) ... for multi-environment functions * * A simple macro for defining reduce combinator function is provided. */ /* * direct elemental function for 1D map. * f: T -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type * 'val' is the value of the input element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC_1D(name, T, val, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ #T " f" #name "(" #T " " #val ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i]);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * direct elemental function for 1D map. * f: T -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type * 'val' is the value of the input element * 'envT' is the element type of the constant environment * 'envval' is the value of the environment element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC_1D_ENV(name, T, val, envT, envval, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|\n"\ #T " f" #name "(" #T " " #val ", " #envT " " #envval ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #envT "* env) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i], env[i]);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * direct elemental function for 1D map with different input/output types. * f: T1 -> T2 * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the input element type * 'outT' is the output element type * 'val' is the value of the input element * 'idx' is the index of the input element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC_1D_IO(name, T, outT, val, idx, ...) \ static char name[] =\ "kern_" #name "|"\ #outT "|\n\n"\ #outT " f" #name "("#T" "#val ",\n"\ "\tconst int " #idx "\n"\ ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #outT "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i], i);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * direct elemental function for 1D map. * f: T -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type * 'val' is the value of the input element * 'envT' is the element type of the constant environment * 'envval' is the value of the environment element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_MAP_ELEMFUNC_1D_ENV_IO(name, T, val, envT, envval, idx, ...) \ static char name[] =\ "kern_" #name "|"\ #T "|\n"\ #T " f" #name "(" #T " " #val ", " #envT " " #envval ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #envT "* env) {\n"\ "\t int i = get_global_id(0);\n"\ "\t uint gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i] = f" #name "(input[i], env[i], i);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array (for bound checking) * 'idx' is the index of the element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_1D(name,T,size,idx, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i) (in[i-offset])\n"\ "#define GET_ENV1(i) (env1[i])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\tconst int offset\n) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,i+offset,offset);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil with read-only environment. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array (for bound checking) * 'idx' is the index of the element * 'env1T' is the element type of the constant environment array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_1D_ENV(name,T,size,idx,env1T, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i) (in[(i)-offset])\n"\ "#define GET_ENV(i) (env[(i)])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\tconst int offset,\n"\ "\t__global const " #env1T "* env) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig,offset,env);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 1D stencil with two read-only environments. * f: N -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'size' is the size of the input array (for bound checking) * 'idx' is the index of the element * 'env1T' is the element type of the first constant environment array * 'env2T' is the element type of the second constant environment array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_1D_2ENV(name,T,size,idx,env1T,env2T, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i) (in[(i)-offset])\n"\ "#define GET_ENV1(i) (env1[i])\n"\ "#define GET_ENV2(i) (env2[i])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #size ",\n"\ "\tconst int " #idx ",\n"\ "\tconst int offset,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env2T "* env2) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inSize,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env1T "* env2) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inSize,ig,offset,env1,env2);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 2D stencil. * f: (N,N) -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'height' is the number of rows in the input array (for bound checking) * 'width' is the number of columns in the input array (for bound checking) * 'row' is the row-index of the element * 'col' is the column-index of the element * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_2D(name,T,height,width,row,col, ...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i,j) (in[((i)*"#width"+(j))-offset])\n"\ "#define GET_ENV1(i,j) (env1[((i)*"#width"+(j))])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #height ",\n"\ "\tconst uint " #width ",\n"\ "\tconst int " #row ",\n"\ "\tconst int " #col ",\n"\ "\tconst int offset) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inHeight,\n"\ "\tconst uint inWidth,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t r = ig / inWidth;\n"\ "\t size_t c = ig % inWidth;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inHeight,inWidth,r,c,offset);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 2D stencil. * f: (N,N) -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'height' is the number of rows in the input array (for bound checking) * 'width' is the number of columns in the input array (for bound checking) * 'row' is the row-index of the element * 'col' is the column-index of the element * 'env1T' is the element type of the constant environment array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_2D_ENV(name,T,height,width,row,col,env1T,...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i,j) (in[((i)*"#width"+(j))-offset])\n"\ "#define GET_ENV(i,j) (env1[((i)*"#width"+(j))])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #height ",\n"\ "\tconst uint " #width ",\n"\ "\tconst int " #row ",\n"\ "\tconst int " #col ",\n"\ "\tconst int offset,\n"\ "\t__global const " #env1T "* env) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inHeight,\n"\ "\tconst uint inWidth,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t r = ig / inWidth;\n"\ "\t size_t c = ig % inWidth;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inHeight,inWidth,r,c,offset,env);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" /* * indexed elemental function for 2D stencil. * f: (N,N) -> T * * API: * 'name' is the name of the string variable in which the code is stored * 'T' is the element type of the input * 'height' is the number of rows in the input array (for bound checking) * 'width' is the number of columns in the input array (for bound checking) * 'row' is the row-index of the element * 'col' is the column-index of the element * 'env1T' is the element type of the first constant environment array * 'env2T' is the element type of the second constant environment array * '...' is the OpenCL code of the elemental function */ #define FF_OCL_STENCIL_ELEMFUNC_2D_2ENV(name,T,height,width,row,col,env1T,env2T,...)\ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i,j) (in[((i)*"#width"+(j))-offset])\n"\ "#define GET_ENV1(i,j) (env1[((i)*"#width"+(j))])\n"\ "#define GET_ENV2(i,j) (env2[((i)*"#width"+(j))])\n"\ #T " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #height ",\n"\ "\tconst uint " #width ",\n"\ "\tconst int " #row ",\n"\ "\tconst int " #col ",\n"\ "\tconst int offset,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env2T "* env2) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #T "* output,\n"\ "\tconst uint inHeight,\n"\ "\tconst uint inWidth,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo,\n"\ "\t__global const " #env1T "* env1,\n"\ "\t__global const " #env2T "* env2) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t r = ig / inWidth;\n"\ "\t size_t c = ig % inWidth;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inHeight,inWidth,r,c,offset,env1,env2);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" #define FF_OCL_STENCIL_ELEMFUNC_2D_IO(name,T, outT, height,width,row,col, ...) \ static char name[] =\ "kern_" #name "|"\ #T "|"\ "\n\n"\ "#define GET_IN(i,j) (in[((i)*"#width"+(j))-offset])\n"\ #outT " f" #name "(\n"\ "\t__global " #T "* in,\n"\ "\tconst uint " #height ",\n"\ "\tconst uint " #width ",\n"\ "\tconst int " #row ",\n"\ "\tconst int " #col ",\n"\ "\tconst int offset) {\n"\ "\t " #__VA_ARGS__";\n"\ "}\n\n"\ "__kernel void kern_" #name "(\n"\ "\t__global " #T "* input,\n"\ "\t__global " #outT "* output,\n"\ "\tconst uint inHeight,\n"\ "\tconst uint inWidth,\n"\ "\tconst uint maxItems,\n"\ "\tconst uint offset,\n"\ "\tconst uint halo) {\n"\ "\t size_t i = get_global_id(0);\n"\ "\t size_t ig = i + offset;\n"\ "\t size_t r = ig / inWidth;\n"\ "\t size_t c = ig % inWidth;\n"\ "\t size_t gridSize = get_local_size(0)*get_num_groups(0);\n"\ "\t while(i < maxItems) {\n"\ "\t output[i+halo] = f" #name "(input+halo,inHeight,inWidth,r,c,offset);\n"\ "\t i += gridSize;\n"\ "\t }\n"\ "}\n" #endif // x=f(param1,param2) 'x', 'param1', 'param2' have the same type #define FF_OCL_REDUCE_COMBINATOR(name, basictype, param1, param2, ...)\ static char name[] =\ "kern_" #name "|"\ #basictype "|"\ #basictype " f" #name "(" #basictype " " #param1 ",\n"\ #basictype " " #param2 ") {\n" #__VA_ARGS__";\n}\n"\ "__kernel void kern_" #name "(__global " #basictype "* input, const uint halo, __global " #basictype "* output, const uint n, __local " #basictype "* sdata, "#basictype" idElem) {\n"\ " uint blockSize = get_local_size(0);\n"\ " uint tid = get_local_id(0);\n"\ " uint i = get_group_id(0)*blockSize + get_local_id(0);\n"\ " uint gridSize = blockSize*get_num_groups(0);\n"\ " " #basictype " result = idElem; input += halo;\n"\ " if(i < n) { result = input[i]; i += gridSize; }\n"\ " while(i < n) {\n"\ " result = f" #name "(result, input[i]);\n"\ " i += gridSize;\n"\ " }\n"\ " sdata[tid] = result;\n"\ " barrier(CLK_LOCAL_MEM_FENCE);\n"\ " if(blockSize >= 512) { if (tid < 256 && tid + 256 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 256]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 256) { if (tid < 128 && tid + 128 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 128]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 128) { if (tid < 64 && tid + 64 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 64]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 64) { if (tid < 32 && tid + 32 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 32]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 32) { if (tid < 16 && tid + 16 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 16]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 16) { if (tid < 8 && tid + 8 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 8]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 8) { if (tid < 4 && tid + 4 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 4]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 4) { if (tid < 2 && tid + 2 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 2]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(blockSize >= 2) { if (tid < 1 && tid + 1 < n) { sdata[tid] = f" #name "(sdata[tid], sdata[tid + 1]); } barrier(CLK_LOCAL_MEM_FENCE); }\n"\ " if(tid == 0) output[get_group_id(0)] = sdata[tid];\n"\ "}\n"; #define FFGENERICFUNC(name, basictype, ...)\ static char name[] =\ "kern_" #name "|"\ #basictype "|"\ #__VA_ARGS__";\n\n" /* ------------------------------------------------------------------------------------- */ // NOTE: A better check would be needed ! // both GNU g++ and Intel icpc define __GXX_EXPERIMENTAL_CXX0X__ if -std=c++0x or -std=c++11 is used // (icpc -E -dM -std=c++11 -x c++ /dev/null | grep GXX_EX) #if (__cplusplus >= 201103L) || (defined __GXX_EXPERIMENTAL_CXX0X__) || defined(HAS_CXX11_VARIADIC_TEMPLATES) template< typename ... Args > std::string stringer(Args const& ... args ) { std::ostringstream stream; using List= int[]; // expanding a parameter pack is only valid in contexts // where the parser expects a comma-separated list of entries (void)List{0, ( (void)(stream << args), 0 ) ... }; return stream.str(); } #define STRINGER(...) stringer(__VA_ARGS__) #endif // c++11 check } // namespace #endif /* STENCILREDUCEOCL_MACROS_HPP_ */
DanieleDeSensi/Peafowl
include/peafowl/external/fastflow/ff/stencilReduceOCL_macros.hpp
C++
mit
27,252
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>DbEnv::set_lg_bsize()</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C++ API Reference" /> <link rel="up" href="lsn.html" title="Chapter 8.  The DbLsn Handle" /> <link rel="prev" href="logstat_print.html" title="DbEnv::log_stat_print()" /> <link rel="next" href="envset_lg_dir.html" title="DbEnv::set_lg_dir()" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">DbEnv::set_lg_bsize()</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="logstat_print.html">Prev</a> </td> <th width="60%" align="center">Chapter 8.  The DbLsn Handle </th> <td width="20%" align="right"> <a accesskey="n" href="envset_lg_dir.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="envset_lg_bsize"></a>DbEnv::set_lg_bsize()</h2> </div> </div> </div> <pre class="programlisting">#include &lt;db_cxx.h&gt; int DbEnv::set_lg_bsize(u_int32_t lg_bsize); </pre> <p> Set the size of the in-memory log buffer, in bytes. </p> <p> When the logging subsystem is configured for on-disk logging, the default size of the in-memory log buffer is approximately 32KB. Log information is stored in-memory until the storage space fills up or transaction commit forces the information to be flushed to stable storage. In the presence of long-running transactions or transactions producing large amounts of data, larger buffer sizes can increase throughput. </p> <p> When the logging subsystem is configured for in-memory logging, the default size of the in-memory log buffer is 1MB. Log information is stored in-memory until the storage space fills up or transaction abort or commit frees up the memory for new transactions. In the presence of long-running transactions or transactions producing large amounts of data, the buffer size must be sufficient to hold all log information that can accumulate during the longest running transaction. When choosing log buffer and file sizes for in-memory logs, applications should ensure the in-memory log buffer size is large enough that no transaction will ever span the entire buffer, and avoid a state where the in-memory buffer is full and no space can be freed because a transaction that started in the first log "file" is still active. </p> <p> The database environment's log buffer size may also be configured using the environment's <a href="../../programmer_reference/env_db_config.html#env_db_config.DB_CONFIG" class="olink">DB_CONFIG</a> file. The syntax of the entry in that file is a single line with the string "set_lg_bsize", one or more whitespace characters, and the size in bytes. Because the <a href="../../programmer_reference/env_db_config.html#env_db_config.DB_CONFIG" class="olink">DB_CONFIG</a> file is read when the database environment is opened, it will silently overrule configuration done before that time. </p> <p> The <code class="methodname">DbEnv::set_lg_bsize()</code> method configures a database environment, not only operations performed using the specified <a class="link" href="env.html" title="Chapter 5.  The DbEnv Handle">DbEnv</a> handle. </p> <p> The <code class="methodname">DbEnv::set_lg_bsize()</code> method may not be called after the <a class="xref" href="envopen.html" title="DbEnv::open()">DbEnv::open()</a> method is called. If the database environment already exists when <a class="xref" href="envopen.html" title="DbEnv::open()">DbEnv::open()</a> is called, the information specified to <code class="methodname">DbEnv::set_lg_bsize()</code> will be ignored. </p> <p> The <code class="methodname">DbEnv::set_lg_bsize()</code> <span> <span> method either returns a non-zero error value or throws an exception that encapsulates a non-zero error value on failure, and returns 0 on success. </span> </span> </p> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id1687777"></a>Parameters</h3> </div> </div> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id1687838"></a>lg_bsize</h4> </div> </div> </div> <p> The <span class="bold"><strong>lg_bsize</strong></span> parameter is the size of the in-memory log buffer, in bytes. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id1687923"></a>Errors</h3> </div> </div> </div> <p> The <code class="methodname">DbEnv::set_lg_bsize()</code> <span> <span> method may fail and throw a <a class="link" href="dbexception.html" title="Chapter 6. The DbException Class">DbException</a> exception, encapsulating one of the following non-zero errors, or return one of the following non-zero errors: </span> </span> </p> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="id1687920"></a>EINVAL</h4> </div> </div> </div> <p> An invalid flag value or parameter was specified. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id1687810"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="env.html" title="Chapter 5.  The DbEnv Handle">DbEnv</a>, <a class="link" href="logc.html" title="The DbLogc Handle">DbLogc</a>, <a class="link" href="lsn.html" title="Chapter 8.  The DbLsn Handle">DbLsn</a> </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="id1687943"></a>See Also</h3> </div> </div> </div> <p> <a class="xref" href="lsn.html#loglist" title="Logging Subsystem and Related Methods">Logging Subsystem and Related Methods</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="logstat_print.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="lsn.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="envset_lg_dir.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">DbEnv::log_stat_print() </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> DbEnv::set_lg_dir()</td> </tr> </table> </div> </body> </html>
dwaynebailey/poedit
deps/db/docs/api_reference/CXX/envset_lg_bsize.html
HTML
mit
8,669
module Locomotive class Membership include Locomotive::Mongoid::Document ## fields ## field :role, default: 'author' ## associations ## belongs_to :account, class_name: 'Locomotive::Account', validate: false embedded_in :site, class_name: 'Locomotive::Site', inverse_of: :memberships ## validations ## validates_presence_of :account validate :can_change_role, if: :role_changed? ## callbacks ## before_save :define_role ## methods ## Locomotive::Ability::ROLES.each do |_role| define_method("#{_role}?") do self.role == _role end end def email; @email; end def email=(email) @email = email self.account = Locomotive::Account.where(email: email).first end def process! if @email.blank? self.errors.add_on_blank(:email) :error elsif self.account.blank? :create_account elsif self.site.memberships.any? { |m| m.account_id == self.account_id && m._id != self._id } self.errors.add(:base, 'Already created') :already_created else self.save :save_it end end def ability @ability ||= Locomotive::Ability.new(self.account, self.site) end protected def define_role self.role = Locomotive::Ability::ROLES.include?(role.downcase) ? role.downcase : Locomotive::Ability::ROLES.first end # Users should not be able to set the role of another user to be higher than # their own. A designer for example should not be able to set another user to # be an administrator def can_change_role current_site = Thread.current[:site] current_membership = current_site.memberships.where(account_id: Thread.current[:account].id).first if current_site.present? if current_membership.present? # The role cannot be set higher than the current one (we use the index in # the roles array to check role presidence) errors.add(:role, :invalid) if Locomotive::Ability::ROLES.index(role) < Locomotive::Ability::ROLES.index(current_membership.role) end end end end
furkanayhan/engine
app/models/locomotive/membership.rb
Ruby
mit
2,167
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import { assign } from 'vs/base/common/objects'; import { Url, parse as parseUrl } from 'url'; import { request, IRequestOptions } from 'vs/base/node/request'; import HttpProxyAgent = require('http-proxy-agent'); import HttpsProxyAgent = require('https-proxy-agent'); export interface IXHROptions extends IRequestOptions { responseType?: string; followRedirects: number; } export interface IXHRResponse { responseText: string; status: number; } let proxyConfiguration: string = null; export function configure(proxyURI: string): void { proxyConfiguration = proxyURI; } function getProxyURI(uri: Url): string { let proxyURI = proxyConfiguration; if (!proxyURI) { if (uri.protocol === 'http:') { proxyURI = process.env.HTTP_PROXY || process.env.http_proxy || null; } else if (uri.protocol === 'https:') { proxyURI = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null; } } return proxyURI; } function getProxyAgent(uri: Url): any { let proxyURI = getProxyURI(uri); if (proxyURI) { let proxyEndpoint = parseUrl(proxyURI); switch (proxyEndpoint.protocol) { case 'http:': case 'https:': return uri.protocol === 'http:' ? new HttpProxyAgent(proxyURI) : new HttpsProxyAgent(proxyURI); } } return void 0; } export function xhr(options: IXHROptions): TPromise<IXHRResponse> { let endpoint = parseUrl(options.url); options = assign({}, options); options = assign(options, { agent: getProxyAgent(endpoint) }); return request(options).then(result => new TPromise<IXHRResponse>((c, e, p) => { let res = result.res; let data: string[] = []; res.on('data', c => data.push(c)); res.on('end', () => { if (options.followRedirects > 0 && (res.statusCode >= 300 && res.statusCode <= 303 || res.statusCode === 307)) { let location = res.headers['location']; if (location) { let newOptions = { type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers, timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data }; xhr(newOptions).done(c, e, p); return; } } let response: IXHRResponse = { responseText: data.join(''), status: res.statusCode }; if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) { c(response); } else { e(response); } }); }, err => { let endpoint = parseUrl(options.url); let agent = getProxyAgent(endpoint); let message: string; if (agent) { message = 'Unable to to connect to ' + options.url + ' through proxy ' + getProxyURI(endpoint) + '. Error: ' + err.message; } else { message = 'Unable to to connect to ' + options.url + '. Error: ' + err.message; } return TPromise.wrapError<IXHRResponse>({ responseText: message, status: 404 }); })); }
takumif/vscode
src/vs/workbench/services/request/node/rawHttpService.ts
TypeScript
mit
3,347
# Frame-filter commands. # Copyright (C) 2013-2019 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """GDB commands for working with frame-filters.""" import sys import gdb import copy from gdb.FrameIterator import FrameIterator from gdb.FrameDecorator import FrameDecorator import gdb.frames import itertools # GDB Commands. class SetFilterPrefixCmd(gdb.Command): """Prefix command for 'set' frame-filter related operations.""" def __init__(self): super(SetFilterPrefixCmd, self).__init__("set frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True) class ShowFilterPrefixCmd(gdb.Command): """Prefix command for 'show' frame-filter related operations.""" def __init__(self): super(ShowFilterPrefixCmd, self).__init__("show frame-filter", gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True) class InfoFrameFilter(gdb.Command): """List all registered Python frame-filters. Usage: info frame-filters""" def __init__(self): super(InfoFrameFilter, self).__init__("info frame-filter", gdb.COMMAND_DATA) @staticmethod def enabled_string(state): """Return "Yes" if filter is enabled, otherwise "No".""" if state: return "Yes" else: return "No" def print_list(self, title, frame_filters, blank_line): sorted_frame_filters = sorted(frame_filters.items(), key=lambda i: gdb.frames.get_priority(i[1]), reverse=True) if len(sorted_frame_filters) == 0: return 0 print(title) print(" Priority Enabled Name") for frame_filter in sorted_frame_filters: name = frame_filter[0] try: priority = '{:<8}'.format( str(gdb.frames.get_priority(frame_filter[1]))) enabled = '{:<7}'.format( self.enabled_string(gdb.frames.get_enabled(frame_filter[1]))) print(" %s %s %s" % (priority, enabled, name)) except Exception: e = sys.exc_info()[1] print(" Error printing filter '"+name+"': "+str(e)) if blank_line: print("") return 1 def invoke(self, arg, from_tty): any_printed = self.print_list("global frame-filters:", gdb.frame_filters, True) cp = gdb.current_progspace() any_printed += self.print_list("progspace %s frame-filters:" % cp.filename, cp.frame_filters, True) for objfile in gdb.objfiles(): any_printed += self.print_list("objfile %s frame-filters:" % objfile.filename, objfile.frame_filters, False) if any_printed == 0: print ("No frame filters.") # Internal enable/disable functions. def _enable_parse_arg(cmd_name, arg): """ Internal worker function to take an argument from enable/disable and return a tuple of arguments. Arguments: cmd_name: Name of the command invoking this function. args: The argument as a string. Returns: A tuple containing the dictionary, and the argument, or just the dictionary in the case of "all". """ argv = gdb.string_to_argv(arg); argc = len(argv) if argc == 0: raise gdb.GdbError(cmd_name + " requires an argument") if argv[0] == "all": if argc > 1: raise gdb.GdbError(cmd_name + ": with 'all' " \ "you may not specify a filter.") elif argc != 2: raise gdb.GdbError(cmd_name + " takes exactly two arguments.") return argv def _do_enable_frame_filter(command_tuple, flag): """Worker for enabling/disabling frame_filters. Arguments: command_type: A tuple with the first element being the frame filter dictionary, and the second being the frame filter name. flag: True for Enable, False for Disable. """ list_op = command_tuple[0] op_list = gdb.frames.return_list(list_op) if list_op == "all": for item in op_list: gdb.frames.set_enabled(item, flag) else: frame_filter = command_tuple[1] try: ff = op_list[frame_filter] except KeyError: msg = "frame-filter '" + str(frame_filter) + "' not found." raise gdb.GdbError(msg) gdb.frames.set_enabled(ff, flag) def _complete_frame_filter_list(text, word, all_flag): """Worker for frame filter dictionary name completion. Arguments: text: The full text of the command line. word: The most recent word of the command line. all_flag: Whether to include the word "all" in completion. Returns: A list of suggested frame filter dictionary name completions from text/word analysis. This list can be empty when there are no suggestions for completion. """ if all_flag == True: filter_locations = ["all", "global", "progspace"] else: filter_locations = ["global", "progspace"] for objfile in gdb.objfiles(): filter_locations.append(objfile.filename) # If the user just asked for completions with no completion # hints, just return all the frame filter dictionaries we know # about. if (text == ""): return filter_locations # Otherwise filter on what we know. flist = filter(lambda x,y=text:x.startswith(y), filter_locations) # If we only have one completion, complete it and return it. if len(flist) == 1: flist[0] = flist[0][len(text)-len(word):] # Otherwise, return an empty list, or a list of frame filter # dictionaries that the previous filter operation returned. return flist def _complete_frame_filter_name(word, printer_dict): """Worker for frame filter name completion. Arguments: word: The most recent word of the command line. printer_dict: The frame filter dictionary to search for frame filter name completions. Returns: A list of suggested frame filter name completions from word analysis of the frame filter dictionary. This list can be empty when there are no suggestions for completion. """ printer_keys = printer_dict.keys() if (word == ""): return printer_keys flist = filter(lambda x,y=word:x.startswith(y), printer_keys) return flist class EnableFrameFilter(gdb.Command): """GDB command to enable the specified frame-filter. Usage: enable frame-filter DICTIONARY [NAME] DICTIONARY is the name of the frame filter dictionary on which to operate. If dictionary is set to "all", perform operations on all dictionaries. Named dictionaries are: "global" for the global frame filter dictionary, "progspace" for the program space's frame filter dictionary. If either all, or the two named dictionaries are not specified, the dictionary name is assumed to be the name of an "objfile" -- a shared library or an executable. NAME matches the name of the frame-filter to operate on.""" def __init__(self): super(EnableFrameFilter, self).__init__("enable frame-filter", gdb.COMMAND_DATA) def complete(self, text, word): """Completion function for both frame filter dictionary, and frame filter name.""" if text.count(" ") == 0: return _complete_frame_filter_list(text, word, True) else: printer_list = gdb.frames.return_list(text.split()[0].rstrip()) return _complete_frame_filter_name(word, printer_list) def invoke(self, arg, from_tty): command_tuple = _enable_parse_arg("enable frame-filter", arg) _do_enable_frame_filter(command_tuple, True) class DisableFrameFilter(gdb.Command): """GDB command to disable the specified frame-filter. Usage: disable frame-filter DICTIONARY [NAME] DICTIONARY is the name of the frame filter dictionary on which to operate. If dictionary is set to "all", perform operations on all dictionaries. Named dictionaries are: "global" for the global frame filter dictionary, "progspace" for the program space's frame filter dictionary. If either all, or the two named dictionaries are not specified, the dictionary name is assumed to be the name of an "objfile" -- a shared library or an executable. NAME matches the name of the frame-filter to operate on.""" def __init__(self): super(DisableFrameFilter, self).__init__("disable frame-filter", gdb.COMMAND_DATA) def complete(self, text, word): """Completion function for both frame filter dictionary, and frame filter name.""" if text.count(" ") == 0: return _complete_frame_filter_list(text, word, True) else: printer_list = gdb.frames.return_list(text.split()[0].rstrip()) return _complete_frame_filter_name(word, printer_list) def invoke(self, arg, from_tty): command_tuple = _enable_parse_arg("disable frame-filter", arg) _do_enable_frame_filter(command_tuple, False) class SetFrameFilterPriority(gdb.Command): """GDB command to set the priority of the specified frame-filter. Usage: set frame-filter priority DICTIONARY NAME PRIORITY DICTIONARY is the name of the frame filter dictionary on which to operate. Named dictionaries are: "global" for the global frame filter dictionary, "progspace" for the program space's framefilter dictionary. If either of these two are not specified, the dictionary name is assumed to be the name of an "objfile" -- a shared library or an executable. NAME matches the name of the frame filter to operate on. PRIORITY is the an integer to assign the new priority to the frame filter.""" def __init__(self): super(SetFrameFilterPriority, self).__init__("set frame-filter " \ "priority", gdb.COMMAND_DATA) def _parse_pri_arg(self, arg): """Internal worker to parse a priority from a tuple. Arguments: arg: Tuple which contains the arguments from the command. Returns: A tuple containing the dictionary, name and priority from the arguments. Raises: gdb.GdbError: An error parsing the arguments. """ argv = gdb.string_to_argv(arg); argc = len(argv) if argc != 3: print("set frame-filter priority " \ "takes exactly three arguments.") return None return argv def _set_filter_priority(self, command_tuple): """Internal worker for setting priority of frame-filters, by parsing a tuple and calling _set_priority with the parsed tuple. Arguments: command_tuple: Tuple which contains the arguments from the command. """ list_op = command_tuple[0] frame_filter = command_tuple[1] # GDB returns arguments as a string, so convert priority to # a number. priority = int(command_tuple[2]) op_list = gdb.frames.return_list(list_op) try: ff = op_list[frame_filter] except KeyError: msg = "frame-filter '" + str(frame_filter) + "' not found." raise gdb.GdbError(msg) gdb.frames.set_priority(ff, priority) def complete(self, text, word): """Completion function for both frame filter dictionary, and frame filter name.""" if text.count(" ") == 0: return _complete_frame_filter_list(text, word, False) else: printer_list = gdb.frames.return_list(text.split()[0].rstrip()) return _complete_frame_filter_name(word, printer_list) def invoke(self, arg, from_tty): command_tuple = self._parse_pri_arg(arg) if command_tuple != None: self._set_filter_priority(command_tuple) class ShowFrameFilterPriority(gdb.Command): """GDB command to show the priority of the specified frame-filter. Usage: show frame-filter priority DICTIONARY NAME DICTIONARY is the name of the frame filter dictionary on which to operate. Named dictionaries are: "global" for the global frame filter dictionary, "progspace" for the program space's framefilter dictionary. If either of these two are not specified, the dictionary name is assumed to be the name of an "objfile" -- a shared library or an executable. NAME matches the name of the frame-filter to operate on.""" def __init__(self): super(ShowFrameFilterPriority, self).__init__("show frame-filter " \ "priority", gdb.COMMAND_DATA) def _parse_pri_arg(self, arg): """Internal worker to parse a dictionary and name from a tuple. Arguments: arg: Tuple which contains the arguments from the command. Returns: A tuple containing the dictionary, and frame filter name. Raises: gdb.GdbError: An error parsing the arguments. """ argv = gdb.string_to_argv(arg); argc = len(argv) if argc != 2: print("show frame-filter priority " \ "takes exactly two arguments.") return None return argv def get_filter_priority(self, frame_filters, name): """Worker for retrieving the priority of frame_filters. Arguments: frame_filters: Name of frame filter dictionary. name: object to select printers. Returns: The priority of the frame filter. Raises: gdb.GdbError: A frame filter cannot be found. """ op_list = gdb.frames.return_list(frame_filters) try: ff = op_list[name] except KeyError: msg = "frame-filter '" + str(name) + "' not found." raise gdb.GdbError(msg) return gdb.frames.get_priority(ff) def complete(self, text, word): """Completion function for both frame filter dictionary, and frame filter name.""" if text.count(" ") == 0: return _complete_frame_filter_list(text, word, False) else: printer_list = frame._return_list(text.split()[0].rstrip()) return _complete_frame_filter_name(word, printer_list) def invoke(self, arg, from_tty): command_tuple = self._parse_pri_arg(arg) if command_tuple == None: return filter_name = command_tuple[1] list_name = command_tuple[0] try: priority = self.get_filter_priority(list_name, filter_name); except Exception: e = sys.exc_info()[1] print("Error printing filter priority for '"+name+"':"+str(e)) else: print("Priority of filter '" + filter_name + "' in list '" \ + list_name + "' is: " + str(priority)) # Register commands SetFilterPrefixCmd() ShowFilterPrefixCmd() InfoFrameFilter() EnableFrameFilter() DisableFrameFilter() SetFrameFilterPriority() ShowFrameFilterPriority()
OpenSmalltalk/vm
processors/ARM/gdb-8.3.1/gdb/python/lib/gdb/command/frame_filters.py
Python
mit
16,256
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TrueCraft.API.Logic; using TrueCraft.API; using TrueCraft.API.Entities; using TrueCraft.API.World; using TrueCraft.API.Networking; namespace TrueCraft.Core.Logic { public abstract class ItemProvider : IItemProvider { public abstract short ID { get; } public virtual sbyte MaximumStack { get { return 64; } } public virtual string DisplayName { get { return string.Empty; } } public virtual void ItemUsedOnEntity(ItemStack item, IEntity usedOn, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual void ItemUsedOnNothing(ItemStack item, IWorld world, IRemoteClient user) { // This space intentionally left blank } } }
blha303/TrueCraft
TrueCraft.Core/Logic/ItemProvider.cs
C#
mit
1,072
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - random_hashing_abstract.h</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2012 Davis E. King (davis@dlib.net) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#undef</font> DLIB_RANDOM_HAsHING_ABSTRACT_Hh_ <font color='#0000FF'>#ifdef</font> DLIB_RANDOM_HAsHING_ABSTRACT_Hh_ <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='random_hashing_abstract.h.html'>random_hashing_abstract.h</a>" <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='murmur_hash3.h.html'>murmur_hash3.h</a>" <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>double</u></font> <b><a name='uniform_random_hash'></a>uniform_random_hash</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k1, <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k2, <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k3 <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - This function uses hashing to generate uniform random values in the range [0,1). - To define this function precisely, assume we have an arbitrary sequence of input triplets. Then calling uniform_random_hash() on each of them should result in a sequence of double values that look like numbers sampled independently and uniformly at random from the interval [0,1). This is true even if there is some simple pattern in the inputs. For example, (0,0,0), (1,0,0), (2,0,0), (3,0,0), etc. - This function is deterministic. That is, the same output is always returned when given the same input. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>double</u></font> <b><a name='gaussian_random_hash'></a>gaussian_random_hash</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k1, <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k2, <font color='#0000FF'>const</font> uint64<font color='#5555FF'>&amp;</font> k3 <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - This function uses hashing to generate Gaussian distributed random values with mean 0 and variance 1. - To define this function precisely, assume we have an arbitrary sequence of input triplets. Then calling gaussian_random_hash() on each of them should result in a sequence of double values that look like numbers sampled independently from a standard normal distribution. This is true even if there is some simple pattern in the inputs. For example, (0,0,0), (1,0,0), (2,0,0), (3,0,0), etc. - This function is deterministic. That is, the same output is always returned when given the same input. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_RANDOM_HAsHING_ABSTRACT_Hh_ </font> </pre></body></html>
ruby-dlib/ruby-dlib
ext/dlib-19.4/docs/dlib/general_hash/random_hashing_abstract.h.html
HTML
mit
3,832
using System; using System.IO; using System.Collections.Specialized; using System.Net; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; namespace SteamTrade { public class SteamWeb { public static string Fetch (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebResponse response = Request (url, method, data, cookies, ajax); using(Stream responseStream = response.GetResponseStream()) { using(StreamReader reader = new StreamReader(responseStream)) { return reader.ReadToEnd(); } } } public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest; request.Method = method; request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //request.Host is set automatically request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; request.Referer = "http://steamcommunity.com/trade/1"; request.Timeout = 50000; //Timeout after 50 seconds if (ajax) { request.Headers.Add ("X-Requested-With", "XMLHttpRequest"); request.Headers.Add ("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = cookies ?? new CookieContainer (); // Request data if (data != null) { string dataString = String.Join ("&", Array.ConvertAll (data.AllKeys, key => String.Format ("{0}={1}", HttpUtility.UrlEncode (key), HttpUtility.UrlEncode (data [key])) )); byte[] dataBytes = Encoding.UTF8.GetBytes (dataString); request.ContentLength = dataBytes.Length; using(Stream requestStream = request.GetRequestStream()) { requestStream.Write(dataBytes, 0, dataBytes.Length); } } // Get the response return request.GetResponse () as HttpWebResponse; } /// <summary> /// Executes the login by using the Steam Website. /// </summary> public static CookieCollection DoLogin (string username, string password) { var data = new NameValueCollection (); data.Add ("username", username); string response = Fetch ("https://steamcommunity.com/login/getrsakey", "POST", data, null, false); GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey> (response); // Validate if (rsaJSON.success != true) { return null; } //RSA Encryption RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (); RSAParameters rsaParameters = new RSAParameters (); rsaParameters.Exponent = HexToByte (rsaJSON.publickey_exp); rsaParameters.Modulus = HexToByte (rsaJSON.publickey_mod); rsa.ImportParameters (rsaParameters); byte[] bytePassword = Encoding.ASCII.GetBytes (password); byte[] encodedPassword = rsa.Encrypt (bytePassword, false); string encryptedBase64Password = Convert.ToBase64String (encodedPassword); SteamResult loginJson = null; CookieCollection cookies; string steamGuardText = ""; string steamGuardId = ""; do { Console.WriteLine ("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed == true; bool steamGuard = loginJson != null && loginJson.emailauth_needed == true; string time = Uri.EscapeDataString (rsaJSON.timestamp); string capGID = loginJson == null ? null : Uri.EscapeDataString (loginJson.captcha_gid); data = new NameValueCollection (); data.Add ("password", encryptedBase64Password); data.Add ("username", username); // Captcha string capText = ""; if (captcha) { Console.WriteLine ("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start ("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine ("SteamWeb: Type the captcha:"); capText = Uri.EscapeDataString (Console.ReadLine ()); } data.Add ("captchagid", captcha ? capGID : ""); data.Add ("captcha_text", captcha ? capText : ""); // Captcha end // SteamGuard if (steamGuard) { Console.WriteLine ("SteamWeb: SteamGuard is needed."); Console.WriteLine ("SteamWeb: Type the code:"); steamGuardText = Uri.EscapeDataString (Console.ReadLine ()); steamGuardId = loginJson.emailsteamid; } data.Add ("emailauth", steamGuardText); data.Add ("emailsteamid", steamGuardId); // SteamGuard end data.Add ("rsatimestamp", time); HttpWebResponse webResponse = Request ("https://steamcommunity.com/login/dologin/", "POST", data, null, false); StreamReader reader = new StreamReader (webResponse.GetResponseStream ()); string json = reader.ReadToEnd (); loginJson = JsonConvert.DeserializeObject<SteamResult> (json); cookies = webResponse.Cookies; } while (loginJson.captcha_needed == true || loginJson.emailauth_needed == true); if (loginJson.success == true) { CookieContainer c = new CookieContainer (); foreach (Cookie cookie in cookies) { c.Add (cookie); } SubmitCookies (c); return cookies; } else { Console.WriteLine ("SteamWeb Error: " + loginJson.message); return null; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public static bool Authenticate(SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token, string MyLoginKey) { sessionId = Convert.ToBase64String (Encoding.UTF8.GetBytes (callback.UniqueID.ToString ())); using (dynamic userAuth = WebAPI.GetInterface ("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock (32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto (KeyDictionary.GetPublicKey (client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt (sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(MyLoginKey), loginKey, MyLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt (loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser ( steamid: client.SteamID.ConvertToUInt64 (), sessionkey: HttpUtility.UrlEncode (cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode (cryptedLoginKey), method: "POST" ); } catch (Exception) { token = null; return false; } token = authResult ["token"].AsString (); return true; } } static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create ("https://steamcommunity.com/") as HttpWebRequest; w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; w.GetResponse ().Close (); return; } static byte[] HexToByte (string hex) { if (hex.Length % 2 == 1) throw new Exception ("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr [i] = (byte)((GetHexVal (hex [i << 1]) << 4) + (GetHexVal (hex [(i << 1) + 1]))); } return arr; } static int GetHexVal (char hex) { int val = (int)hex; return val - (val < 58 ? 48 : 55); } public static bool ValidateRemoteCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // allow all certificates return true; } } // JSON Classes public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
JackHarknes/Bot1
SteamTrade/SteamWeb.cs
C#
mit
10,937
using TestExtensions; using Xunit; namespace NonSilo.Tests { // Assembly collections must be defined once in each assembly [CollectionDefinition("DefaultCluster")] public class DefaultClusterTestCollection : ICollectionFixture<DefaultClusterFixture> { } [CollectionDefinition(TestEnvironmentFixture.DefaultCollection)] public class TestEnvironmentFixtureCollection : ICollectionFixture<TestEnvironmentFixture> { } }
veikkoeeva/orleans
test/NonSilo.Tests/CollectionFixtures.cs
C#
mit
438
// ----------------------------------------------------------------------- // <copyright file="ShouldRetryException.cs" company=""> // TODO: Update copyright text. // </copyright> // ----------------------------------------------------------------------- namespace Cinchcast.Roque.Core { using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// If a job throws this exception the Worker will retry. /// </summary> public class ShouldRetryException : Exception { /// <summary> /// A delay to wait for next retry /// </summary> public TimeSpan Delay { get; private set; } /// <summary> /// Maximum number of times to retry. /// </summary> public int MaxTimes { get; private set; } /// <summary> /// Creates a ShouldRetryException /// </summary> /// <param name="delay">A delay to wait for next retry</param> /// <param name="maxTimes">Maximum number of times to retry.</param> /// <param name="innerException">the error that caused the job to fail</param> public ShouldRetryException(TimeSpan delay, int maxTimes, Exception innerException) : base("The Job execution failed and should be retried: " + innerException.Message, innerException) { Delay = delay; MaxTimes = maxTimes; } } }
benjamine/Roque
Roque.Core/ShouldRetryException.cs
C#
mit
1,490
/*! * OOUI v0.27.5 * https://www.mediawiki.org/wiki/OOUI * * Copyright 2011–2018 OOUI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2018-07-11T18:13:08Z */ /** * WikimediaUI Base v0.10.0 * Wikimedia Foundation user interface base variables */ .oo-ui-icon-menu { background-image: url('themes/wikimediaui/images/icons/menu.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/menu.svg'); } .oo-ui-image-invert.oo-ui-icon-menu { background-image: url('themes/wikimediaui/images/icons/menu-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/menu-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-menu { background-image: url('themes/wikimediaui/images/icons/menu-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/menu-progressive.svg'); } .oo-ui-icon-stripeFlow { background-image: url('themes/wikimediaui/images/icons/stripeFlow-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeFlow-rtl.svg'); } .oo-ui-image-invert.oo-ui-icon-stripeFlow { background-image: url('themes/wikimediaui/images/icons/stripeFlow-rtl-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeFlow-rtl-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-stripeFlow { background-image: url('themes/wikimediaui/images/icons/stripeFlow-rtl-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeFlow-rtl-progressive.svg'); } .oo-ui-icon-stripeSummary { background-image: url('themes/wikimediaui/images/icons/stripeSummary-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeSummary-rtl.svg'); } .oo-ui-image-invert.oo-ui-icon-stripeSummary { background-image: url('themes/wikimediaui/images/icons/stripeSummary-rtl-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeSummary-rtl-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-stripeSummary { background-image: url('themes/wikimediaui/images/icons/stripeSummary-rtl-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeSummary-rtl-progressive.svg'); } .oo-ui-icon-stripeToC { background-image: url('themes/wikimediaui/images/icons/stripeToC-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeToC-rtl.svg'); } .oo-ui-image-invert.oo-ui-icon-stripeToC { background-image: url('themes/wikimediaui/images/icons/stripeToC-rtl-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeToC-rtl-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-stripeToC { background-image: url('themes/wikimediaui/images/icons/stripeToC-rtl-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/stripeToC-rtl-progressive.svg'); } .oo-ui-icon-viewCompact { background-image: url('themes/wikimediaui/images/icons/viewCompact.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewCompact.svg'); } .oo-ui-image-invert.oo-ui-icon-viewCompact { background-image: url('themes/wikimediaui/images/icons/viewCompact-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewCompact-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-viewCompact { background-image: url('themes/wikimediaui/images/icons/viewCompact-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewCompact-progressive.svg'); } .oo-ui-icon-viewDetails { background-image: url('themes/wikimediaui/images/icons/viewDetails-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewDetails-rtl.svg'); } .oo-ui-image-invert.oo-ui-icon-viewDetails { background-image: url('themes/wikimediaui/images/icons/viewDetails-rtl-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewDetails-rtl-invert.svg'); } .oo-ui-image-progressive.oo-ui-icon-viewDetails { background-image: url('themes/wikimediaui/images/icons/viewDetails-rtl-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/viewDetails-rtl-progressive.svg'); }
sufuf3/cdnjs
ajax/libs/oojs-ui/0.27.5/oojs-ui-wikimediaui-icons-layout.rtl.css
CSS
mit
5,071
# Ignore documentation lints as these aren't original implementations. # rubocop:disable Documentation module Sass::Script # Since the Sass library is already loaded at this point. # Define the `node_name` and `visit_method` class methods for each Sass Script # parse tree node type so that our custom visitor can seamless traverse the # tree. # Define the `invalid_child_method_name` and `invalid_parent_method_name` # class methods to make errors understandable. # # This would be easier if we could just define an `inherited` callback, but # that won't work since the Sass library will have already been loaded before # this code gets loaded, so the `inherited` callback won't be fired. # # Thus we are left to manually define the methods for each type explicitly. { 'Value' => %w[ArgList Bool Color List Map Null Number String], 'Tree' => %w[Funcall Interpolation ListLiteral Literal MapLiteral Operation Selector StringInterpolation UnaryOperation Variable], }.each do |namespace, types| types.each do |type| node_name = type.downcase eval <<-DECL class #{namespace}::#{type} def self.node_name :script_#{node_name} end def self.visit_method :visit_script_#{node_name} end def self.invalid_child_method_name :"invalid_#{node_name}_child?" end def self.invalid_parent_method_name :"invalid_#{node_name}_parent?" end end DECL end end class Value::Base attr_accessor :node_parent def children [] end def line @line || (node_parent && node_parent.line) end def source_range @source_range || (node_parent && node_parent.source_range) end end # Contains extensions of Sass::Script::Tree::Nodes to add support for # accessing various parts of the parse tree not provided out-of-the-box. module Tree class Node attr_accessor :node_parent end class Literal # Literals wrap their underlying values. For sake of convenience, consider # the wrapped value a child of the Literal. def children [value] end end end end
ivantsepp/scss-lint
lib/scss_lint/sass/script.rb
Ruby
mit
2,259
"use strict"; var render = require("../../render"); var src = __dirname + "/src.js"; render( { src: src, template: __dirname + "/../template.hbs", "global-index-format": "none", source: src }, __dirname + "/readme.md" );
daserge/jsdoc-to-markdown
example/tags/todo and done/render.js
JavaScript
mit
267
/** Challenge Activity 2 - Temperature Conversion * * In this activity, we will write a GUI program to convert temperatures to/from * Celcius/Fahrenheit. You should be able to run the program right now but it will * not perform the conversion. Your mission for this activity it to get the * program to perform the conversions and display the correct temperature. * * NOTE: you should be able to find the formulas for conversion from C -> F * and F-> C on-line. * */ package temperatureconversion; public class TempConv extends javax.swing.JFrame { /** * Creates new form TempConv */ public TempConv() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroupConvert = new javax.swing.ButtonGroup(); jButtonConvert = new javax.swing.JButton(); jRadioButtonC = new javax.swing.JRadioButton(); jRadioButtonF = new javax.swing.JRadioButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextTemp = new javax.swing.JTextField(); jLabelAnswer = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Temperature Conversion Program"); jButtonConvert.setText("Convert"); jButtonConvert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonConvertActionPerformed(evt); } }); buttonGroupConvert.add(jRadioButtonC); jRadioButtonC.setSelected(true); jRadioButtonC.setText("Celcius"); buttonGroupConvert.add(jRadioButtonF); jRadioButtonF.setText("Fahrenheit"); jLabel2.setText("Enter Temp:"); jLabel3.setText("Unit"); jTextTemp.setText("0"); jTextTemp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextTempActionPerformed(evt); } }); jLabelAnswer.setToolTipText(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabelAnswer) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextTemp, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButtonC) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButtonF) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonConvert))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextTemp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 1, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButtonF) .addComponent(jRadioButtonC) .addComponent(jLabel3) .addComponent(jButtonConvert)))) .addGap(25, 25, 25) .addComponent(jLabelAnswer) .addContainerGap(51, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConvertActionPerformed // TODO add your handling code here: String target = ""; double temp = Double.parseDouble(this.jTextTemp.getText()); if (this.jRadioButtonC.isSelected()) { temp = 9.0 * temp / 5.0 + 32; target = "Fahrenheit"; } else { temp =5.0 * (temp-32) / 9.0; target = "Celcius"; } this.jLabelAnswer.setText(String.format("%f degrees %s", temp, target)); }//GEN-LAST:event_jButtonConvertActionPerformed private void jTextTempActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextTempActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextTempActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TempConv.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TempConv.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TempConv.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TempConv.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TempConv().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroupConvert; private javax.swing.JButton jButtonConvert; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabelAnswer; private javax.swing.JRadioButton jRadioButtonC; private javax.swing.JRadioButton jRadioButtonF; private javax.swing.JTextField jTextTemp; // End of variables declaration//GEN-END:variables }
Prajwalch27/prajwal
Lesson-18/SOLUTIONS/Solution-ChallengeActivity2-TemperatureConversion/src/temperatureconversion/TempConv.java
Java
mit
8,622
import React from "react"; export default React.createClass({ propTypes: { show: React.PropTypes.bool, viaCSS: React.PropTypes.bool, }, render: function() { if (this.props.viaCSS) { const display = this.props.show ? null : {display: "none"}; return ( <div style={display}>{this.props.children}</div> ); } else { return this.props.show ? this.props.children : null; } }, });
wflmax/webm.js
src/util/show-hide.js
JavaScript
cc0-1.0
435
# MongoDB - Aula 03 - Exercício autor: Hudson Brendon Silva ## Liste todos Pokemons com a altura **menor que** 0.5; ``` ubuntu(mongod-3.0.7) pokemons> db.pokemons.find({height:{$lt: 0.5}}) { "_id": ObjectId("564d08317ba047cbf6497bc8"), "name": "Pikachu", "description": "Rato elétrico bem fofinho", "type": "electric", "attack": 55, "height": 0.4 } { "_id": ObjectId("564d08a07ba047cbf6497bc9"), "name": "Bulbassauro", "description": "Chicote de trepadeira", "type": "grama", "attack": 49, "height": 0.4 } { "_id": ObjectId("564d0a817ba047cbf6497bcc"), "name": "Caterpie", "description": "Larva lutadora", "type": "inseto", "attack": 30, "height": 0.3, "defense": 35 } Fetched 3 record(s) in 31ms ``` ## Liste todos Pokemons com a altura **maior ou igual que** 0.5 ``` ubuntu(mongod-3.0.7) pokemons> db.pokemons.find({height:{$gte: 0.5}}) { "_id": ObjectId("564d08d37ba047cbf6497bca"), "name": "Charmander", "description": "Esse é o cão chupando manga de fofinho", "type": "fogo", "attack": 52, "height": 0.6 } { "_id": ObjectId("564d09007ba047cbf6497bcb"), "name": "Squirtle", "description": "Ejeta água que passarinho não bebe", "type": "água", "attack": 48, "height": 0.5 } Fetched 2 record(s) in 1ms ``` ## Liste todos Pokemons com a altura **menor ou igual que** 0.5 **E** do tipo grama ``` ubuntu(mongod-3.0.7) pokemons> db.pokemons.find({$and: [{height: {$lt: 0.5}}, {type: "grama"}]}) { "_id": ObjectId("564d08a07ba047cbf6497bc9"), "name": "Bulbassauro", "description": "Chicote de trepadeira", "type": "grama", "attack": 49, "height": 0.4 } Fetched 1 record(s) in 2ms ``` ## Liste todos Pokemons com o name `Pikachu` **OU** com attack **menor ou igual que** 0.5 ``` ubuntu(mongod-3.0.7) pokemons> db.pokemons.find({$and: [{name: "Pikachu"}, {attack: {$lte: 0.5}}]}) Fetched 0 record(s) in 0ms ``` ## Liste todos Pokemons com o attack **MAIOR OU IGUAL QUE** 48 **E** com height **menor ou igual que** 0.5 ``` ubuntu(mongod-3.0.7) pokemons> db.pokemons.find({$and: [{height: {$lte: 0.5}}, {attack: {$gte: 48}}]}) { "_id": ObjectId("564d08317ba047cbf6497bc8"), "name": "Pikachu", "description": "Rato elétrico bem fofinho", "type": "electric", "attack": 55, "height": 0.4 } { "_id": ObjectId("564d08a07ba047cbf6497bc9"), "name": "Bulbassauro", "description": "Chicote de trepadeira", "type": "grama", "attack": 49, "height": 0.4 } { "_id": ObjectId("564d09007ba047cbf6497bcb"), "name": "Squirtle", "description": "Ejeta água que passarinho não bebe", "type": "água", "attack": 48, "height": 0.5 } Fetched 3 record(s) in 49ms ```
netoabel/be-mean-instagram-mongodb-exercises
class-03/class03-resolved-hudsonbrendon-Hudson-Brendon.md
Markdown
cc0-1.0
2,673
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.plugin.jdb.server.expression; /** @author andrew00x */ public abstract class ExpressionParser { private final String expression; protected ExpressionParser(String expression) { this.expression = expression; } /** * Create new instance of parser for specified Java expression. * * @param expression * Java language expression * @return concrete implementation of ExpressionParser */ public static ExpressionParser newInstance(String expression) { // At the moment create instance of ANTLRExpressionParser directly. return new ANTLRExpressionParser(expression); } /** * Get expression for this parser. * * @return expression */ public String getExpression() { return expression; } /** * Evaluate expression. * * @param ev * Evaluator * @return result of evaluation * @throws ExpressionException * if specified expression is invalid or another error occurs when try to evaluate expression */ public abstract com.sun.jdi.Value evaluate(Evaluator ev); }
gazarenkov/che-sketch
plugins/plugin-java-debugger/che-plugin-java-debugger-server/src/main/java/org/eclipse/che/plugin/jdb/server/expression/ExpressionParser.java
Java
epl-1.0
1,690
/* * PackageReference.java * * Copyright (c) 2013 Mike Strobel * * This source code is based on Mono.Cecil from Jb Evain, Copyright (c) Jb Evain; * and ILSpy/ICSharpCode from SharpDevelop, Copyright (c) AlphaSierraPapa. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. * A copy of the license can be found in the License.html file at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. */ package com.strobel.assembler.metadata; import com.strobel.core.StringUtilities; import com.strobel.core.VerifyArgument; import java.util.List; public class PackageReference { public final static PackageReference GLOBAL = new PackageReference(); private final PackageReference _parent; private final String _name; private String _fullName; private PackageReference() { _parent = null; _name = StringUtilities.EMPTY; } public PackageReference(final String name) { _parent = null; _name = VerifyArgument.notNull(name, "name"); } public PackageReference(final PackageReference parent, final String name) { _parent = parent; _name = VerifyArgument.notNull(name, "name"); } public final boolean isGlobal() { return _name.length() == 0; } public final String getName() { return _name; } public final String getFullName() { if (_fullName == null) { if (_parent == null || _parent.equals(GLOBAL)) { _fullName = getName(); } else { _fullName = _parent.getFullName() + "." + getName(); } } return _fullName; } public final PackageReference getParent() { return _parent; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o instanceof PackageReference) { final PackageReference that = (PackageReference) o; return _name.equals(that._name) && (_parent == null ? that._parent == null : _parent.equals(that._parent)); } return false; } @Override public int hashCode() { int result = _parent != null ? _parent.hashCode() : 0; result = 31 * result + _name.hashCode(); return result; } public static PackageReference parse(final String qualifiedName) { VerifyArgument.notNull(qualifiedName, "qualifiedName"); final List<String> parts = StringUtilities.split(qualifiedName, '.', '/'); if (parts.isEmpty()) { return GLOBAL; } PackageReference current = new PackageReference(parts.get(0)); for (int i = 1; i < parts.size(); i++) { current = new PackageReference(current, parts.get(i)); } return current; } }
mbriskar/windup
forks/procyon/Procyon.CompilerTools/src/main/java/com/strobel/assembler/metadata/PackageReference.java
Java
epl-1.0
3,167
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.api.event; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; /** * @author Vlad Zhukovskiy * @author Dmitry Shnurenko */ public class ModuleCreatedEvent extends GwtEvent<ModuleCreatedEvent.ModuleCreatedHandler> { public interface ModuleCreatedHandler extends EventHandler { void onModuleCreated(ModuleCreatedEvent event); } private static Type<ModuleCreatedHandler> TYPE; public static Type<ModuleCreatedHandler> getType() { if (TYPE == null) { TYPE = new Type<>(); } return TYPE; } private ProjectConfigDto module; public ModuleCreatedEvent(ProjectConfigDto module) { this.module = module; } public ProjectConfigDto getModule() { return module; } /** {@inheritDoc} */ @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Type<ModuleCreatedHandler> getAssociatedType() { return (Type)TYPE; } @Override protected void dispatch(ModuleCreatedHandler handler) { handler.onModuleCreated(this); } }
gazarenkov/che-sketch
ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/event/ModuleCreatedEvent.java
Java
epl-1.0
1,723
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.squeezebox.internal; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.eclipse.smarthome.core.audio.AudioFormat; import org.eclipse.smarthome.core.audio.AudioHTTPServer; import org.eclipse.smarthome.core.audio.AudioSink; import org.eclipse.smarthome.core.audio.AudioStream; import org.eclipse.smarthome.core.audio.FileAudioStream; import org.eclipse.smarthome.core.audio.FixedLengthAudioStream; import org.eclipse.smarthome.core.audio.URLAudioStream; import org.eclipse.smarthome.core.audio.UnsupportedAudioFormatException; import org.eclipse.smarthome.core.audio.UnsupportedAudioStreamException; import org.eclipse.smarthome.core.audio.utils.AudioStreamUtils; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.library.types.StringType; import org.openhab.binding.squeezebox.internal.handler.SqueezeBoxPlayerHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This makes a SqueezeBox Player serve as an {@link AudioSink}- * * @author Mark Hilbush - Implement AudioSink and notifications */ public class SqueezeBoxAudioSink implements AudioSink { private Logger logger = LoggerFactory.getLogger(SqueezeBoxAudioSink.class); private static final HashSet<AudioFormat> SUPPORTED_FORMATS = new HashSet<>(); private static final HashSet<Class<? extends AudioStream>> SUPPORTED_STREAMS = new HashSet<>(); // Needed because Squeezebox does multiple requests for the stream private final int STREAM_TIMEOUT = 15; static { SUPPORTED_FORMATS.add(AudioFormat.WAV); SUPPORTED_FORMATS.add(AudioFormat.MP3); SUPPORTED_STREAMS.add(FixedLengthAudioStream.class); SUPPORTED_STREAMS.add(URLAudioStream.class); } private AudioHTTPServer audioHTTPServer; private SqueezeBoxPlayerHandler playerHandler; public SqueezeBoxAudioSink(SqueezeBoxPlayerHandler playerHandler, AudioHTTPServer audioHTTPServer) { this.playerHandler = playerHandler; this.audioHTTPServer = audioHTTPServer; } @Override public String getId() { return playerHandler.getThing().getUID().toString(); } @Override public String getLabel(Locale locale) { return playerHandler.getThing().getLabel(); } @Override public void process(AudioStream audioStream) throws UnsupportedAudioFormatException, UnsupportedAudioStreamException { AudioFormat format = audioStream.getFormat(); if (!AudioFormat.WAV.isCompatible(format) && !AudioFormat.MP3.isCompatible(format)) { throw new UnsupportedAudioFormatException("Currently only MP3 and WAV formats are supported: ", format); } String url; if (audioStream instanceof URLAudioStream) { url = ((URLAudioStream) audioStream).getURL(); } else if (audioStream instanceof FixedLengthAudioStream) { // Since Squeezebox will make multiple requests for the stream, set a timeout on the stream url = audioHTTPServer.serve((FixedLengthAudioStream) audioStream, STREAM_TIMEOUT).toString(); if (AudioFormat.WAV.isCompatible(format)) { url += AudioStreamUtils.EXTENSION_SEPARATOR + FileAudioStream.WAV_EXTENSION; } else if (AudioFormat.MP3.isCompatible(format)) { url += AudioStreamUtils.EXTENSION_SEPARATOR + FileAudioStream.MP3_EXTENSION; } // Form the URL for streaming the notification from the OH2 web server String host = playerHandler.getHostAndPort(); if (host == null) { logger.warn("Unable to get host/port from which to stream notification"); return; } url = host + url; } else { throw new UnsupportedAudioStreamException( "SqueezeBox can only handle URLAudioStream or FixedLengthAudioStreams.", null); } logger.debug("Processing audioStream {} of format {}", url, format); playerHandler.playNotificationSoundURI(new StringType(url)); } @Override public Set<AudioFormat> getSupportedFormats() { return SUPPORTED_FORMATS; } @Override public Set<Class<? extends AudioStream>> getSupportedStreams() { return SUPPORTED_STREAMS; } @Override public PercentType getVolume() { return playerHandler.getNotificationSoundVolume(); } @Override public void setVolume(PercentType volume) { playerHandler.setNotificationSoundVolume(volume); } }
gerrieg/openhab2
addons/binding/org.openhab.binding.squeezebox/src/main/java/org/openhab/binding/squeezebox/internal/SqueezeBoxAudioSink.java
Java
epl-1.0
5,000
#pragma once #include "captions-handler.hpp" #include "captions-mssapi-stream.hpp" #include <util/windows/HRError.hpp> #include <util/windows/ComPtr.hpp> #include <util/windows/WinHandle.hpp> #include <util/windows/CoTaskMemPtr.hpp> #include <util/threading.h> #include <util/platform.h> #include <sphelper.h> #include <obs.hpp> #include <thread> class mssapi_captions : public captions_handler { friend class CaptionStream; ComPtr<CaptionStream> audio; ComPtr<ISpObjectToken> token; ComPtr<ISpRecoGrammar> grammar; ComPtr<ISpRecognizer> recognizer; ComPtr<ISpRecoContext> context; HANDLE notify; WinHandle stop; std::thread t; bool started = false; void main_thread(); public: mssapi_captions(captions_cb callback, const std::string &lang); virtual ~mssapi_captions(); virtual void pcm_data(const void *data, size_t frames) override; };
makeen/obs-studio
UI/frontend-plugins/frontend-tools/captions-mssapi.hpp
C++
gpl-2.0
920
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace MediaBrowser.Controller.Entities.Audio { /// <summary> /// Class MusicGenre /// </summary> public class MusicGenre : BaseItem, IItemByName { /// <summary> /// Gets the user data key. /// </summary> /// <returns>System.String.</returns> protected override string CreateUserDataKey() { return "MusicGenre-" + Name; } [IgnoreDataMember] public override bool SupportsAddingToPlaylist { get { return true; } } /// <summary> /// Returns the folder containing the item. /// If the item is a folder, it returns the folder itself /// </summary> /// <value>The containing folder path.</value> [IgnoreDataMember] public override string ContainingFolderPath { get { return Path; } } public override bool CanDelete() { return false; } public override bool IsSaveLocalMetadataEnabled() { return true; } /// <summary> /// Gets a value indicating whether this instance is owned item. /// </summary> /// <value><c>true</c> if this instance is owned item; otherwise, <c>false</c>.</value> [IgnoreDataMember] public override bool IsOwnedItem { get { return false; } } public IEnumerable<BaseItem> GetTaggedItems(IEnumerable<BaseItem> inputItems) { return inputItems.Where(GetItemFilter()); } public Func<BaseItem, bool> GetItemFilter() { return i => (i is IHasMusicGenres) && i.Genres.Contains(Name, StringComparer.OrdinalIgnoreCase); } [IgnoreDataMember] public override bool SupportsPeople { get { return false; } } } }
mtlott/Emby
MediaBrowser.Controller/Entities/Audio/MusicGenre.cs
C#
gpl-2.0
2,132
/* This file is part of the KDE project @@COPYRIGHT@@ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef KCHART_TESTLOADING_H_ME07_PERCENTAGE_STACKED_BAR_CHART #define KCHART_TESTLOADING_H_ME07_PERCENTAGE_STACKED_BAR_CHART #include "../TestLoadingBase.h" #include <QStandardItemModel> namespace KChart { class TestLoading : public TestLoadingBase { Q_OBJECT public: TestLoading(); private slots: void initTestCase(); void testInternalTable(); void testDataSets(); void testLegend(); private: /// Faked data model of sheet embedding this chart QStandardItemModel m_sheet; }; } // namespace KChart #endif // KCHART_TESTLOADING_H_ME07_PERCENTAGE_STACKED_BAR_CHART
KDE/calligra-history
plugins/chartshape/tests/odf/me07_percentage_stacked_bar_chart/TestLoading.h
C
gpl-2.0
1,436
/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2015 Brazil This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #include "../grn_ctx_impl.h" #ifdef GRN_WITH_MRUBY #include <mruby.h> #include <mruby/class.h> #include <mruby/data.h> #include <mruby/variable.h> #include <mruby/string.h> #include "../grn_mrb.h" #include "mrb_query_logger.h" static mrb_value query_logger_need_log_p(mrb_state *mrb, mrb_value self) { grn_ctx *ctx = (grn_ctx *)mrb->ud; mrb_int flag; mrb_get_args(mrb, "i", &flag); return mrb_bool_value(grn_query_logger_pass(ctx, flag)); } static mrb_value query_logger_log_raw(mrb_state *mrb, mrb_value self) { grn_ctx *ctx = (grn_ctx *)mrb->ud; mrb_int flag; char *mark; char *message; mrb_int message_size; mrb_get_args(mrb, "izs", &flag, &mark, &message, &message_size); grn_query_logger_put(ctx, flag, mark, "%.*s", (int)message_size, message); return self; } void grn_mrb_query_logger_init(grn_ctx *ctx) { grn_mrb_data *data = &(ctx->impl->mrb); mrb_state *mrb = data->state; struct RClass *module = data->module; struct RClass *klass; klass = mrb_define_class_under(mrb, module, "QueryLogger", mrb->object_class); mrb_define_method(mrb, klass, "need_log?", query_logger_need_log_p, MRB_ARGS_REQ(1)); mrb_define_method(mrb, klass, "log_raw", query_logger_log_raw, MRB_ARGS_REQ(3)); grn_mrb_load(ctx, "query_logger/flag.rb"); grn_mrb_load(ctx, "query_logger.rb"); } #endif
MariaDB/server
storage/mroonga/vendor/groonga/lib/mrb/mrb_query_logger.c
C
gpl-2.0
2,125
/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * */ #include "vidc.h" #include "vidc_hwio.h" #define VIDC_1080P_INIT_CH_INST_ID 0x0000ffff #define VIDC_1080P_RESET_VI 0x3f7 #define VIDC_1080P_RESET_VI_RISC 0x3f6 #define VIDC_1080P_RESET_VI_VIDC_RISC 0x3f2 #define VIDC_1080P_RESET_ALL 0 #define VIDC_1080P_RESET_RISC 0x3fe #define VIDC_1080P_RESET_NONE 0x3ff #define VIDC_1080P_INTERRUPT_CLEAR 0 #define VIDC_1080P_MAX_H264DECODER_DPB 32 #define VIDC_1080P_MAX_DEC_RECON_BUF 32 #define VIDC_1080P_SI_RG7_DISPLAY_STATUS_MASK 0x00000007 #define VIDC_1080P_SI_RG7_DISPLAY_STATUS_SHIFT 0 #define VIDC_1080P_SI_RG7_DISPLAY_CODING_MASK 0x00000008 #define VIDC_1080P_SI_RG7_DISPLAY_CODING_SHIFT 3 #define VIDC_1080P_SI_RG7_DISPLAY_RES_MASK 0x00000030 #define VIDC_1080P_SI_RG7_DISPLAY_RES_SHIFT 4 #define VIDC_1080P_SI_RG7_DISPLAY_CROP_MASK 0x00000040 #define VIDC_1080P_SI_RG7_DISPLAY_CROP_SHIFT 6 #define VIDC_1080P_SI_RG7_DISPLAY_CORRECT_MASK 0x00000180 #define VIDC_1080P_SI_RG7_DISPLAY_CORRECT_SHIFT 7 #define VIDC_1080P_SI_RG8_DECODE_FRAMETYPE_MASK 0x00000007 #define VIDC_1080P_SI_RG10_NUM_DPB_BMSK 0x00003fff #define VIDC_1080P_SI_RG10_NUM_DPB_SHFT 0 #define VIDC_1080P_SI_RG10_DPB_FLUSH_BMSK 0x00004000 #define VIDC_1080P_SI_RG10_DPB_FLUSH_SHFT 14 #define VIDC_1080P_SI_RG10_DMX_DISABLE_BMSK 0x00008000 #define VIDC_1080P_SI_RG10_DMX_DISABLE_SHFT 15 #define VIDC_1080P_SI_RG11_DECODE_STATUS_MASK 0x00000007 #define VIDC_1080P_SI_RG11_DECODE_STATUS_SHIFT 0 #define VIDC_1080P_SI_RG11_DECODE_CODING_MASK 0x00000008 #define VIDC_1080P_SI_RG11_DECODE_CODING_SHIFT 3 #define VIDC_1080P_SI_RG11_DECODE_RES_MASK 0x000000C0 #define VIDC_1080P_SI_RG11_DECODE_RES_SHIFT 6 #define VIDC_1080P_SI_RG11_DECODE_CROPP_MASK 0x00000100 #define VIDC_1080P_SI_RG11_DECODE_CROPP_SHIFT 8 #define VIDC_1080P_SI_RG11_DECODE_CORRECT_MASK 0x00000600 #define VIDC_1080P_SI_RG11_DECODE_CORRECT_SHIFT 9 #define VIDC_1080P_BASE_OFFSET_SHIFT 11 #define VIDC_1080P_H264DEC_LUMA_ADDR HWIO_REG_759068_ADDR #define VIDC_1080P_H264DEC_CHROMA_ADDR HWIO_REG_515200_ADDR #define VIDC_1080P_H264DEC_MV_PLANE_ADDR HWIO_REG_466192_ADDR #define VIDC_1080P_DEC_LUMA_ADDR HWIO_REG_759068_ADDR #define VIDC_1080P_DEC_CHROMA_ADDR HWIO_REG_515200_ADDR #define VIDC_1080P_DEC_TYPE_SEQ_HEADER 0x00010000 #define VIDC_1080P_DEC_TYPE_FRAME_DATA 0x00020000 #define VIDC_1080P_DEC_TYPE_LAST_FRAME_DATA 0x00030000 #define VIDC_1080P_DEC_TYPE_INIT_BUFFERS 0x00040000 #define VIDC_1080P_ENC_TYPE_SEQ_HEADER 0x00010000 #define VIDC_1080P_ENC_TYPE_FRAME_DATA 0x00020000 #define VIDC_1080P_ENC_TYPE_LAST_FRAME_DATA 0x00030000 #define VIDC_1080P_MAX_INTRA_PERIOD 0xffff u8 *VIDC_BASE_PTR; void vidc_1080p_do_sw_reset(enum vidc_1080p_reset init_flag) { if (init_flag == VIDC_1080P_RESET_IN_SEQ_FIRST_STAGE) { u32 sw_reset_value = 0; VIDC_HWIO_IN(REG_557899, &sw_reset_value); sw_reset_value &= (~HWIO_REG_557899_RSTN_VI_BMSK); VIDC_HWIO_OUT(REG_557899, sw_reset_value); sw_reset_value &= (~HWIO_REG_557899_RSTN_RISC_BMSK); VIDC_HWIO_OUT(REG_557899, sw_reset_value); sw_reset_value &= (~(HWIO_REG_557899_RSTN_VIDCCORE_BMSK | HWIO_REG_557899_RSTN_DMX_BMSK)); VIDC_HWIO_OUT(REG_557899, sw_reset_value); } else if (init_flag == VIDC_1080P_RESET_IN_SEQ_SECOND_STAGE) { VIDC_HWIO_OUT(REG_557899, VIDC_1080P_RESET_ALL); VIDC_HWIO_OUT(REG_557899, VIDC_1080P_RESET_RISC); } } void vidc_1080p_release_sw_reset(void) { u32 nAxiCtl; u32 nAxiStatus; u32 nRdWrBurst; nAxiCtl = VIDC_SETFIELD(1, HWIO_REG_471159_AXI_HALT_REQ_SHFT, HWIO_REG_471159_AXI_HALT_REQ_BMSK); VIDC_HWIO_OUT(REG_471159, nAxiCtl); do { VIDC_HWIO_IN(REG_437878, &nAxiStatus); nAxiStatus = VIDC_GETFIELD(nAxiStatus, HWIO_REG_437878_AXI_HALT_ACK_BMSK, HWIO_REG_437878_AXI_HALT_ACK_SHFT); } while (0x3 != nAxiStatus); nAxiCtl = VIDC_SETFIELD(1, HWIO_REG_471159_AXI_RESET_SHFT, HWIO_REG_471159_AXI_RESET_BMSK); VIDC_HWIO_OUT(REG_471159, nAxiCtl); VIDC_HWIO_OUT(REG_471159, 0); nRdWrBurst = VIDC_SETFIELD(8, HWIO_REG_922106_XBAR_OUT_MAX_RD_BURST_SHFT, HWIO_REG_922106_XBAR_OUT_MAX_RD_BURST_BMSK) | VIDC_SETFIELD(8, HWIO_REG_922106_XBAR_OUT_MAX_WR_BURST_SHFT, HWIO_REG_922106_XBAR_OUT_MAX_WR_BURST_BMSK); VIDC_HWIO_OUT(REG_922106, nRdWrBurst); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_611794, VIDC_1080P_HOST2RISC_CMD_EMPTY); VIDC_HWIO_OUT(REG_557899, VIDC_1080P_RESET_NONE); } void vidc_1080p_clear_interrupt(void) { VIDC_HWIO_OUT(REG_575377, VIDC_1080P_INTERRUPT_CLEAR); } void vidc_1080p_set_host2risc_cmd(enum vidc_1080p_host2risc_cmd host2risc_command, u32 host2risc_arg1, u32 host2risc_arg2, u32 host2risc_arg3, u32 host2risc_arg4) { VIDC_HWIO_OUT(REG_611794, VIDC_1080P_HOST2RISC_CMD_EMPTY); VIDC_HWIO_OUT(REG_356340, host2risc_arg1); VIDC_HWIO_OUT(REG_899023, host2risc_arg2); VIDC_HWIO_OUT(REG_987762, host2risc_arg3); VIDC_HWIO_OUT(REG_544000, host2risc_arg4); VIDC_HWIO_OUT(REG_611794, host2risc_command); } void vidc_1080p_get_risc2host_cmd(u32 *pn_risc2host_command, u32 *pn_risc2host_arg1, u32 *pn_risc2host_arg2, u32 *pn_risc2host_arg3, u32 *pn_risc2host_arg4) { VIDC_HWIO_IN(REG_695082, pn_risc2host_command); VIDC_HWIO_IN(REG_156596, pn_risc2host_arg1); VIDC_HWIO_IN(REG_222292, pn_risc2host_arg2); VIDC_HWIO_IN(REG_790962, pn_risc2host_arg3); VIDC_HWIO_IN(REG_679882, pn_risc2host_arg4); } void vidc_1080p_get_risc2host_cmd_status(u32 err_status, u32 *dec_err_status, u32 *disp_err_status) { *dec_err_status = VIDC_GETFIELD(err_status, VIDC_RISC2HOST_ARG2_VIDC_DEC_ERROR_STATUS_BMSK, VIDC_RISC2HOST_ARG2_VIDC_DEC_ERROR_STATUS_SHFT); *disp_err_status = VIDC_GETFIELD(err_status, VIDC_RISC2HOST_ARG2_VIDC_DISP_ERROR_STATUS_BMSK, VIDC_RISC2HOST_ARG2_VIDC_DISP_ERROR_STATUS_SHFT); } void vidc_1080p_clear_risc2host_cmd(void) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); } void vidc_1080p_get_fw_version(u32 *pn_fw_version) { VIDC_HWIO_IN(REG_653206, pn_fw_version); } void vidc_1080p_get_fw_status(u32 *pn_fw_status) { VIDC_HWIO_IN(REG_350619, pn_fw_status); } void vidc_1080p_init_memory_controller(u32 dram_base_addr_a, u32 dram_base_addr_b) { VIDC_HWIO_OUT(REG_64440, dram_base_addr_a); VIDC_HWIO_OUT(REG_675915, dram_base_addr_b); } void vidc_1080p_get_memory_controller_status(u32 *pb_mc_abusy, u32 *pb_mc_bbusy) { u32 mc_status = 0; VIDC_HWIO_IN(REG_399911, &mc_status); *pb_mc_abusy = (u32) ((mc_status & HWIO_REG_399911_MC_BUSY_A_BMSK) >> HWIO_REG_399911_MC_BUSY_A_SHFT); *pb_mc_bbusy = (u32) ((mc_status & HWIO_REG_399911_MC_BUSY_B_BMSK) >> HWIO_REG_399911_MC_BUSY_B_SHFT); } void vidc_1080p_set_h264_decode_buffers(u32 dpb, u32 dec_vert_nb_mv_offset, u32 dec_nb_ip_offset, u32 *pn_dpb_luma_offset, u32 *pn_dpb_chroma_offset, u32 *pn_mv_buffer_offset) { u32 count = 0, num_dpb_used = dpb; u8 *vidc_dpb_luma_reg = (u8 *) VIDC_1080P_H264DEC_LUMA_ADDR; u8 *vidc_dpb_chroma_reg = (u8 *) VIDC_1080P_H264DEC_CHROMA_ADDR; u8 *vidc_mv_buffer_reg = (u8 *) VIDC_1080P_H264DEC_MV_PLANE_ADDR; VIDC_HWIO_OUT(REG_931311, (dec_vert_nb_mv_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_16277, (dec_nb_ip_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); if (num_dpb_used > VIDC_1080P_MAX_H264DECODER_DPB) num_dpb_used = VIDC_1080P_MAX_H264DECODER_DPB; for (count = 0; count < num_dpb_used; count++) { VIDC_OUT_DWORD(vidc_dpb_luma_reg, (pn_dpb_luma_offset[count] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_OUT_DWORD(vidc_dpb_chroma_reg, (pn_dpb_chroma_offset[count] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_OUT_DWORD(vidc_mv_buffer_reg, (pn_mv_buffer_offset[count] >> VIDC_1080P_BASE_OFFSET_SHIFT)); vidc_dpb_luma_reg += 4; vidc_dpb_chroma_reg += 4; vidc_mv_buffer_reg += 4; } } void vidc_1080p_set_decode_recon_buffers(u32 recon_buffer, u32 *pn_dec_luma, u32 *pn_dec_chroma) { u32 count = 0, recon_buf_to_program = recon_buffer; u8 *dec_recon_luma_reg = (u8 *) VIDC_1080P_DEC_LUMA_ADDR; u8 *dec_recon_chroma_reg = (u8 *) VIDC_1080P_DEC_CHROMA_ADDR; if (recon_buf_to_program > VIDC_1080P_MAX_DEC_RECON_BUF) recon_buf_to_program = VIDC_1080P_MAX_DEC_RECON_BUF; for (count = 0; count < recon_buf_to_program; count++) { VIDC_OUT_DWORD(dec_recon_luma_reg, (pn_dec_luma[count] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_OUT_DWORD(dec_recon_chroma_reg, (pn_dec_chroma[count] >> VIDC_1080P_BASE_OFFSET_SHIFT)); dec_recon_luma_reg += 4; dec_recon_chroma_reg += 4; } } void vidc_1080p_set_mpeg4_divx_decode_work_buffers(u32 nb_dcac_buffer_offset, u32 upnb_mv_buffer_offset, u32 sub_anchor_buffer_offset, u32 overlay_transform_buffer_offset, u32 stx_parser_buffer_offset) { VIDC_HWIO_OUT(REG_931311, (nb_dcac_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_16277, (upnb_mv_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_654169, (sub_anchor_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_802794, (overlay_transform_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_252167, (stx_parser_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_h263_decode_work_buffers(u32 nb_dcac_buffer_offset, u32 upnb_mv_buffer_offset, u32 sub_anchor_buffer_offset, u32 overlay_transform_buffer_offset) { VIDC_HWIO_OUT(REG_931311, (nb_dcac_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_16277, (upnb_mv_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_654169, (sub_anchor_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_802794, (overlay_transform_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_vc1_decode_work_buffers(u32 nb_dcac_buffer_offset, u32 upnb_mv_buffer_offset, u32 sub_anchor_buffer_offset, u32 overlay_transform_buffer_offset, u32 bitplain1Buffer_offset, u32 bitplain2Buffer_offset, u32 bitplain3Buffer_offset) { VIDC_HWIO_OUT(REG_931311, (nb_dcac_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_16277, (upnb_mv_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_654169, (sub_anchor_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_802794, (overlay_transform_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_724376, (bitplain3Buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_551674, (bitplain2Buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_115991, (bitplain1Buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_encode_recon_buffers(u32 recon_buffer, u32 *pn_enc_luma, u32 *pn_enc_chroma) { if (recon_buffer > 0) { VIDC_HWIO_OUT(REG_294579, (pn_enc_luma[0] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_759068, (pn_enc_chroma[0] >> VIDC_1080P_BASE_OFFSET_SHIFT)); } if (recon_buffer > 1) { VIDC_HWIO_OUT(REG_616802, (pn_enc_luma[1] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_833502, (pn_enc_chroma[1] >> VIDC_1080P_BASE_OFFSET_SHIFT)); } if (recon_buffer > 2) { VIDC_HWIO_OUT(REG_61427, (pn_enc_luma[2] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_68356, (pn_enc_chroma[2] >> VIDC_1080P_BASE_OFFSET_SHIFT)); } if (recon_buffer > 3) { VIDC_HWIO_OUT(REG_23318, (pn_enc_luma[3] >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_127855, (pn_enc_chroma[3] >> VIDC_1080P_BASE_OFFSET_SHIFT)); } } void vidc_1080p_set_h264_encode_work_buffers(u32 up_row_mv_buffer_offset, u32 direct_colzero_flag_buffer_offset, u32 upper_intra_md_buffer_offset, u32 upper_intra_pred_buffer_offset, u32 nbor_infor_buffer_offset, u32 mb_info_offset) { VIDC_HWIO_OUT(REG_515200, (up_row_mv_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_69832, (direct_colzero_flag_buffer_offset>> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_256132, (upper_intra_md_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_475648, (upper_intra_pred_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_29510, (nbor_infor_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_175929, (mb_info_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_h263_encode_work_buffers(u32 up_row_mv_buffer_offset, u32 up_row_inv_quanti_coeff_buffer_offset) { VIDC_HWIO_OUT(REG_515200, (up_row_mv_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_29510, ( up_row_inv_quanti_coeff_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_mpeg4_encode_work_buffers(u32 skip_flag_buffer_offset, u32 up_row_inv_quanti_coeff_buffer_offset, u32 upper_mv_offset) { VIDC_HWIO_OUT(REG_69832, (skip_flag_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_29510, ( up_row_inv_quanti_coeff_buffer_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); VIDC_HWIO_OUT(REG_515200, (upper_mv_offset >> VIDC_1080P_BASE_OFFSET_SHIFT)); } void vidc_1080p_set_encode_frame_size(u32 hori_size, u32 vert_size) { VIDC_HWIO_OUT(REG_934655, hori_size); VIDC_HWIO_OUT(REG_179070, vert_size); } void vidc_1080p_set_encode_profile_level(u32 encode_profile, u32 enc_level) { u32 profile_level = 0; profile_level = VIDC_SETFIELD(enc_level, HWIO_REG_63643_LEVEL_SHFT, HWIO_REG_63643_LEVEL_BMSK) | VIDC_SETFIELD(encode_profile, HWIO_REG_63643_PROFILE_SHFT, HWIO_REG_63643_PROFILE_BMSK); VIDC_HWIO_OUT(REG_63643, profile_level); } void vidc_1080p_set_encode_field_picture_structure(u32 enc_field_picture) { VIDC_HWIO_OUT(REG_786024, enc_field_picture); } void vidc_1080p_set_decode_mpeg4_pp_filter(u32 lf_enables) { VIDC_HWIO_OUT(REG_152500, lf_enables); } void vidc_1080p_set_decode_qp_save_control(u32 enable_q_pout) { VIDC_HWIO_OUT(REG_143629, enable_q_pout); } void vidc_1080p_get_returned_channel_inst_id(u32 *pn_rtn_chid) { VIDC_HWIO_IN(REG_607589, pn_rtn_chid); } void vidc_1080p_clear_returned_channel_inst_id(void) { VIDC_HWIO_OUT(REG_607589, VIDC_1080P_INIT_CH_INST_ID); } void vidc_1080p_get_decode_seq_start_result( struct vidc_1080p_seq_hdr_info *seq_hdr_info) { u32 dec_disp_result; u32 frame = 0; VIDC_HWIO_IN(REG_845544, &seq_hdr_info->img_size_y); VIDC_HWIO_IN(REG_859906, &seq_hdr_info->img_size_x); VIDC_HWIO_IN(REG_490078, &seq_hdr_info->min_num_dpb); VIDC_HWIO_IN(REG_489688, &seq_hdr_info->dec_frm_size); VIDC_HWIO_IN(REG_853667, &dec_disp_result); seq_hdr_info->disp_progressive = VIDC_GETFIELD(dec_disp_result, VIDC_1080P_SI_RG7_DISPLAY_CODING_MASK, VIDC_1080P_SI_RG7_DISPLAY_CODING_SHIFT); seq_hdr_info->disp_crop_exists = VIDC_GETFIELD(dec_disp_result, VIDC_1080P_SI_RG7_DISPLAY_CROP_MASK, VIDC_1080P_SI_RG7_DISPLAY_CROP_SHIFT); VIDC_HWIO_IN(REG_692991, &dec_disp_result); seq_hdr_info->dec_progressive = VIDC_GETFIELD(dec_disp_result, VIDC_1080P_SI_RG11_DECODE_CODING_MASK, VIDC_1080P_SI_RG11_DECODE_CODING_SHIFT); seq_hdr_info->dec_crop_exists = VIDC_GETFIELD(dec_disp_result, VIDC_1080P_SI_RG11_DECODE_CROPP_MASK, VIDC_1080P_SI_RG11_DECODE_CROPP_SHIFT); VIDC_HWIO_IN(REG_760102, &frame); seq_hdr_info->data_partition = ((frame & 0x8) >> 3); } void vidc_1080p_get_decoded_frame_size(u32 *pn_decoded_size) { VIDC_HWIO_IN(REG_489688, pn_decoded_size); } void vidc_1080p_get_display_frame_result( struct vidc_1080p_dec_disp_info *dec_disp_info) { u32 display_result; VIDC_HWIO_IN(REG_640904, &dec_disp_info->display_y_addr); VIDC_HWIO_IN(REG_60114, &dec_disp_info->display_c_addr); VIDC_HWIO_IN(REG_853667, &display_result); dec_disp_info->display_status = (enum vidc_1080p_display_status) VIDC_GETFIELD(display_result, VIDC_1080P_SI_RG7_DISPLAY_STATUS_MASK, VIDC_1080P_SI_RG7_DISPLAY_STATUS_SHIFT); dec_disp_info->display_coding = (enum vidc_1080p_display_coding) VIDC_GETFIELD(display_result, VIDC_1080P_SI_RG7_DISPLAY_CODING_MASK, VIDC_1080P_SI_RG7_DISPLAY_CODING_SHIFT); dec_disp_info->disp_resl_change = VIDC_GETFIELD(display_result, VIDC_1080P_SI_RG7_DISPLAY_RES_MASK, VIDC_1080P_SI_RG7_DISPLAY_RES_SHIFT); dec_disp_info->disp_crop_exists = VIDC_GETFIELD(display_result, VIDC_1080P_SI_RG7_DISPLAY_CROP_MASK, VIDC_1080P_SI_RG7_DISPLAY_CROP_SHIFT); dec_disp_info->display_correct = VIDC_GETFIELD(display_result, VIDC_1080P_SI_RG7_DISPLAY_CORRECT_MASK, VIDC_1080P_SI_RG7_DISPLAY_CORRECT_SHIFT); } void vidc_1080p_get_decode_frame( enum vidc_1080p_decode_frame *pe_frame) { u32 frame = 0; VIDC_HWIO_IN(REG_760102, &frame); *pe_frame = (enum vidc_1080p_decode_frame) (frame & VIDC_1080P_SI_RG8_DECODE_FRAMETYPE_MASK); } void vidc_1080p_get_decode_frame_result( struct vidc_1080p_dec_disp_info *dec_disp_info) { u32 decode_result; VIDC_HWIO_IN(REG_378318, &dec_disp_info->decode_y_addr); VIDC_HWIO_IN(REG_203487, &dec_disp_info->decode_c_addr); VIDC_HWIO_IN(REG_692991, &decode_result); dec_disp_info->decode_status = (enum vidc_1080p_display_status) VIDC_GETFIELD(decode_result, VIDC_1080P_SI_RG11_DECODE_STATUS_MASK, VIDC_1080P_SI_RG11_DECODE_STATUS_SHIFT); dec_disp_info->decode_coding = (enum vidc_1080p_display_coding) VIDC_GETFIELD(decode_result, VIDC_1080P_SI_RG11_DECODE_CODING_MASK, VIDC_1080P_SI_RG11_DECODE_CODING_SHIFT); dec_disp_info->dec_resl_change = VIDC_GETFIELD(decode_result, VIDC_1080P_SI_RG11_DECODE_RES_MASK, VIDC_1080P_SI_RG11_DECODE_RES_SHIFT); dec_disp_info->dec_crop_exists = VIDC_GETFIELD(decode_result, VIDC_1080P_SI_RG11_DECODE_CROPP_MASK, VIDC_1080P_SI_RG11_DECODE_CROPP_SHIFT); dec_disp_info->decode_correct = VIDC_GETFIELD(decode_result, VIDC_1080P_SI_RG11_DECODE_CORRECT_MASK, VIDC_1080P_SI_RG11_DECODE_CORRECT_SHIFT); } void vidc_1080p_decode_seq_start_ch0( struct vidc_1080p_dec_seq_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_117192, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_145068, param->stream_frame_size); VIDC_HWIO_OUT(REG_921356, param->descriptor_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_190381, param->stream_buffersize); VIDC_HWIO_OUT(REG_85655, param->descriptor_buffer_size); VIDC_HWIO_OUT(REG_889944, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_397087, param->cmd_seq_num); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_DEC_TYPE_SEQ_HEADER | param->inst_id); } void vidc_1080p_decode_seq_start_ch1( struct vidc_1080p_dec_seq_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_980194, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_936704, param->stream_frame_size); VIDC_HWIO_OUT(REG_821977, param->descriptor_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_887095, param->stream_buffersize); VIDC_HWIO_OUT(REG_576987, param->descriptor_buffer_size); VIDC_HWIO_OUT(REG_652528, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_254093, param->cmd_seq_num); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_DEC_TYPE_SEQ_HEADER | param->inst_id); } void vidc_1080p_decode_frame_start_ch0( struct vidc_1080p_dec_frame_start_param *param) { u32 dpb_config; VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); if ((param->decode == VIDC_1080P_DEC_TYPE_LAST_FRAME_DATA) && ((!param->stream_buffer_addr_offset) || (!param->stream_frame_size))) { VIDC_HWIO_OUT(REG_117192, 0); VIDC_HWIO_OUT(REG_145068, 0); VIDC_HWIO_OUT(REG_190381, 0); } else { VIDC_HWIO_OUT(REG_117192, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_145068, param->stream_frame_size); VIDC_HWIO_OUT(REG_190381, param->stream_buffersize); } dpb_config = VIDC_SETFIELD(param->dpb_flush, VIDC_1080P_SI_RG10_DPB_FLUSH_SHFT, VIDC_1080P_SI_RG10_DPB_FLUSH_BMSK) | VIDC_SETFIELD(param->dpb_count, VIDC_1080P_SI_RG10_NUM_DPB_SHFT, VIDC_1080P_SI_RG10_NUM_DPB_BMSK); VIDC_HWIO_OUT(REG_921356, param->descriptor_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_85655, param->descriptor_buffer_size); VIDC_HWIO_OUT(REG_86830, param->release_dpb_bit_mask); VIDC_HWIO_OUT(REG_889944, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_404623, dpb_config); VIDC_HWIO_OUT(REG_397087, param->cmd_seq_num); VIDC_HWIO_OUT(REG_666957, (u32)param->decode | param->inst_id); } void vidc_1080p_decode_frame_start_ch1( struct vidc_1080p_dec_frame_start_param *param) { u32 dpb_config; VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); if ((param->decode == VIDC_1080P_DEC_TYPE_LAST_FRAME_DATA) && ((!param->stream_buffer_addr_offset) || (!param->stream_frame_size))) { VIDC_HWIO_OUT(REG_980194, 0); VIDC_HWIO_OUT(REG_936704, 0); VIDC_HWIO_OUT(REG_887095, 0); } else { VIDC_HWIO_OUT(REG_980194, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_936704, param->stream_frame_size); VIDC_HWIO_OUT(REG_887095, param->stream_buffersize); } dpb_config = VIDC_SETFIELD(param->dpb_flush, VIDC_1080P_SI_RG10_DPB_FLUSH_SHFT, VIDC_1080P_SI_RG10_DPB_FLUSH_BMSK) | VIDC_SETFIELD(param->dpb_count, VIDC_1080P_SI_RG10_NUM_DPB_SHFT, VIDC_1080P_SI_RG10_NUM_DPB_BMSK); VIDC_HWIO_OUT(REG_821977, param->descriptor_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_576987, param->descriptor_buffer_size); VIDC_HWIO_OUT(REG_70448, param->release_dpb_bit_mask); VIDC_HWIO_OUT(REG_652528, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_220637, dpb_config); VIDC_HWIO_OUT(REG_254093, param->cmd_seq_num); VIDC_HWIO_OUT(REG_313350, (u32)param->decode | param->inst_id); } void vidc_1080p_decode_init_buffers_ch0( struct vidc_1080p_dec_init_buffers_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_889944, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_404623, param->dpb_count); VIDC_HWIO_OUT(REG_397087, param->cmd_seq_num); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_DEC_TYPE_INIT_BUFFERS | param->inst_id); } void vidc_1080p_decode_init_buffers_ch1( struct vidc_1080p_dec_init_buffers_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_652528, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_220637, param->dpb_count); VIDC_HWIO_OUT(REG_254093, param->cmd_seq_num); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_DEC_TYPE_INIT_BUFFERS | param->inst_id); } void vidc_1080p_set_divx3_resolution_ch0(u32 width, u32 height) { VIDC_HWIO_OUT(REG_612810, height); VIDC_HWIO_OUT(REG_175608, width); } void vidc_1080p_set_divx3_resolution_ch1(u32 width, u32 height) { VIDC_HWIO_OUT(REG_655721, height); VIDC_HWIO_OUT(REG_548308, width); } void vidc_1080p_get_encode_frame_info( struct vidc_1080p_enc_frame_info *frame_info) { VIDC_HWIO_IN(REG_845544, &(frame_info->enc_frame_size)); VIDC_HWIO_IN(REG_859906, &(frame_info->enc_picture_count)); VIDC_HWIO_IN(REG_490078, &(frame_info->enc_write_pointer)); VIDC_HWIO_IN(REG_640904, (u32 *)(&(frame_info->enc_frame))); VIDC_HWIO_IN(REG_60114, &(frame_info->enc_luma_address)); frame_info->enc_luma_address = frame_info->enc_luma_address << VIDC_1080P_BASE_OFFSET_SHIFT; VIDC_HWIO_IN(REG_489688, &(frame_info->enc_chroma_address)); frame_info->enc_chroma_address = frame_info->\ enc_chroma_address << VIDC_1080P_BASE_OFFSET_SHIFT; } void vidc_1080p_encode_seq_start_ch0( struct vidc_1080p_enc_seq_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_117192, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_921356, param->stream_buffer_size); VIDC_HWIO_OUT(REG_889944, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_397087, param->cmd_seq_num); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_ENC_TYPE_SEQ_HEADER | param->inst_id); } void vidc_1080p_encode_seq_start_ch1( struct vidc_1080p_enc_seq_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_980194, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_821977, param->stream_buffer_size); VIDC_HWIO_OUT(REG_652528, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_254093, param->cmd_seq_num); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_ENC_TYPE_SEQ_HEADER | param->inst_id); } void vidc_1080p_encode_frame_start_ch0( struct vidc_1080p_enc_frame_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_666957, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_117192, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_921356, param->stream_buffer_size); VIDC_HWIO_OUT(REG_612810, param->current_y_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_175608, param->current_c_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_190381, param->intra_frame); VIDC_HWIO_OUT(REG_889944, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_404623, param->input_flush); VIDC_HWIO_OUT(REG_397087, param->cmd_seq_num); VIDC_HWIO_OUT(REG_666957, (u32)param->encode | param->inst_id); } void vidc_1080p_encode_frame_start_ch1( struct vidc_1080p_enc_frame_start_param *param) { VIDC_HWIO_OUT(REG_695082, VIDC_1080P_RISC2HOST_CMD_EMPTY); VIDC_HWIO_OUT(REG_313350, VIDC_1080P_INIT_CH_INST_ID); VIDC_HWIO_OUT(REG_980194, param->stream_buffer_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_821977, param->stream_buffer_size); VIDC_HWIO_OUT(REG_655721, param->current_y_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_548308, param->current_c_addr_offset >> VIDC_1080P_BASE_OFFSET_SHIFT); VIDC_HWIO_OUT(REG_887095, param->intra_frame); VIDC_HWIO_OUT(REG_652528, param->shared_mem_addr_offset); VIDC_HWIO_OUT(REG_404623, param->input_flush); VIDC_HWIO_OUT(REG_254093, param->cmd_seq_num); VIDC_HWIO_OUT(REG_313350, (u32)param->encode | param->inst_id); } void vidc_1080p_set_encode_picture(u32 number_p, u32 number_b) { u32 picture, ifrm_ctrl; if (number_p >= VIDC_1080P_MAX_INTRA_PERIOD) ifrm_ctrl = 0; else ifrm_ctrl = number_p + 1; picture = VIDC_SETFIELD(1 , HWIO_REG_783891_ENC_PIC_TYPE_USE_SHFT, HWIO_REG_783891_ENC_PIC_TYPE_USE_BMSK) | VIDC_SETFIELD(ifrm_ctrl, HWIO_REG_783891_I_FRM_CTRL_SHFT, HWIO_REG_783891_I_FRM_CTRL_BMSK) | VIDC_SETFIELD(number_b , HWIO_REG_783891_B_FRM_CTRL_SHFT , HWIO_REG_783891_B_FRM_CTRL_BMSK); VIDC_HWIO_OUT(REG_783891, picture); } void vidc_1080p_set_encode_multi_slice_control( enum vidc_1080p_MSlice_selection multiple_slice_selection, u32 mslice_mb, u32 mslice_byte) { VIDC_HWIO_OUT(REG_226332, multiple_slice_selection); VIDC_HWIO_OUT(REG_696136, mslice_mb); VIDC_HWIO_OUT(REG_515564, mslice_byte); } void vidc_1080p_set_encode_circular_intra_refresh(u32 cir_num) { VIDC_HWIO_OUT(REG_886210, cir_num); } void vidc_1080p_set_encode_input_frame_format( enum vidc_1080p_memory_access_method memory_format) { VIDC_HWIO_OUT(REG_645603, memory_format); } void vidc_1080p_set_encode_padding_control(u32 pad_ctrl_on, u32 cr_pad_val, u32 cb_pad_val, u32 luma_pad_val) { u32 padding = VIDC_SETFIELD(pad_ctrl_on , HWIO_REG_811733_PAD_CTRL_ON_SHFT, HWIO_REG_811733_PAD_CTRL_ON_BMSK) | VIDC_SETFIELD(cr_pad_val , HWIO_REG_811733_CR_PAD_VIDC_SHFT , HWIO_REG_811733_CR_PAD_VIDC_BMSK) | VIDC_SETFIELD(cb_pad_val , HWIO_REG_811733_CB_PAD_VIDC_SHFT , HWIO_REG_811733_CB_PAD_VIDC_BMSK) | VIDC_SETFIELD(luma_pad_val , HWIO_REG_811733_LUMA_PAD_VIDC_SHFT , HWIO_REG_811733_LUMA_PAD_VIDC_BMSK) ; VIDC_HWIO_OUT(REG_811733, padding); } void vidc_1080p_encode_set_rc_config(u32 enable_frame_level_rc, u32 enable_mb_level_rc_flag, u32 frame_qp) { u32 rc_config = VIDC_SETFIELD(enable_frame_level_rc , HWIO_REG_559908_FR_RC_EN_SHFT , HWIO_REG_559908_FR_RC_EN_BMSK) | VIDC_SETFIELD(enable_mb_level_rc_flag , HWIO_REG_559908_MB_RC_EN_SHFT, HWIO_REG_559908_MB_RC_EN_BMSK) | VIDC_SETFIELD(frame_qp , HWIO_REG_559908_FRAME_QP_SHFT , HWIO_REG_559908_FRAME_QP_BMSK); VIDC_HWIO_OUT(REG_559908, rc_config); } void vidc_1080p_encode_set_frame_level_rc_params(u32 rc_frame_rate, u32 target_bitrate, u32 reaction_coeff) { VIDC_HWIO_OUT(REG_977937, rc_frame_rate); VIDC_HWIO_OUT(REG_166135, target_bitrate); VIDC_HWIO_OUT(REG_550322, reaction_coeff); } void vidc_1080p_encode_set_qp_params(u32 max_qp, u32 min_qp) { u32 qbound = VIDC_SETFIELD(max_qp , HWIO_REG_109072_MAX_QP_SHFT, HWIO_REG_109072_MAX_QP_BMSK) | VIDC_SETFIELD(min_qp, HWIO_REG_109072_MIN_QP_SHFT , HWIO_REG_109072_MIN_QP_BMSK); VIDC_HWIO_OUT(REG_109072, qbound); } void vidc_1080p_encode_set_mb_level_rc_params(u32 disable_dark_region_as_flag, u32 disable_smooth_region_as_flag , u32 disable_static_region_as_flag, u32 disable_activity_region_flag) { u32 rc_active_feature = VIDC_SETFIELD( disable_dark_region_as_flag, HWIO_REG_949086_DARK_DISABLE_SHFT, HWIO_REG_949086_DARK_DISABLE_BMSK) | VIDC_SETFIELD( disable_smooth_region_as_flag, HWIO_REG_949086_SMOOTH_DISABLE_SHFT, HWIO_REG_949086_SMOOTH_DISABLE_BMSK) | VIDC_SETFIELD( disable_static_region_as_flag, HWIO_REG_949086_STATIC_DISABLE_SHFT, HWIO_REG_949086_STATIC_DISABLE_BMSK) | VIDC_SETFIELD( disable_activity_region_flag, HWIO_REG_949086_ACT_DISABLE_SHFT, HWIO_REG_949086_ACT_DISABLE_BMSK); VIDC_HWIO_OUT(REG_949086, rc_active_feature); } void vidc_1080p_set_h264_encode_entropy( enum vidc_1080p_entropy_sel entropy_sel) { VIDC_HWIO_OUT(REG_447796, entropy_sel); } void vidc_1080p_set_h264_encode_loop_filter( enum vidc_1080p_DBConfig db_config, u32 slice_alpha_offset, u32 slice_beta_offset) { VIDC_HWIO_OUT(REG_152500, db_config); VIDC_HWIO_OUT(REG_266285, slice_alpha_offset); VIDC_HWIO_OUT(REG_964731, slice_beta_offset); } void vidc_1080p_set_h264_encoder_p_frame_ref_count(u32 max_reference) { u32 ref_frames; ref_frames = VIDC_SETFIELD(max_reference, HWIO_REG_744348_P_SHFT, HWIO_REG_744348_P_BMSK); VIDC_HWIO_OUT(REG_744348, ref_frames); } void vidc_1080p_set_h264_encode_8x8transform_control(u32 enable_8x8transform) { VIDC_HWIO_OUT(REG_672163, enable_8x8transform); } void vidc_1080p_set_mpeg4_encode_quarter_pel_control( u32 enable_mpeg4_quarter_pel) { VIDC_HWIO_OUT(REG_330132, enable_mpeg4_quarter_pel); } void vidc_1080p_set_device_base_addr(u8 *mapped_va) { VIDC_BASE_PTR = mapped_va; } void vidc_1080p_get_intra_bias(u32 *bias) { u32 intra_bias; VIDC_HWIO_IN(REG_676866, &intra_bias); *bias = VIDC_GETFIELD(intra_bias, HWIO_REG_676866_RMSK, HWIO_REG_676866_SHFT); } void vidc_1080p_set_intra_bias(u32 bias) { u32 intra_bias; intra_bias = VIDC_SETFIELD(bias, HWIO_REG_676866_SHFT, HWIO_REG_676866_RMSK); VIDC_HWIO_OUT(REG_676866, intra_bias); } void vidc_1080p_get_bi_directional_bias(u32 *bi_directional_bias) { u32 nbi_direct_bias; VIDC_HWIO_IN(REG_54267, &nbi_direct_bias); *bi_directional_bias = VIDC_GETFIELD(nbi_direct_bias, HWIO_REG_54267_RMSK, HWIO_REG_54267_SHFT); } void vidc_1080p_set_bi_directional_bias(u32 bi_directional_bias) { u32 nbi_direct_bias; nbi_direct_bias = VIDC_SETFIELD(bi_directional_bias, HWIO_REG_54267_SHFT, HWIO_REG_54267_RMSK); VIDC_HWIO_OUT(REG_54267, nbi_direct_bias); } void vidc_1080p_get_encoder_sequence_header_size(u32 *seq_header_size) { VIDC_HWIO_IN(REG_845544, seq_header_size); } void vidc_1080p_get_intermedia_stage_debug_counter( u32 *intermediate_stage_counter) { VIDC_HWIO_IN(REG_805993, intermediate_stage_counter); } void vidc_1080p_get_exception_status(u32 *exception_status) { VIDC_HWIO_IN(REG_493355, exception_status); }
faux123/htc-kernel-pyramid
drivers/video/msm_8x60/vidc/1080p/ddl/vidc.c
C
gpl-2.0
33,290
/* Copyright (c) 2009, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * */ #ifndef MT9V113_H #define MT9V113_H #include <linux/types.h> #include <mach/camera.h> /* Enum Type for different ISO Mode supported */ enum mt9v113_iso_value { CAMERA_ISO_AUTO = 0, CAMERA_ISO_DEBLUR, CAMERA_ISO_100, CAMERA_ISO_200, CAMERA_ISO_400, CAMERA_ISO_MAX }; extern struct mt9v113_reg mt9v113_regs; enum mt9v113_width { BYTE_LEN, WORD_LEN, }; struct mt9v113_i2c_reg_conf { unsigned short waddr; unsigned short wdata; }; struct mt9v113_reg { struct mt9v113_i2c_reg_conf const *init_tbl; uint16_t inittbl_size; struct mt9v113_i2c_reg_conf const *init_tbl1; uint16_t inittbl1_size; struct mt9v113_i2c_reg_conf const *init_tbl2; uint16_t inittbl2_size; // Effect struct mt9v113_i2c_reg_conf const *effect_default_tbl; uint16_t effect_default_tbl_size; struct mt9v113_i2c_reg_conf const *effect_mono_tbl; uint16_t effect_mono_tbl_size; struct mt9v113_i2c_reg_conf const *effect_sepia_tbl; uint16_t effect_sepia_tbl_size; struct mt9v113_i2c_reg_conf const *effect_aqua_tbl; uint16_t effect_aqua_tbl_size; struct mt9v113_i2c_reg_conf const *effect_negative_tbl; uint16_t effect_negative_tbl_size; struct mt9v113_i2c_reg_conf const *effect_solarization_tbl; uint16_t effect_solarization_tbl_size; // White balance struct mt9v113_i2c_reg_conf const *wb_default_tbl; uint16_t wb_default_tbl_size; struct mt9v113_i2c_reg_conf const *wb_sunny_tbl; uint16_t wb_sunny_tbl_size; struct mt9v113_i2c_reg_conf const *wb_cloudy_tbl; uint16_t wb_cloudy_tbl_size; struct mt9v113_i2c_reg_conf const *wb_fluorescent_tbl; uint16_t wb_fluorescent_tbl_size; struct mt9v113_i2c_reg_conf const *wb_incandescent_tbl; uint16_t wb_incandescent_tbl_size; // ISO struct mt9v113_i2c_reg_conf const *iso_default_tbl; uint16_t iso_default_tbl_size; struct mt9v113_i2c_reg_conf const *iso_160_tbl; uint16_t iso_160_tbl_size; struct mt9v113_i2c_reg_conf const *iso_200_tbl; uint16_t iso_200_tbl_size; struct mt9v113_i2c_reg_conf const *iso_400_tbl; uint16_t iso_400_tbl_size; // FPS struct mt9v113_i2c_reg_conf const *fps_fixed_15_tbl; uint16_t fps_fixed_15_tbl_size; struct mt9v113_i2c_reg_conf const *fps_fixed_30_tbl; uint16_t fps_fixed_30_tbl_size; struct mt9v113_i2c_reg_conf const *fps_auto_1030_tbl; uint16_t fps_auto_1030_tbl_size; struct mt9v113_i2c_reg_conf const *fps_auto_730_tbl; uint16_t fps_auto_730_tbl_size; // Change-config struct mt9v113_i2c_reg_conf const *change_config_tbl; uint16_t change_config_tbl_size; }; #endif /* MT9V113_H */
thenameisnigel/android_kernel_lge_ls840
lge/com_device/camera/sensor_mt9v113.h
C
gpl-2.0
3,252
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Sequence</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../index.html" title="Chapter&#160;1.&#160;Fusion 2.2"> <link rel="up" href="../index.html" title="Chapter&#160;1.&#160;Fusion 2.2"> <link rel="prev" href="iterator/metafunctions/deref_data.html" title="deref_data"> <link rel="next" href="sequence/concepts.html" title="Concepts"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="iterator/metafunctions/deref_data.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="sequence/concepts.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h2 class="title" style="clear: both"> <a name="fusion.sequence"></a><a class="link" href="sequence.html" title="Sequence">Sequence</a> </h2></div></div></div> <div class="toc"><dl class="toc"> <dt><span class="section"><a href="sequence/concepts.html">Concepts</a></span></dt> <dd><dl> <dt><span class="section"><a href="sequence/concepts/forward_sequence.html">Forward Sequence</a></span></dt> <dt><span class="section"><a href="sequence/concepts/bidirectional_sequence.html">Bidirectional Sequence</a></span></dt> <dt><span class="section"><a href="sequence/concepts/random_access_sequence.html">Random Access Sequence</a></span></dt> <dt><span class="section"><a href="sequence/concepts/associative_sequence.html">Associative Sequence</a></span></dt> <dt><span class="section"><a href="sequence/concepts/unbounded_sequence.html">Unbounded Sequence</a></span></dt> </dl></dd> <dt><span class="section"><a href="sequence/intrinsic.html">Intrinsic</a></span></dt> <dd><dl> <dt><span class="section"><a href="sequence/intrinsic/functions.html">Functions</a></span></dt> <dt><span class="section"><a href="sequence/intrinsic/metafunctions.html">Metafunctions</a></span></dt> </dl></dd> <dt><span class="section"><a href="sequence/operator.html">Operator</a></span></dt> <dd><dl> <dt><span class="section"><a href="sequence/operator/i_o.html">I/O</a></span></dt> <dt><span class="section"><a href="sequence/operator/comparison.html">Comparison</a></span></dt> <dt><span class="section"><a href="sequence/operator/hashing.html">Hashing</a></span></dt> </dl></dd> </dl></div> <p> Like <a href="http://www.boost.org/libs/mpl/index.html" target="_top">MPL</a>, the Sequence is a fundamental concept in Fusion. A Sequence may or may not actually store or contain data. <a class="link" href="container.html" title="Container">Container</a> are sequences that hold data. <a class="link" href="view.html" title="View">Views</a>, on the other hand, are sequences that do not store any data. Instead, they are proxies that impart an alternative presentation over another sequence. All models of Sequence have an associated <a class="link" href="iterator.html" title="Iterator">Iterator</a> type that can be used to iterate through the Sequence's elements. </p> <h4> <a name="fusion.sequence.h0"></a> <span class="phrase"><a name="fusion.sequence.header"></a></span><a class="link" href="sequence.html#fusion.sequence.header">Header</a> </h4> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">sequence</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">include</span><span class="special">/</span><span class="identifier">sequence</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2001-2006, 2011, 2012 Joel de Guzman, Dan Marsden, Tobias Schwinger<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="iterator/metafunctions/deref_data.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../index.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="sequence/concepts.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
FFMG/myoddweb.piger
myodd/boost/libs/fusion/doc/html/fusion/sequence.html
HTML
gpl-2.0
6,100
/*------------------------------------------------------------------------- SDCCsystem - SDCC system & pipe functions Written By - Sandeep Dutta . sandeep.dutta@usa.net (1999) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! -------------------------------------------------------------------------*/ #ifndef SDCCSYSTEM_H #define SDCCSYSTEM_H #include <stdio.h> #include "SDCCset.h" extern set *binPathSet; /* set of binary paths */ int sdcc_system (const char *cmd); FILE *sdcc_popen (const char *cmd); int sdcc_pclose (FILE *fp); #endif
darconeous/sdcc
src/SDCCsystem.h
C
gpl-2.0
1,405
<?php /** * AMF0 Parser * * Based (pretty far) on the AMFPHP serializer. I actually started using the AMFPHP serializer and * mostly rewrote it. * * @author Tommy Lacroix <tlacroix@quantiksolutions.com> * @copyright Copyright (c) 2006-2008 Tommy Lacroix * @license LGPL */ class AMF0Parser { /** * Endianess, 0x00 for big, 0x01 for little * * @var int */ var $endian; /** * AMF0 Data * * @var string (binary) */ var $data; /** * Index in data * * @var int */ var $index; /** * Data length * * @var int */ var $dataLength; /** * Constructor * * @return AMF0Parser */ function AMF0Parser() { /** * Proceed to endianess detection. This will be needed by * double decoding because unpack doesn't allow the selection * of endianess when decoding doubles. */ // Pack 1 in machine order $tmp = @pack("L", 1); // Unpack it in big endian order $tmp2 = @unpack("None",$tmp); // Check if it's still one if ($tmp2['one'] == 1) $this->endian = 0x00; // Yes, big endian else $this->endian = 0x01; // No, little endian } /** * Initialize data * * @param string AMF0 Data */ function initialize($str) { $this->data = $str; $this->dataLength = strlen($str); $this->index = 0; } /** * Read all packets * * @param string AMF0 data (optional, uses the initialized one if not given) * @return array */ function readAllPackets($str = false) { // Initialize if needed if ($str !== false) $this->initialize($str); // Parse each packet $ret = array(); while ($this->index < $this->dataLength) $ret[] = $this->readPacket(); // Return it return $ret; } /** * Read a packet at current index * * @return mixed */ function readPacket() { // Get data code $dataType = ord($this->data[$this->index++]); // Interpret switch($dataType) { case 0x00: // Number 0x00 return $this->readNumber(); case 0x01: // Boolean 0x01 return $this->readBoolean(); case 0x02: // String 0x02 return $this->readString(); break; case 0x03: // Object 0x03 return $this->readObject(); break; case 0x08 : // Mixed array 0x08 return $this->readMixedArray(); break; case 0x0a: // Array 0x0a return $this->readArray(); break; case 0x0c: // 0x0c return $this->readLongString(); break; case 0x0f: // 0x0f return $this->readLongString(); break; case 0x10: // 0x10 Typed Object return $this->readTypedObject(); break; default: break; } } /** * Read a string at current index * * @return string */ function readString() { // Get length $data = substr($this->data,$this->index,2); if( strlen( $data ) == 2 ){ $len = @unpack('nlen', $data); $this->index+=2; // Get string $val = substr($this->data, $this->index, $len['len']); $this->index += $len['len']; } // Return it return $val; } /** * Read a long string at current index * * @return string */ function readLongString() { // Get length $data = substr($this->data,$this->index,2); if( strlen( $data ) == 4 ){ $len = @unpack('Nlen', $data); $this->index+=4; // Get string $val = substr($this->data, $this->index, $len['len']); $this->index += $len['len']; } // Return it return $val; } /** * Read a number (double) at current index * * @return double */ function readNumber() { // Get the packet, big endian (8 bytes long) $packed = substr($this->data, $this->index, 8); if( strlen( $packed ) == 8 ){ $this->index += 8; // Reverse it if we're little endian if ($this->endian == 0x01) $packed = strrev($packed); // Unpack it $tmp = @unpack("dnumber", $packed); // Return it return $tmp['number']; } } /** * Read a boolean at current index * * @return boolean */ function readBoolean() { return ord($this->data[$this->index++]) == 1; } /** * Read an object at current index * * @return stdClass */ function readObject() { // Create return object we will add data to $ret = new stdClass(); while( in_array( $key = $this->readString(), array( 'width', 'height', 'duration' ) ) ) { $dataType = ord( $this->data[$this->index] ); if( !$key || $dataType == 0x09 ){ // Consume byte $this->index += 1; break; } // Get data $val = $this->readPacket(); // Store it $ret->$key = $val; } return $ret; } /** * Read a typed object at current index * * @return stdClass */ function readTypedObject() { $className = $this->readString(); $object = $this->readObject(); $object->__className = $className; return $object; } /** * Read a mixed array at current position * * Note: A mixed array is basically an object, but with a long integer describing its highest index at first. * * @return array */ function readMixedArray() { // Skip the index $this->index += 4; // Parse the object, but return it as an array return get_object_vars($this->readObject()); } /** * Get an indexed array ([0,1,2,3,4,...]) * * @return array */ function readArray() { // Get item count $data = substr($this->data,$this->index,4); if( strlen( $data ) == 4 ){ $len = @unpack('Nlen', $data); $this->index+=4; // Get each packet $ret = array(); for($i=0;$i<$len['len'];$i++) $ret[] = $this->readPacket(); } // Return the array return $ret; } } ?>
thinkcollege/tc-code
plugins/editors/jce/tiny_mce/plugins/mediamanager/classes/flvinfo/amfo.php
PHP
gpl-2.0
6,978
start windiff *.exp *.txt
MavenRain/reko
src/tools/wd.cmd
Batchfile
gpl-2.0
26
SELECT a.Id FROM Weather a, Weather b WHERE TO_DAYS(a.Date) = TO_DAYS(b.Date) + 1 AND a.Temperature > b.Temperature
daniyuu/leetcode
solutions/197.Rising_Temperature/AC_TO_DAYS.sql
SQL
gpl-2.0
116
/**************************************************************************** * * Copyright (C) 2005 - 2012 by Vivante Corp. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the license, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ #ifndef __gc_hal_enum_h_ #define __gc_hal_enum_h_ #ifdef __cplusplus extern "C" { #endif /* Chip models. */ typedef enum _gceCHIPMODEL { gcv300 = 0x0300, gcv320 = 0x0320, gcv350 = 0x0350, gcv355 = 0x0355, gcv400 = 0x0400, gcv410 = 0x0410, gcv450 = 0x0450, gcv500 = 0x0500, gcv530 = 0x0530, gcv600 = 0x0600, gcv700 = 0x0700, gcv800 = 0x0800, gcv860 = 0x0860, gcv880 = 0x0880, gcv1000 = 0x1000, gcv2000 = 0x2000, gcv2100 = 0x2100, gcv4000 = 0x4000, } gceCHIPMODEL; /* Chip features. */ typedef enum _gceFEATURE { gcvFEATURE_PIPE_2D = 0, gcvFEATURE_PIPE_3D, gcvFEATURE_PIPE_VG, gcvFEATURE_DC, gcvFEATURE_HIGH_DYNAMIC_RANGE, gcvFEATURE_MODULE_CG, gcvFEATURE_MIN_AREA, gcvFEATURE_BUFFER_INTERLEAVING, gcvFEATURE_BYTE_WRITE_2D, gcvFEATURE_ENDIANNESS_CONFIG, gcvFEATURE_DUAL_RETURN_BUS, gcvFEATURE_DEBUG_MODE, gcvFEATURE_YUY2_RENDER_TARGET, gcvFEATURE_FRAGMENT_PROCESSOR, gcvFEATURE_2DPE20, gcvFEATURE_FAST_CLEAR, gcvFEATURE_YUV420_TILER, gcvFEATURE_YUY2_AVERAGING, gcvFEATURE_FLIP_Y, gcvFEATURE_EARLY_Z, gcvFEATURE_Z_COMPRESSION, gcvFEATURE_MSAA, gcvFEATURE_SPECIAL_ANTI_ALIASING, gcvFEATURE_SPECIAL_MSAA_LOD, gcvFEATURE_422_TEXTURE_COMPRESSION, gcvFEATURE_DXT_TEXTURE_COMPRESSION, gcvFEATURE_ETC1_TEXTURE_COMPRESSION, gcvFEATURE_CORRECT_TEXTURE_CONVERTER, gcvFEATURE_TEXTURE_8K, gcvFEATURE_SCALER, gcvFEATURE_YUV420_SCALER, gcvFEATURE_SHADER_HAS_W, gcvFEATURE_SHADER_HAS_SIGN, gcvFEATURE_SHADER_HAS_FLOOR, gcvFEATURE_SHADER_HAS_CEIL, gcvFEATURE_SHADER_HAS_SQRT, gcvFEATURE_SHADER_HAS_TRIG, gcvFEATURE_VAA, gcvFEATURE_HZ, gcvFEATURE_CORRECT_STENCIL, gcvFEATURE_VG20, gcvFEATURE_VG_FILTER, gcvFEATURE_VG21, gcvFEATURE_VG_DOUBLE_BUFFER, gcvFEATURE_MC20, gcvFEATURE_SUPER_TILED, gcvFEATURE_2D_FILTERBLIT_PLUS_ALPHABLEND, gcvFEATURE_2D_DITHER, gcvFEATURE_2D_A8_TARGET, gcvFEATURE_2D_FILTERBLIT_FULLROTATION, gcvFEATURE_2D_BITBLIT_FULLROTATION, gcvFEATURE_WIDE_LINE, gcvFEATURE_FC_FLUSH_STALL, gcvFEATURE_FULL_DIRECTFB, gcvFEATURE_HALF_FLOAT_PIPE, gcvFEATURE_LINE_LOOP, gcvFEATURE_2D_YUV_BLIT, gcvFEATURE_2D_TILING, gcvFEATURE_NON_POWER_OF_TWO, gcvFEATURE_3D_TEXTURE, gcvFEATURE_TEXTURE_ARRAY, gcvFEATURE_TILE_FILLER, gcvFEATURE_LOGIC_OP, gcvFEATURE_COMPOSITION, gcvFEATURE_MIXED_STREAMS, gcvFEATURE_2D_MULTI_SOURCE_BLT, gcvFEATURE_END_EVENT, gcvFEATURE_VERTEX_10_10_10_2, gcvFEATURE_TEXTURE_10_10_10_2, gcvFEATURE_TEXTURE_ANISOTROPIC_FILTERING, gcvFEATURE_TEXTURE_FLOAT_HALF_FLOAT, gcvFEATURE_2D_ROTATION_STALL_FIX, gcvFEATURE_2D_MULTI_SOURCE_BLT_EX, gcvFEATURE_BUG_FIXES10, gcvFEATURE_2D_MINOR_TILING, /* Supertiled compressed textures are supported. */ gcvFEATURE_TEX_COMPRRESSION_SUPERTILED, gcvFEATURE_FAST_MSAA, gcvFEATURE_BUG_FIXED_INDEXED_TRIANGLE_STRIP, gcvFEATURE_TEXTURE_TILED_READ, gcvFEATURE_DEPTH_BIAS_FIX } gceFEATURE; /* Chip Power Status. */ typedef enum _gceCHIPPOWERSTATE { gcvPOWER_ON = 0, gcvPOWER_OFF, gcvPOWER_IDLE, gcvPOWER_SUSPEND, gcvPOWER_SUSPEND_ATPOWERON, gcvPOWER_OFF_ATPOWERON, gcvPOWER_IDLE_BROADCAST, gcvPOWER_SUSPEND_BROADCAST, gcvPOWER_OFF_BROADCAST, gcvPOWER_OFF_RECOVERY, #if gcdPOWEROFF_TIMEOUT gcvPOWER_OFF_TIMEOUT, #endif gcvPOWER_ON_AUTO } gceCHIPPOWERSTATE; /* CPU cache operations */ typedef enum _gceCACHEOPERATION { gcvCACHE_CLEAN = 0x01, gcvCACHE_INVALIDATE = 0x02, gcvCACHE_FLUSH = gcvCACHE_CLEAN | gcvCACHE_INVALIDATE } gceCACHEOPERATION; typedef enum _gceVIDMEM_NODE_SHARED_INFO_TYPE { gcvVIDMEM_INFO_GENERIC, gcvVIDMEM_INFO_DIRTY_RECTANGLE } gceVIDMEM_NODE_SHARED_INFO_TYPE; /* Surface types. */ typedef enum _gceSURF_TYPE { gcvSURF_TYPE_UNKNOWN = 0, gcvSURF_INDEX, gcvSURF_VERTEX, gcvSURF_TEXTURE, gcvSURF_RENDER_TARGET, gcvSURF_DEPTH, gcvSURF_BITMAP, gcvSURF_TILE_STATUS, gcvSURF_IMAGE, gcvSURF_MASK, gcvSURF_SCISSOR, gcvSURF_HIERARCHICAL_DEPTH, gcvSURF_NUM_TYPES, /* Make sure this is the last one! */ /* Combinations. */ gcvSURF_NO_TILE_STATUS = 0x100, gcvSURF_NO_VIDMEM = 0x200, /* Used to allocate surfaces with no underlying vidmem node. In Android, vidmem node is allocated by another process. */ gcvSURF_CACHEABLE = 0x400, /* Used to allocate a cacheable surface */ #if gcdANDROID_UNALIGNED_LINEAR_COMPOSITION_ADJUST gcvSURF_FLIP = 0x800, /* The Resolve Target the will been flip resolve from RT */ #endif gcvSURF_RENDER_TARGET_NO_TILE_STATUS = gcvSURF_RENDER_TARGET | gcvSURF_NO_TILE_STATUS, gcvSURF_DEPTH_NO_TILE_STATUS = gcvSURF_DEPTH | gcvSURF_NO_TILE_STATUS, /* Supported surface types with no vidmem node. */ gcvSURF_BITMAP_NO_VIDMEM = gcvSURF_BITMAP | gcvSURF_NO_VIDMEM, gcvSURF_TEXTURE_NO_VIDMEM = gcvSURF_TEXTURE | gcvSURF_NO_VIDMEM, /* Cacheable surface types with no vidmem node. */ gcvSURF_CACHEABLE_BITMAP_NO_VIDMEM = gcvSURF_BITMAP_NO_VIDMEM | gcvSURF_CACHEABLE, gcvSURF_CACHEABLE_BITMAP = gcvSURF_BITMAP | gcvSURF_CACHEABLE, #if gcdANDROID_UNALIGNED_LINEAR_COMPOSITION_ADJUST gcvSURF_FLIP_BITMAP = gcvSURF_BITMAP | gcvSURF_FLIP, #endif } gceSURF_TYPE; typedef enum _gceSURF_USAGE { gcvSURF_USAGE_UNKNOWN, gcvSURF_USAGE_RESOLVE_AFTER_CPU, gcvSURF_USAGE_RESOLVE_AFTER_3D } gceSURF_USAGE; typedef enum _gceSURF_COLOR_TYPE { gcvSURF_COLOR_UNKNOWN = 0, gcvSURF_COLOR_LINEAR = 0x01, gcvSURF_COLOR_ALPHA_PRE = 0x02, } gceSURF_COLOR_TYPE; /* Rotation. */ typedef enum _gceSURF_ROTATION { gcvSURF_0_DEGREE = 0, gcvSURF_90_DEGREE, gcvSURF_180_DEGREE, gcvSURF_270_DEGREE, gcvSURF_FLIP_X, gcvSURF_FLIP_Y, } gceSURF_ROTATION; /* Surface formats. */ typedef enum _gceSURF_FORMAT { /* Unknown format. */ gcvSURF_UNKNOWN = 0, /* Palettized formats. */ gcvSURF_INDEX1 = 100, gcvSURF_INDEX4, gcvSURF_INDEX8, /* RGB formats. */ gcvSURF_A2R2G2B2 = 200, gcvSURF_R3G3B2, gcvSURF_A8R3G3B2, gcvSURF_X4R4G4B4, gcvSURF_A4R4G4B4, gcvSURF_R4G4B4A4, gcvSURF_X1R5G5B5, gcvSURF_A1R5G5B5, gcvSURF_R5G5B5A1, gcvSURF_R5G6B5, gcvSURF_R8G8B8, gcvSURF_X8R8G8B8, gcvSURF_A8R8G8B8, gcvSURF_R8G8B8A8, gcvSURF_G8R8G8B8, gcvSURF_R8G8B8G8, gcvSURF_X2R10G10B10, gcvSURF_A2R10G10B10, gcvSURF_X12R12G12B12, gcvSURF_A12R12G12B12, gcvSURF_X16R16G16B16, gcvSURF_A16R16G16B16, gcvSURF_A32R32G32B32, gcvSURF_R8G8B8X8, gcvSURF_R5G5B5X1, gcvSURF_R4G4B4X4, /* BGR formats. */ gcvSURF_A4B4G4R4 = 300, gcvSURF_A1B5G5R5, gcvSURF_B5G6R5, gcvSURF_B8G8R8, gcvSURF_B16G16R16, gcvSURF_X8B8G8R8, gcvSURF_A8B8G8R8, gcvSURF_A2B10G10R10, gcvSURF_X16B16G16R16, gcvSURF_A16B16G16R16, gcvSURF_B32G32R32, gcvSURF_X32B32G32R32, gcvSURF_A32B32G32R32, gcvSURF_B4G4R4A4, gcvSURF_B5G5R5A1, gcvSURF_B8G8R8X8, gcvSURF_B8G8R8A8, gcvSURF_X4B4G4R4, gcvSURF_X1B5G5R5, gcvSURF_B4G4R4X4, gcvSURF_B5G5R5X1, gcvSURF_X2B10G10R10, /* Compressed formats. */ gcvSURF_DXT1 = 400, gcvSURF_DXT2, gcvSURF_DXT3, gcvSURF_DXT4, gcvSURF_DXT5, gcvSURF_CXV8U8, gcvSURF_ETC1, /* YUV formats. */ gcvSURF_YUY2 = 500, gcvSURF_UYVY, gcvSURF_YV12, gcvSURF_I420, gcvSURF_NV12, gcvSURF_NV21, gcvSURF_NV16, gcvSURF_NV61, gcvSURF_YVYU, gcvSURF_VYUY, /* Depth formats. */ gcvSURF_D16 = 600, gcvSURF_D24S8, gcvSURF_D32, gcvSURF_D24X8, /* Alpha formats. */ gcvSURF_A4 = 700, gcvSURF_A8, gcvSURF_A12, gcvSURF_A16, gcvSURF_A32, gcvSURF_A1, /* Luminance formats. */ gcvSURF_L4 = 800, gcvSURF_L8, gcvSURF_L12, gcvSURF_L16, gcvSURF_L32, gcvSURF_L1, /* Alpha/Luminance formats. */ gcvSURF_A4L4 = 900, gcvSURF_A2L6, gcvSURF_A8L8, gcvSURF_A4L12, gcvSURF_A12L12, gcvSURF_A16L16, /* Bump formats. */ gcvSURF_L6V5U5 = 1000, gcvSURF_V8U8, gcvSURF_X8L8V8U8, gcvSURF_Q8W8V8U8, gcvSURF_A2W10V10U10, gcvSURF_V16U16, gcvSURF_Q16W16V16U16, /* R/RG/RA formats. */ gcvSURF_R8 = 1100, gcvSURF_X8R8, gcvSURF_G8R8, gcvSURF_X8G8R8, gcvSURF_A8R8, gcvSURF_R16, gcvSURF_X16R16, gcvSURF_G16R16, gcvSURF_X16G16R16, gcvSURF_A16R16, gcvSURF_R32, gcvSURF_X32R32, gcvSURF_G32R32, gcvSURF_X32G32R32, gcvSURF_A32R32, gcvSURF_RG16, /* Floating point formats. */ gcvSURF_R16F = 1200, gcvSURF_X16R16F, gcvSURF_G16R16F, gcvSURF_X16G16R16F, gcvSURF_B16G16R16F, gcvSURF_X16B16G16R16F, gcvSURF_A16B16G16R16F, gcvSURF_R32F, gcvSURF_X32R32F, gcvSURF_G32R32F, gcvSURF_X32G32R32F, gcvSURF_B32G32R32F, gcvSURF_X32B32G32R32F, gcvSURF_A32B32G32R32F, gcvSURF_A16F, gcvSURF_L16F, gcvSURF_A16L16F, gcvSURF_A16R16F, gcvSURF_A32F, gcvSURF_L32F, gcvSURF_A32L32F, gcvSURF_A32R32F, } gceSURF_FORMAT; /* Pixel swizzle modes. */ typedef enum _gceSURF_SWIZZLE { gcvSURF_NOSWIZZLE = 0, gcvSURF_ARGB, gcvSURF_ABGR, gcvSURF_RGBA, gcvSURF_BGRA } gceSURF_SWIZZLE; /* Transparency modes. */ typedef enum _gceSURF_TRANSPARENCY { /* Valid only for PE 1.0 */ gcvSURF_OPAQUE = 0, gcvSURF_SOURCE_MATCH, gcvSURF_SOURCE_MASK, gcvSURF_PATTERN_MASK, } gceSURF_TRANSPARENCY; /* Surface Alignment. */ typedef enum _gceSURF_ALIGNMENT { gcvSURF_FOUR = 0, gcvSURF_SIXTEEN, gcvSURF_SUPER_TILED, gcvSURF_SPLIT_TILED, gcvSURF_SPLIT_SUPER_TILED, } gceSURF_ALIGNMENT; /* Transparency modes. */ typedef enum _gce2D_TRANSPARENCY { /* Valid only for PE 2.0 */ gcv2D_OPAQUE = 0, gcv2D_KEYED, gcv2D_MASKED } gce2D_TRANSPARENCY; /* Mono packing modes. */ typedef enum _gceSURF_MONOPACK { gcvSURF_PACKED8 = 0, gcvSURF_PACKED16, gcvSURF_PACKED32, gcvSURF_UNPACKED, } gceSURF_MONOPACK; /* Blending modes. */ typedef enum _gceSURF_BLEND_MODE { /* Porter-Duff blending modes. */ /* Fsrc Fdst */ gcvBLEND_CLEAR = 0, /* 0 0 */ gcvBLEND_SRC, /* 1 0 */ gcvBLEND_DST, /* 0 1 */ gcvBLEND_SRC_OVER_DST, /* 1 1 - Asrc */ gcvBLEND_DST_OVER_SRC, /* 1 - Adst 1 */ gcvBLEND_SRC_IN_DST, /* Adst 0 */ gcvBLEND_DST_IN_SRC, /* 0 Asrc */ gcvBLEND_SRC_OUT_DST, /* 1 - Adst 0 */ gcvBLEND_DST_OUT_SRC, /* 0 1 - Asrc */ gcvBLEND_SRC_ATOP_DST, /* Adst 1 - Asrc */ gcvBLEND_DST_ATOP_SRC, /* 1 - Adst Asrc */ gcvBLEND_SRC_XOR_DST, /* 1 - Adst 1 - Asrc */ /* Special blending modes. */ gcvBLEND_SET, /* DST = 1 */ gcvBLEND_SUB /* DST = DST * (1 - SRC) */ } gceSURF_BLEND_MODE; /* Per-pixel alpha modes. */ typedef enum _gceSURF_PIXEL_ALPHA_MODE { gcvSURF_PIXEL_ALPHA_STRAIGHT = 0, gcvSURF_PIXEL_ALPHA_INVERSED } gceSURF_PIXEL_ALPHA_MODE; /* Global alpha modes. */ typedef enum _gceSURF_GLOBAL_ALPHA_MODE { gcvSURF_GLOBAL_ALPHA_OFF = 0, gcvSURF_GLOBAL_ALPHA_ON, gcvSURF_GLOBAL_ALPHA_SCALE } gceSURF_GLOBAL_ALPHA_MODE; /* Color component modes for alpha blending. */ typedef enum _gceSURF_PIXEL_COLOR_MODE { gcvSURF_COLOR_STRAIGHT = 0, gcvSURF_COLOR_MULTIPLY } gceSURF_PIXEL_COLOR_MODE; /* Color component modes for alpha blending. */ typedef enum _gce2D_PIXEL_COLOR_MULTIPLY_MODE { gcv2D_COLOR_MULTIPLY_DISABLE = 0, gcv2D_COLOR_MULTIPLY_ENABLE } gce2D_PIXEL_COLOR_MULTIPLY_MODE; /* Color component modes for alpha blending. */ typedef enum _gce2D_GLOBAL_COLOR_MULTIPLY_MODE { gcv2D_GLOBAL_COLOR_MULTIPLY_DISABLE = 0, gcv2D_GLOBAL_COLOR_MULTIPLY_ALPHA, gcv2D_GLOBAL_COLOR_MULTIPLY_COLOR } gce2D_GLOBAL_COLOR_MULTIPLY_MODE; /* Alpha blending factor modes. */ typedef enum _gceSURF_BLEND_FACTOR_MODE { gcvSURF_BLEND_ZERO = 0, gcvSURF_BLEND_ONE, gcvSURF_BLEND_STRAIGHT, gcvSURF_BLEND_INVERSED, gcvSURF_BLEND_COLOR, gcvSURF_BLEND_COLOR_INVERSED, gcvSURF_BLEND_SRC_ALPHA_SATURATED, gcvSURF_BLEND_STRAIGHT_NO_CROSS, gcvSURF_BLEND_INVERSED_NO_CROSS, gcvSURF_BLEND_COLOR_NO_CROSS, gcvSURF_BLEND_COLOR_INVERSED_NO_CROSS, gcvSURF_BLEND_SRC_ALPHA_SATURATED_CROSS } gceSURF_BLEND_FACTOR_MODE; /* Alpha blending porter duff rules. */ typedef enum _gce2D_PORTER_DUFF_RULE { gcvPD_CLEAR = 0, gcvPD_SRC, gcvPD_SRC_OVER, gcvPD_DST_OVER, gcvPD_SRC_IN, gcvPD_DST_IN, gcvPD_SRC_OUT, gcvPD_DST_OUT, gcvPD_SRC_ATOP, gcvPD_DST_ATOP, gcvPD_ADD, gcvPD_XOR, gcvPD_DST } gce2D_PORTER_DUFF_RULE; /* Alpha blending factor modes. */ typedef enum _gce2D_YUV_COLOR_MODE { gcv2D_YUV_601= 0, gcv2D_YUV_709 } gce2D_YUV_COLOR_MODE; /* 2D Rotation and flipping. */ typedef enum _gce2D_ORIENTATION { gcv2D_0_DEGREE = 0, gcv2D_90_DEGREE, gcv2D_180_DEGREE, gcv2D_270_DEGREE, gcv2D_X_FLIP, gcv2D_Y_FLIP } gce2D_ORIENTATION; typedef enum _gce2D_COMMAND { gcv2D_CLEAR = 0, gcv2D_LINE, gcv2D_BLT, gcv2D_STRETCH, gcv2D_HOR_FILTER, gcv2D_VER_FILTER, gcv2D_MULTI_SOURCE_BLT, } gce2D_COMMAND; #ifndef VIVANTE_NO_3D /* Texture functions. */ typedef enum _gceTEXTURE_FUNCTION { gcvTEXTURE_DUMMY = 0, gcvTEXTURE_REPLACE = 0, gcvTEXTURE_MODULATE, gcvTEXTURE_ADD, gcvTEXTURE_ADD_SIGNED, gcvTEXTURE_INTERPOLATE, gcvTEXTURE_SUBTRACT, gcvTEXTURE_DOT3 } gceTEXTURE_FUNCTION; /* Texture sources. */ typedef enum _gceTEXTURE_SOURCE { gcvCOLOR_FROM_TEXTURE = 0, gcvCOLOR_FROM_CONSTANT_COLOR, gcvCOLOR_FROM_PRIMARY_COLOR, gcvCOLOR_FROM_PREVIOUS_COLOR } gceTEXTURE_SOURCE; /* Texture source channels. */ typedef enum _gceTEXTURE_CHANNEL { gcvFROM_COLOR = 0, gcvFROM_ONE_MINUS_COLOR, gcvFROM_ALPHA, gcvFROM_ONE_MINUS_ALPHA } gceTEXTURE_CHANNEL; #endif /* VIVANTE_NO_3D */ /* Filter types. */ typedef enum _gceFILTER_TYPE { gcvFILTER_SYNC = 0, gcvFILTER_BLUR, gcvFILTER_USER } gceFILTER_TYPE; /* Filter pass types. */ typedef enum _gceFILTER_PASS_TYPE { gcvFILTER_HOR_PASS = 0, gcvFILTER_VER_PASS } gceFILTER_PASS_TYPE; /* Endian hints. */ typedef enum _gceENDIAN_HINT { gcvENDIAN_NO_SWAP = 0, gcvENDIAN_SWAP_WORD, gcvENDIAN_SWAP_DWORD } gceENDIAN_HINT; /* Tiling modes. */ typedef enum _gceTILING { gcvLINEAR = 0, gcvTILED, gcvSUPERTILED, gcvMULTI_TILED, gcvMULTI_SUPERTILED, gcvMINORTILED, } gceTILING; /* 2D pattern type. */ typedef enum _gce2D_PATTERN { gcv2D_PATTERN_SOLID = 0, gcv2D_PATTERN_MONO, gcv2D_PATTERN_COLOR, gcv2D_PATTERN_INVALID } gce2D_PATTERN; /* 2D source type. */ typedef enum _gce2D_SOURCE { gcv2D_SOURCE_MASKED = 0, gcv2D_SOURCE_MONO, gcv2D_SOURCE_COLOR, gcv2D_SOURCE_INVALID } gce2D_SOURCE; /* Pipes. */ typedef enum _gcePIPE_SELECT { gcvPIPE_INVALID = ~0, gcvPIPE_3D = 0, gcvPIPE_2D } gcePIPE_SELECT; /* Hardware type. */ typedef enum _gceHARDWARE_TYPE { gcvHARDWARE_INVALID = 0x00, gcvHARDWARE_3D = 0x01, gcvHARDWARE_2D = 0x02, gcvHARDWARE_VG = 0x04, gcvHARDWARE_3D2D = gcvHARDWARE_3D | gcvHARDWARE_2D } gceHARDWARE_TYPE; #define gcdCHIP_COUNT 3 typedef enum _gceMMU_MODE { gcvMMU_MODE_1K, gcvMMU_MODE_4K, } gceMMU_MODE; /* User signal command codes. */ typedef enum _gceUSER_SIGNAL_COMMAND_CODES { gcvUSER_SIGNAL_CREATE, gcvUSER_SIGNAL_DESTROY, gcvUSER_SIGNAL_SIGNAL, gcvUSER_SIGNAL_WAIT, gcvUSER_SIGNAL_MAP, gcvUSER_SIGNAL_UNMAP, } gceUSER_SIGNAL_COMMAND_CODES; /* Event locations. */ typedef enum _gceKERNEL_WHERE { gcvKERNEL_COMMAND, gcvKERNEL_VERTEX, gcvKERNEL_TRIANGLE, gcvKERNEL_TEXTURE, gcvKERNEL_PIXEL, } gceKERNEL_WHERE; #if gcdENABLE_VG /* Hardware blocks. */ typedef enum _gceBLOCK { gcvBLOCK_COMMAND, gcvBLOCK_TESSELLATOR, gcvBLOCK_TESSELLATOR2, gcvBLOCK_TESSELLATOR3, gcvBLOCK_RASTER, gcvBLOCK_VG, gcvBLOCK_VG2, gcvBLOCK_VG3, gcvBLOCK_PIXEL, /* Number of defined blocks. */ gcvBLOCK_COUNT } gceBLOCK; #endif /* gcdDUMP message type. */ typedef enum _gceDEBUG_MESSAGE_TYPE { gcvMESSAGE_TEXT, gcvMESSAGE_DUMP } gceDEBUG_MESSAGE_TYPE; /******************************************************************************\ ****************************** Object Declarations ***************************** \******************************************************************************/ typedef struct _gckCONTEXT * gckCONTEXT; typedef struct _gcoCMDBUF * gcoCMDBUF; typedef struct _gcsSTATE_DELTA * gcsSTATE_DELTA_PTR; typedef struct _gcsQUEUE * gcsQUEUE_PTR; typedef struct _gcoQUEUE * gcoQUEUE; typedef struct _gcsHAL_INTERFACE * gcsHAL_INTERFACE_PTR; typedef struct _gcs2D_PROFILE * gcs2D_PROFILE_PTR; #if gcdENABLE_VG typedef struct _gcoVGHARDWARE * gcoVGHARDWARE; typedef struct _gcoVGBUFFER * gcoVGBUFFER; typedef struct _gckVGHARDWARE * gckVGHARDWARE; typedef struct _gcsVGCONTEXT * gcsVGCONTEXT_PTR; typedef struct _gcsVGCONTEXT_MAP * gcsVGCONTEXT_MAP_PTR; typedef struct _gcsVGCMDQUEUE * gcsVGCMDQUEUE_PTR; typedef struct _gcsTASK_MASTER_TABLE * gcsTASK_MASTER_TABLE_PTR; typedef struct _gckVGKERNEL * gckVGKERNEL; typedef void * gctTHREAD; #endif #ifdef __cplusplus } #endif #endif /* __gc_hal_enum_h_ */
tsfs/Vybrid-Linux
drivers/mxc/gpu-viv/hal/kernel/inc/gc_hal_enum.h
C
gpl-2.0
19,403
/* * ADI-AIM ADC Interface Module * * Copyright 2012 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <linux/slab.h> #include <linux/kernel.h> #include <linux/poll.h> #include <linux/io.h> #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include "../iio.h" #include "../sysfs.h" #include "../buffer.h" #include "../ring_hw.h" #include "cf_ad9467.h" #include "cf_fft_core.h" static int aim_read_first_n_hw_rb(struct iio_buffer *r, size_t count, char __user *buf) { struct iio_hw_buffer *hw_ring = iio_to_hw_buf(r); struct iio_dev *indio_dev = hw_ring->private; struct aim_state *st = iio_priv(indio_dev); int ret; unsigned stat, dma_stat; mutex_lock(&st->lock); ret = wait_for_completion_interruptible_timeout(&st->dma_complete, 4 * HZ); stat = aim_read(st, AD9467_PCORE_ADC_STAT); dma_stat = aim_read(st, AD9467_PCORE_DMA_STAT); if (st->compl_stat < 0) { ret = st->compl_stat; goto error_ret; } else if (ret == 0) { ret = -ETIMEDOUT; dev_err(indio_dev->dev.parent, "timeout: DMA_STAT 0x%X, ADC_STAT 0x%X\n", dma_stat, stat); goto error_ret; } else if (ret < 0) { goto error_ret; } #if defined(CONFIG_CF_FFT) if (st->fftcount) { ret = fft_calculate(st->buf_phys, st->buf_phys + st->fftcount, st->fftcount / 4); } #endif if (copy_to_user(buf, st->buf_virt + st->fftcount, count)) ret = -EFAULT; if ((stat & AD9467_PCORE_ADC_STAT_OVR) || dma_stat) dev_warn(indio_dev->dev.parent, "STATUS: DMA_STAT 0x%X, ADC_STAT 0x%X\n", dma_stat, stat); error_ret: r->stufftoread = 0; mutex_unlock(&st->lock); return ret < 0 ? ret : count; } static int aim_ring_get_length(struct iio_buffer *r) { struct iio_hw_buffer *hw_ring = iio_to_hw_buf(r); struct iio_dev *indio_dev = hw_ring->private; struct aim_state *st = iio_priv(indio_dev); return st->ring_lenght; } static int aim_ring_set_length(struct iio_buffer *r, int lenght) { struct iio_hw_buffer *hw_ring = iio_to_hw_buf(r); struct aim_state *st = iio_priv(hw_ring->private); st->ring_lenght = lenght; return 0; } static int aim_ring_get_bytes_per_datum(struct iio_buffer *r) { struct iio_hw_buffer *hw_ring = iio_to_hw_buf(r); struct aim_state *st = iio_priv(hw_ring->private); return st->bytes_per_datum; } static IIO_BUFFER_ENABLE_ATTR; static IIO_BUFFER_LENGTH_ATTR; static struct attribute *aim_ring_attributes[] = { &dev_attr_length.attr, &dev_attr_enable.attr, NULL, }; static struct attribute_group aim_ring_attr = { .attrs = aim_ring_attributes, .name = "buffer", }; static struct iio_buffer *aim_rb_allocate(struct iio_dev *indio_dev) { struct iio_buffer *buf; struct iio_hw_buffer *ring; ring = kzalloc(sizeof *ring, GFP_KERNEL); if (!ring) return NULL; ring->private = indio_dev; buf = &ring->buf; buf->attrs = &aim_ring_attr; iio_buffer_init(buf); return buf; } static inline void aim_rb_free(struct iio_buffer *r) { kfree(iio_to_hw_buf(r)); } static const struct iio_buffer_access_funcs aim_ring_access_funcs = { .read_first_n = &aim_read_first_n_hw_rb, .get_length = &aim_ring_get_length, .set_length = &aim_ring_set_length, .get_bytes_per_datum = &aim_ring_get_bytes_per_datum, }; static int __aim_hw_ring_state_set(struct iio_dev *indio_dev, bool state) { struct aim_state *st = iio_priv(indio_dev); struct dma_async_tx_descriptor *desc; dma_cookie_t cookie; int ret = 0; if (!state) { if (!completion_done(&st->dma_complete)) { st->compl_stat = -EPERM; dmaengine_terminate_all(st->rx_chan); complete(&st->dma_complete); } dma_free_coherent(indio_dev->dev.parent, PAGE_ALIGN(st->rcount + st->fftcount), st->buf_virt, st->buf_phys); return 0; } st->compl_stat = 0; if (st->ring_lenght == 0) { ret = -EINVAL; goto error_ret; } if (st->ring_lenght % 8) st->rcount = (st->ring_lenght + 8) & 0xFFFFFFF8; else st->rcount = st->ring_lenght; #if defined(CONFIG_CF_FFT) st->fftcount = st->rcount; #else st->fftcount = 0; #endif st->buf_virt = dma_alloc_coherent(indio_dev->dev.parent, PAGE_ALIGN(st->rcount + st->fftcount), &st->buf_phys, GFP_KERNEL); if (st->buf_virt == NULL) { ret = -ENOMEM; goto error_ret; } desc = dmaengine_prep_slave_single(st->rx_chan, st->buf_phys, st->rcount, DMA_FROM_DEVICE, DMA_PREP_INTERRUPT); if (!desc) { dev_err(indio_dev->dev.parent, "Failed to allocate a dma descriptor\n"); ret = -ENOMEM; goto error_free; } desc->callback = (dma_async_tx_callback) complete; desc->callback_param = &st->dma_complete; cookie = dmaengine_submit(desc); if (cookie < 0) { dev_err(indio_dev->dev.parent, "Failed to submit a dma transfer\n"); ret = cookie; goto error_free; } INIT_COMPLETION(st->dma_complete); dma_async_issue_pending(st->rx_chan); aim_write(st, AD9467_PCORE_DMA_CTRL, 0); aim_write(st, AD9467_PCORE_ADC_STAT, 0xFF); aim_write(st, AD9467_PCORE_DMA_STAT, 0xFF); aim_write(st, AD9467_PCORE_DMA_CTRL, AD9647_DMA_CAP_EN | AD9647_DMA_CNT((st->rcount / 8) - 1)); return 0; error_free: dma_free_coherent(indio_dev->dev.parent, PAGE_ALIGN(st->rcount), st->buf_virt, st->buf_phys); error_ret: return ret; } static int aim_hw_ring_preenable(struct iio_dev *indio_dev) { return __aim_hw_ring_state_set(indio_dev, 1); } static int aim_hw_ring_postdisable(struct iio_dev *indio_dev) { return __aim_hw_ring_state_set(indio_dev, 0); } static const struct iio_buffer_setup_ops aim_ring_setup_ops = { .preenable = &aim_hw_ring_preenable, .postdisable = &aim_hw_ring_postdisable, }; int aim_configure_ring(struct iio_dev *indio_dev) { indio_dev->buffer = aim_rb_allocate(indio_dev); if (indio_dev->buffer == NULL) return -ENOMEM; indio_dev->modes |= INDIO_BUFFER_HARDWARE; indio_dev->buffer->access = &aim_ring_access_funcs; indio_dev->setup_ops = &aim_ring_setup_ops; return 0; } void aim_unconfigure_ring(struct iio_dev *indio_dev) { aim_rb_free(indio_dev->buffer); }
xiaogaogao/linuxFromDigilent
drivers/staging/iio/adc/cf_ad9467_ring.c
C
gpl-2.0
5,954
/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CREATE_FK_IMPL_HPP #define CREATE_FK_IMPL_HPP #include "SignalData.hpp" #define JAM_FILE_ID 208 struct CreateFKImplReq { /** * Sender(s) / Reciver(s) */ friend class Dbdict; /** * For printing */ friend bool printCREATE_FK_IMPL_REQ(FILE*, const Uint32*, Uint32, Uint16); STATIC_CONST( SignalLength = 10 ); STATIC_CONST( PARENT_COLUMNS = 0); // section no STATIC_CONST( CHILD_COLUMNS = 1); // section no enum { RT_PARSE = 0x1, RT_PREPARE = 0x2, RT_ABORT = 0x3, RT_COMMIT = 0x4, RT_COMPLETE = 0x5 }; enum Bits { FK_PARENT_UI = 1, // Parent index is an unique index FK_PARENT_OI = 2, // Parent index is an ordered index FK_CHILD_UI = 4, // Child index is an unique index FK_CHILD_OI = 8, // Child index is an ordered index FK_UPDATE_RESTRICT = 16, // On update restrict FK_UPDATE_CASCADE = 32, // On update cascade FK_UPDATE_SET_NULL = 64, // On update set null FK_UPDATE_SET_DEFAULT = 128, // On update set default FK_DELETE_RESTRICT = 256, // On delete restrict FK_DELETE_CASCADE = 512, // On delete cascade FK_DELETE_SET_NULL = 1024,// On delete set null FK_DELETE_SET_DEFAULT = 2048,// On delete set default FK_UPDATE_MASK = (FK_UPDATE_RESTRICT | FK_UPDATE_CASCADE | FK_UPDATE_SET_NULL | FK_UPDATE_SET_DEFAULT), FK_DELETE_MASK = (FK_DELETE_RESTRICT | FK_DELETE_CASCADE | FK_DELETE_SET_NULL | FK_DELETE_SET_DEFAULT), FK_ACTION_MASK = (FK_UPDATE_MASK | FK_DELETE_MASK), FK_UPDATE_ACTION = (FK_UPDATE_CASCADE | FK_UPDATE_SET_NULL | FK_UPDATE_SET_DEFAULT), FK_DELETE_ACTION = (FK_DELETE_CASCADE | FK_DELETE_SET_NULL | FK_DELETE_SET_DEFAULT), FK_ON_ACTION = (FK_UPDATE_ACTION | FK_DELETE_ACTION), FK_END = 0 // marker }; Uint32 senderData; Uint32 senderRef; Uint32 requestType; Uint32 fkId; Uint32 fkVersion; Uint32 bits; Uint32 parentTableId; Uint32 parentIndexId; Uint32 childTableId; Uint32 childIndexId; }; struct CreateFKImplRef { /** * Sender(s) */ friend class Dbdict; /** * For printing */ friend bool printCREATE_FK_IMPL_REF(FILE*, const Uint32*, Uint32, Uint16); STATIC_CONST( SignalLength = 3 ); Uint32 senderData; Uint32 senderRef; Uint32 errorCode; enum ErrCode { ObjectAlreadyExist = 21030, NoMoreObjectRecords = 21031, InvalidFormat = 21032 }; }; struct CreateFKImplConf { /** * Sender(s) */ friend class Dbdict; /** * For printing */ friend bool printCREATE_FK_IMPL_CONF(FILE*, const Uint32*, Uint32, Uint16); STATIC_CONST( SignalLength = 4 ); Uint32 senderData; Uint32 senderRef; }; #undef JAM_FILE_ID #endif
greenlion/mysql-server
storage/ndb/include/kernel/signaldata/CreateFKImpl.hpp
C++
gpl-2.0
4,177
/* Mach-O support for BFD. Copyright (C) 1999-2017 Free Software Foundation, Inc. This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* Define generic entry points here so that we don't need to duplicate the defines in every target. But define once as this file may be included several times. */ #ifndef MACH_O_TARGET_COMMON_DEFINED #define MACH_O_TARGET_COMMON_DEFINED #define bfd_mach_o_bfd_free_cached_info _bfd_generic_bfd_free_cached_info #define bfd_mach_o_get_section_contents_in_window _bfd_generic_get_section_contents_in_window #define bfd_mach_o_bfd_print_private_bfd_data _bfd_generic_bfd_print_private_bfd_data #define bfd_mach_o_bfd_is_target_special_symbol ((bfd_boolean (*) (bfd *, asymbol *)) bfd_false) #define bfd_mach_o_bfd_is_local_label_name bfd_generic_is_local_label_name #define bfd_mach_o_get_lineno _bfd_nosymbols_get_lineno #define bfd_mach_o_find_inliner_info _bfd_nosymbols_find_inliner_info #define bfd_mach_o_get_symbol_version_string _bfd_nosymbols_get_symbol_version_string #define bfd_mach_o_bfd_make_debug_symbol _bfd_nosymbols_bfd_make_debug_symbol #define bfd_mach_o_read_minisymbols _bfd_generic_read_minisymbols #define bfd_mach_o_minisymbol_to_symbol _bfd_generic_minisymbol_to_symbol #define bfd_mach_o_bfd_get_relocated_section_contents bfd_generic_get_relocated_section_contents #define bfd_mach_o_bfd_relax_section bfd_generic_relax_section #define bfd_mach_o_bfd_link_hash_table_create _bfd_generic_link_hash_table_create #define bfd_mach_o_bfd_link_add_symbols _bfd_generic_link_add_symbols #define bfd_mach_o_bfd_link_just_syms _bfd_generic_link_just_syms #define bfd_mach_o_bfd_copy_link_hash_symbol_type \ _bfd_generic_copy_link_hash_symbol_type #define bfd_mach_o_bfd_final_link _bfd_generic_final_link #define bfd_mach_o_bfd_link_split_section _bfd_generic_link_split_section #define bfd_mach_o_bfd_link_check_relocs _bfd_generic_link_check_relocs #define bfd_mach_o_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data #define bfd_mach_o_bfd_set_private_flags bfd_mach_o_bfd_set_private_flags #define bfd_mach_o_get_section_contents _bfd_generic_get_section_contents #define bfd_mach_o_bfd_gc_sections bfd_generic_gc_sections #define bfd_mach_o_bfd_lookup_section_flags bfd_generic_lookup_section_flags #define bfd_mach_o_bfd_merge_sections bfd_generic_merge_sections #define bfd_mach_o_bfd_is_group_section bfd_generic_is_group_section #define bfd_mach_o_bfd_discard_group bfd_generic_discard_group #define bfd_mach_o_section_already_linked _bfd_generic_section_already_linked #define bfd_mach_o_bfd_define_common_symbol bfd_generic_define_common_symbol #define bfd_mach_o_bfd_copy_private_bfd_data _bfd_generic_bfd_copy_private_bfd_data #define bfd_mach_o_core_file_matches_executable_p generic_core_file_matches_executable_p #define bfd_mach_o_core_file_pid _bfd_nocore_core_file_pid #define bfd_mach_o_get_dynamic_symtab_upper_bound bfd_mach_o_get_symtab_upper_bound #define bfd_mach_o_canonicalize_dynamic_symtab bfd_mach_o_canonicalize_symtab /* For Mach-O special archives. */ #define bfd_mach_o_read_ar_hdr _bfd_noarchive_read_ar_hdr #define bfd_mach_o_write_ar_hdr _bfd_noarchive_write_ar_hdr #define bfd_mach_o_slurp_armap _bfd_noarchive_slurp_armap #define bfd_mach_o_slurp_extended_name_table _bfd_noarchive_slurp_extended_name_table #define bfd_mach_o_construct_extended_name_table _bfd_noarchive_construct_extended_name_table #define bfd_mach_o_truncate_arname _bfd_noarchive_truncate_arname #define bfd_mach_o_write_armap _bfd_noarchive_write_armap #define bfd_mach_o_get_elt_at_index _bfd_noarchive_get_elt_at_index #define bfd_mach_o_update_armap_timestamp _bfd_noarchive_update_armap_timestamp #define TARGET_NAME_BACKEND XCONCAT2(TARGET_NAME,_backend) #endif /* MACH_O_TARGET_COMMON_DEFINED */ #ifndef TARGET_NAME #error TARGET_NAME must be defined #endif /* TARGET_NAME */ #ifndef TARGET_STRING #error TARGET_STRING must be defined #endif /* TARGET_STRING */ #ifndef TARGET_ARCHITECTURE #error TARGET_ARCHITECTURE must be defined #endif /* TARGET_ARCHITECTURE */ #ifndef TARGET_BIG_ENDIAN #error TARGET_BIG_ENDIAN must be defined #endif /* TARGET_BIG_ENDIAN */ #ifndef TARGET_ARCHIVE #error TARGET_ARCHIVE must be defined #endif /* TARGET_ARCHIVE */ #ifndef TARGET_PAGESIZE #error TARGET_PAGESIZE must be defined #endif static const bfd_mach_o_backend_data TARGET_NAME_BACKEND = { TARGET_ARCHITECTURE, TARGET_PAGESIZE, bfd_mach_o_canonicalize_one_reloc, bfd_mach_o_swap_reloc_out, bfd_mach_o_print_thread, bfd_mach_o_tgt_seg_table, bfd_mach_o_section_type_valid_for_tgt }; const bfd_target TARGET_NAME = { TARGET_STRING, /* Name. */ bfd_target_mach_o_flavour, #if TARGET_BIG_ENDIAN BFD_ENDIAN_BIG, /* Target byte order. */ BFD_ENDIAN_BIG, /* Target headers byte order. */ #else BFD_ENDIAN_LITTLE, /* Target byte order. */ BFD_ENDIAN_LITTLE, /* Target headers byte order. */ #endif (HAS_RELOC | EXEC_P | /* Object flags. */ HAS_LINENO | HAS_DEBUG | HAS_SYMS | HAS_LOCALS | DYNAMIC | WP_TEXT | D_PAGED), (SEC_CODE | SEC_DATA | SEC_ROM | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_RELOC), /* Section flags. */ '_', /* symbol_leading_char. */ ' ', /* ar_pad_char. */ 16, /* ar_max_namelen. */ TARGET_PRIORITY, /* match priority. */ #if TARGET_BIG_ENDIAN bfd_getb64, bfd_getb_signed_64, bfd_putb64, bfd_getb32, bfd_getb_signed_32, bfd_putb32, bfd_getb16, bfd_getb_signed_16, bfd_putb16, /* Data. */ bfd_getb64, bfd_getb_signed_64, bfd_putb64, bfd_getb32, bfd_getb_signed_32, bfd_putb32, bfd_getb16, bfd_getb_signed_16, bfd_putb16, /* Hdrs. */ #else bfd_getl64, bfd_getl_signed_64, bfd_putl64, bfd_getl32, bfd_getl_signed_32, bfd_putl32, bfd_getl16, bfd_getl_signed_16, bfd_putl16, /* data */ bfd_getl64, bfd_getl_signed_64, bfd_putl64, bfd_getl32, bfd_getl_signed_32, bfd_putl32, bfd_getl16, bfd_getl_signed_16, bfd_putl16, /* hdrs */ #endif /* TARGET_BIG_ENDIAN */ { /* bfd_check_format. */ #if TARGET_ARCHIVE _bfd_dummy_target, _bfd_dummy_target, bfd_mach_o_archive_p, _bfd_dummy_target, #else _bfd_dummy_target, bfd_mach_o_object_p, bfd_generic_archive_p, bfd_mach_o_core_p #endif }, { /* bfd_set_format. */ bfd_false, bfd_mach_o_mkobject, _bfd_generic_mkarchive, bfd_mach_o_mkobject, }, { /* bfd_write_contents. */ bfd_false, bfd_mach_o_write_contents, _bfd_write_archive_contents, bfd_mach_o_write_contents, }, BFD_JUMP_TABLE_GENERIC (bfd_mach_o), BFD_JUMP_TABLE_COPY (bfd_mach_o), BFD_JUMP_TABLE_CORE (bfd_mach_o), #if TARGET_ARCHIVE BFD_JUMP_TABLE_ARCHIVE (bfd_mach_o), #else BFD_JUMP_TABLE_ARCHIVE (_bfd_archive_bsd44), #endif BFD_JUMP_TABLE_SYMBOLS (bfd_mach_o), BFD_JUMP_TABLE_RELOCS (bfd_mach_o), BFD_JUMP_TABLE_WRITE (bfd_mach_o), BFD_JUMP_TABLE_LINK (bfd_mach_o), BFD_JUMP_TABLE_DYNAMIC (bfd_mach_o), /* Alternative endian target. */ NULL, /* Back-end data. */ &TARGET_NAME_BACKEND };
totalspectrum/binutils-propeller
bfd/mach-o-target.c
C
gpl-2.0
8,300
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MANGOS_LOOTMGR_H #define MANGOS_LOOTMGR_H #include "ItemEnchantmentMgr.h" #include "ByteBuffer.h" #include "ObjectGuid.h" #include "Utilities/LinkedReference/RefManager.h" #include <map> #include <vector> #define MAX_NR_LOOT_ITEMS 16 // note: the client cannot show more than 16 items total #define MAX_NR_QUEST_ITEMS 32 // unrelated to the number of quest items shown, just for reserve enum PermissionTypes { ALL_PERMISSION = 0, GROUP_PERMISSION = 1, MASTER_PERMISSION = 2, OWNER_PERMISSION = 3, // for single player only loots NONE_PERMISSION = 4 }; enum LootType { LOOT_CORPSE = 1, LOOT_PICKPOCKETING = 2, LOOT_FISHING = 3, LOOT_DISENCHANTING = 4, // ignored always by client LOOT_SKINNING = 6, LOOT_PROSPECTING = 7, LOOT_MILLING = 8, LOOT_FISHINGHOLE = 20, // unsupported by client, sending LOOT_FISHING instead LOOT_FISHING_FAIL = 21, // unsupported by client, sending LOOT_FISHING instead LOOT_INSIGNIA = 22 // unsupported by client, sending LOOT_CORPSE instead }; enum LootSlotType { LOOT_SLOT_NORMAL = 0, // can be looted LOOT_SLOT_VIEW = 1, // can be only view (ignore any loot attempts) LOOT_SLOT_MASTER = 2, // can be looted only master (error message) LOOT_SLOT_REQS = 3, // can't be looted (error message about missing reqs) LOOT_SLOT_OWNER = 4, // ignore binding confirmation and etc, for single player looting MAX_LOOT_SLOT_TYPE // custom, use for mark skipped from show items }; class Player; class LootStore; struct LootStoreItem { uint32 itemid; // id of the item float chance; // always positive, chance to drop for both quest and non-quest items, chance to be used for refs int32 mincountOrRef; // mincount for drop items (positive) or minus referenced TemplateleId (negative) uint8 group :7; bool needs_quest :1; // quest drop (negative ChanceOrQuestChance in DB) uint8 maxcount :8; // max drop count for the item (mincountOrRef positive) or Ref multiplicator (mincountOrRef negative) uint16 conditionId :16; // additional loot condition Id // Constructor, converting ChanceOrQuestChance -> (chance, needs_quest) // displayid is filled in IsValid() which must be called after LootStoreItem(uint32 _itemid, float _chanceOrQuestChance, int8 _group, uint16 _conditionId, int32 _mincountOrRef, uint8 _maxcount) : itemid(_itemid), chance(fabs(_chanceOrQuestChance)), mincountOrRef(_mincountOrRef), group(_group), needs_quest(_chanceOrQuestChance < 0), maxcount(_maxcount), conditionId(_conditionId) {} bool Roll(bool rate) const; // Checks if the entry takes it's chance (at loot generation) bool IsValid(LootStore const& store, uint32 entry) const; // Checks correctness of values }; typedef std::set<uint32> AllowedLooterSet; struct LootItem { uint32 itemid; uint32 randomSuffix; int32 randomPropertyId; AllowedLooterSet allowedGUIDs; uint16 conditionId :16; // allow compiler pack structure uint8 count : 8; bool is_looted : 1; bool is_blocked : 1; bool freeforall : 1; // free for all bool is_underthreshold : 1; bool is_counted : 1; bool needs_quest : 1; // quest drop // Constructor, copies most fields from LootStoreItem, generates random count and random suffixes/properties // Should be called for non-reference LootStoreItem entries only (mincountOrRef > 0) explicit LootItem(LootStoreItem const& li); LootItem(uint32 itemid_, uint32 count_, uint32 randomSuffix_ = 0, int32 randomPropertyId_ = 0); // Basic checks for player/item compatibility - if false no chance to see the item in the loot bool AllowedForPlayer(Player const * player) const; LootSlotType GetSlotTypeForSharedLoot(PermissionTypes permission, Player* viewer, bool condition_ok = false) const; void AddAllowedLooter(Player const* player); AllowedLooterSet* GetAllowedLooters() { return &allowedGUIDs; } }; typedef std::vector<LootItem> LootItemList; struct QuestItem { uint8 index; // position in quest_items; bool is_looted; QuestItem() : index(0), is_looted(false) {} QuestItem(uint8 _index, bool _islooted = false) : index(_index), is_looted(_islooted) {} }; struct Loot; class LootTemplate; typedef std::vector<QuestItem> QuestItemList; typedef std::map<uint32, QuestItemList *> QuestItemMap; typedef std::vector<LootStoreItem> LootStoreItemList; typedef UNORDERED_MAP<uint32, LootTemplate*> LootTemplateMap; typedef std::set<uint32> LootIdSet; class LootStore { public: explicit LootStore(char const* name, char const* entryName, bool ratesAllowed) : m_name(name), m_entryName(entryName), m_ratesAllowed(ratesAllowed) {} virtual ~LootStore() { Clear(); } void Verify() const; void LoadAndCollectLootIds(LootIdSet& ids_set); void CheckLootRefs(LootIdSet* ref_set = NULL) const;// check existence reference and remove it from ref_set void ReportUnusedIds(LootIdSet const& ids_set) const; void ReportNotExistedId(uint32 id) const; bool HaveLootFor(uint32 loot_id) const { return m_LootTemplates.find(loot_id) != m_LootTemplates.end(); } bool HaveQuestLootFor(uint32 loot_id) const; bool HaveQuestLootForPlayer(uint32 loot_id,Player* player) const; LootTemplate const* GetLootFor(uint32 loot_id) const; char const* GetName() const { return m_name; } char const* GetEntryName() const { return m_entryName; } bool IsRatesAllowed() const { return m_ratesAllowed; } protected: void LoadLootTable(); void Clear(); private: LootTemplateMap m_LootTemplates; char const* m_name; char const* m_entryName; bool m_ratesAllowed; }; class LootTemplate { class LootGroup; // A set of loot definitions for items (refs are not allowed inside) typedef std::vector<LootGroup> LootGroups; public: // Adds an entry to the group (at loading stage) void AddEntry(LootStoreItem& item); // Rolls for every item in the template and adds the rolled items the the loot void Process(Loot& loot, LootStore const& store, bool rate, uint8 GroupId = 0) const; // True if template includes at least 1 quest drop entry bool HasQuestDrop(LootTemplateMap const& store, uint8 GroupId = 0) const; // True if template includes at least 1 quest drop for an active quest of the player bool HasQuestDropForPlayer(LootTemplateMap const& store, Player const * player, uint8 GroupId = 0) const; // Checks integrity of the template void Verify(LootStore const& store, uint32 Id) const; void CheckLootRefs(LootIdSet* ref_set) const; private: LootStoreItemList Entries; // not grouped only LootGroups Groups; // groups have own (optimised) processing, grouped entries go there }; //===================================================== class LootValidatorRef : public Reference<Loot, LootValidatorRef> { public: LootValidatorRef() {} void targetObjectDestroyLink() {} void sourceObjectDestroyLink() {} }; //===================================================== class LootValidatorRefManager : public RefManager<Loot, LootValidatorRef> { public: typedef LinkedListHead::Iterator< LootValidatorRef > iterator; LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager<Loot, LootValidatorRef>::getFirst(); } LootValidatorRef* getLast() { return (LootValidatorRef*)RefManager<Loot, LootValidatorRef>::getLast(); } iterator begin() { return iterator(getFirst()); } iterator end() { return iterator(NULL); } iterator rbegin() { return iterator(getLast()); } iterator rend() { return iterator(NULL); } }; //===================================================== struct LootView; ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); struct Loot { friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); QuestItemMap const& GetPlayerQuestItems() const { return m_playerQuestItems; } QuestItemMap const& GetPlayerFFAItems() const { return m_playerFFAItems; } QuestItemMap const& GetPlayerNonQuestNonFFAConditionalItems() const { return m_playerNonQuestNonFFAConditionalItems; } LootItemList items; uint32 gold; uint8 unlootedCount; LootType loot_type; // required for achievement system Loot(uint32 _gold = 0) : gold(_gold), unlootedCount(0), loot_type(LOOT_CORPSE) {} ~Loot() { clear(); } // if loot becomes invalid this reference is used to inform the listener void addLootValidatorRef(LootValidatorRef* pLootValidatorRef) { m_LootValidatorRefManager.insertFirst(pLootValidatorRef); } // void clear(); void clear() { for (QuestItemMap::const_iterator itr = m_playerQuestItems.begin(); itr != m_playerQuestItems.end(); ++itr) delete itr->second; m_playerQuestItems.clear(); for (QuestItemMap::const_iterator itr = m_playerFFAItems.begin(); itr != m_playerFFAItems.end(); ++itr) delete itr->second; m_playerFFAItems.clear(); for (QuestItemMap::const_iterator itr = m_playerNonQuestNonFFAConditionalItems.begin(); itr != m_playerNonQuestNonFFAConditionalItems.end(); ++itr) delete itr->second; m_playerNonQuestNonFFAConditionalItems.clear(); m_playersLooting.clear(); items.clear(); m_questItems.clear(); gold = 0; unlootedCount = 0; m_LootValidatorRefManager.clearReferences(); } bool empty() const { return items.empty() && gold == 0; } bool isLooted() const { return gold == 0 && unlootedCount == 0; } void NotifyItemRemoved(uint8 lootIndex); void NotifyQuestItemRemoved(uint8 questIndex); void NotifyMoneyRemoved(); void AddLooter(ObjectGuid guid) { m_playersLooting.insert(guid); } void RemoveLooter(ObjectGuid guid) { m_playersLooting.erase(guid); } void generateMoneyLoot(uint32 minAmount, uint32 maxAmount); bool FillLoot(uint32 loot_id, LootStore const& store, Player* loot_owner, bool personal, bool noEmptyError = false); // Inserts the item into the loot (called by LootTemplate processors) void AddItem(LootStoreItem const & item); LootItem* LootItemInSlot(uint32 lootslot, Player* player, QuestItem** qitem = NULL, QuestItem** ffaitem = NULL, QuestItem** conditem = NULL); uint32 GetMaxSlotInLootFor(Player* player) const; private: void FillNotNormalLootFor(Player* player); QuestItemList* FillFFALoot(Player* player); QuestItemList* FillQuestLoot(Player* player); QuestItemList* FillNonQuestNonFFAConditionalLoot(Player* player); LootItemList m_questItems; typedef std::set<ObjectGuid> PlayersLooting; PlayersLooting m_playersLooting; QuestItemMap m_playerQuestItems; QuestItemMap m_playerFFAItems; QuestItemMap m_playerNonQuestNonFFAConditionalItems; // All rolls are registered here. They need to know, when the loot is not valid anymore LootValidatorRefManager m_LootValidatorRefManager; }; struct LootView { Loot &loot; Player *viewer; PermissionTypes permission; LootView(Loot &_loot, Player *_viewer,PermissionTypes _permission = ALL_PERMISSION) : loot(_loot), viewer(_viewer), permission(_permission) {} }; extern LootStore LootTemplates_Creature; extern LootStore LootTemplates_Fishing; extern LootStore LootTemplates_Gameobject; extern LootStore LootTemplates_Item; extern LootStore LootTemplates_Mail; extern LootStore LootTemplates_Milling; extern LootStore LootTemplates_Pickpocketing; extern LootStore LootTemplates_Skinning; extern LootStore LootTemplates_Disenchant; extern LootStore LootTemplates_Prospecting; extern LootStore LootTemplates_Spell; void LoadLootTemplates_Creature(); void LoadLootTemplates_Fishing(); void LoadLootTemplates_Gameobject(); void LoadLootTemplates_Item(); void LoadLootTemplates_Mail(); void LoadLootTemplates_Milling(); void LoadLootTemplates_Pickpocketing(); void LoadLootTemplates_Skinning(); void LoadLootTemplates_Disenchant(); void LoadLootTemplates_Prospecting(); void LoadLootTemplates_Spell(); void LoadLootTemplates_Reference(); inline void LoadLootTables() { LoadLootTemplates_Creature(); LoadLootTemplates_Fishing(); LoadLootTemplates_Gameobject(); LoadLootTemplates_Item(); LoadLootTemplates_Mail(); LoadLootTemplates_Milling(); LoadLootTemplates_Pickpocketing(); LoadLootTemplates_Skinning(); LoadLootTemplates_Disenchant(); LoadLootTemplates_Prospecting(); LoadLootTemplates_Spell(); LoadLootTemplates_Reference(); } #endif
Kreegoth/Darkportalwow
src/game/LootMgr.h
C
gpl-2.0
14,833
/* * grunt-notify * https://github.com/dylang/grunt-notify * * Copyright (c) 2014 Dylan Greene, 2014 Matej Simek * Licensed under the MIT license. */ 'use strict'; var NOTIFY_TYPE = 'toaster'; var path = require('path'); var os = require('os'); var spawn = require('../util/spawn'); var semver = require('semver'); // A wee Win8 console notifications app. Post toast notifications from the console, making it easy to integrate into existing batch scripts etc. // Toaster by Nels Oscar https://github.com/nels-o/toaster var CMD = path.resolve(__dirname, '../../bin/toaster/toast.exe'); var IS_WINDOWS = os.type() === 'Windows_NT'; var DEFAULT_IMAGE = path.resolve(__dirname, '../../images/grunt-logo.png'); function supported(options) { var WINDOWS_8; try { WINDOWS_8 = IS_WINDOWS && semver.satisfies(os.release(), '>=6.2.9200'); } catch (e) { options.debug({semverError: e }); } options.debug({ os: os.type(), version: os.release(), IS_WINDOWS: IS_WINDOWS, WINDOWS_8: WINDOWS_8, toaster: IS_WINDOWS && WINDOWS_8 ? 'Will use Windows 8 notifications' : 'Not available for your OS.' }); return IS_WINDOWS && WINDOWS_8; } function notify(options, cb) { var args = [ '-p', DEFAULT_IMAGE, '-t', options.title, '-m', options.message ]; options.debug({ cmd: CMD, args: args.join(' ') }); spawn(CMD, args, function(code) { if (code !== 0) { cb(code); } else { cb(); } }); } module.exports = { name: NOTIFY_TYPE, notify: notify, supported: supported };
marceliotstein/marcelio8
web/themes/baspac/node_modules/grunt-notify/lib/platforms/toaster.js
JavaScript
gpl-2.0
1,564
explain select actor_id, (select count(film_id) from sakila.film join sakila.film_actor using(film_id)) from sakila.actor; +----+-------------+------------+-------+----------------+--------------------+---------+---------------------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+-------+----------------+--------------------+---------+---------------------+------+-------------+ | 1 | PRIMARY | actor | index | NULL | PRIMARY | 2 | NULL | 200 | Using index | | 2 | SUBQUERY | film | index | PRIMARY | idx_fk_language_id | 1 | NULL | 951 | Using index | | 2 | SUBQUERY | film_actor | ref | idx_fk_film_id | idx_fk_film_id | 2 | sakila.film.film_id | 2 | Using index | +----+-------------+------------+-------+----------------+--------------------+---------+---------------------+------+-------------+ 3 rows in set (0.00 sec) mysql> notee
fipar/percona-toolkit
t/pt-visual-explain/samples/join_in_subquery.sql
SQL
gpl-2.0
1,100
// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // package com.cloud.utils.time; public interface InaccurateClockMBean { String restart(); String turnOff(); long[] getCurrentTimes(); }
ikoula/cloudstack
utils/src/main/java/com/cloud/utils/time/InaccurateClockMBean.java
Java
gpl-2.0
957
/* LUFA Library Copyright (C) Dean Camera, 2011. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** \file * \brief Board specific LED driver header for the Tempusdictum Benito. * \copydetails Group_LEDs_BENITO * * \note This file should not be included directly. It is automatically included as needed by the LEDs driver * dispatch header located in LUFA/Drivers/Board/LEDs.h. */ /** \ingroup Group_LEDs * \defgroup Group_LEDs_BENITO BENITO * \brief Board specific LED driver header for the Tempusdictum Benito. * * Board specific LED driver header for the Tempusdictum Benito (http://dorkbotpdx.org/wiki/benito). * * @{ */ #ifndef __LEDS_BENITO_H__ #define __LEDS_BENITO_H__ /* Includes: */ #include "../../../Common/Common.h" /* Enable C linkage for C++ Compilers: */ #if defined(__cplusplus) extern "C" { #endif /* Preprocessor Checks: */ #if !defined(__INCLUDE_FROM_LEDS_H) #error Do not include this file directly. Include LUFA/Drivers/Board/LEDS.h instead. #endif /* Public Interface - May be used in end-application: */ /* Macros: */ /** LED mask for the first LED on the board. */ #define LEDS_LED1 (1 << 7) /** LED mask for the second LED on the board. */ #define LEDS_LED2 (1 << 6) /** LED mask for all the LEDs on the board. */ #define LEDS_ALL_LEDS (LEDS_LED1 | LEDS_LED2) /** LED mask for none of the board LEDs. */ #define LEDS_NO_LEDS 0 /* Inline Functions: */ #if !defined(__DOXYGEN__) static inline void LEDs_Init(void) { DDRC |= LEDS_ALL_LEDS; PORTC |= LEDS_ALL_LEDS; } static inline void LEDs_TurnOnLEDs(const uint8_t LEDMask) { PORTC &= ~LEDMask; } static inline void LEDs_TurnOffLEDs(const uint8_t LEDMask) { PORTC |= LEDMask; } static inline void LEDs_SetAllLEDs(const uint8_t LEDMask) { PORTC = ((PORTC | LEDS_ALL_LEDS) & ~LEDMask); } static inline void LEDs_ChangeLEDs(const uint8_t LEDMask, const uint8_t ActiveMask) { PORTC = ((PORTC | LEDMask) & ~ActiveMask); } static inline void LEDs_ToggleLEDs(const uint8_t LEDMask) { PORTC ^= LEDMask; } static inline uint8_t LEDs_GetLEDs(void) ATTR_WARN_UNUSED_RESULT; static inline uint8_t LEDs_GetLEDs(void) { return (PORTC & LEDS_ALL_LEDS); } #endif /* Disable C linkage for C++ Compilers: */ #if defined(__cplusplus) } #endif #endif /** @} */
SelfDesignRobotics/DuinoPack
win/hardware/multiplo/avr/bootloaders/DuinoBot.v1.x/Sources/HID/LUFA/Drivers/Board/BENITO/LEDs.h
C
gpl-2.0
3,686
/* =========================================================================== Copyright (C) 1999 - 2005, Id Software, Inc. Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #ifndef __G_LOCAL_H__ #define __G_LOCAL_H__ // g_local.h -- local definitions for game module // define GAME_INCLUDE so that g_public.h does not define the // short, server-visible gclient_t and gentity_t structures, // because we define the full size ones in this file #define GAME_INCLUDE #include "../../code/ui/gameinfo.h" #include "g_shared.h" #include "anims.h" #include "dmstates.h" #include "time.h" //================================================================== // the "gameversion" client command will print this plus compile date #define GAMEVERSION "base" #define BODY_QUEUE_SIZE 8 #define Q3_INFINITE 16777216 #define FRAMETIME 100 // msec #define EVENT_VALID_MSEC 300 #define CARNAGE_REWARD_TIME 3000 #define INTERMISSION_DELAY_TIME 1000 #define START_TIME_LINK_ENTS FRAMETIME*1 // time-delay after map start at which all ents have been spawned, so can link them #define START_TIME_FIND_LINKS FRAMETIME*2 // time-delay after map start at which you can find linked entities #define START_TIME_MOVERS_SPAWNED FRAMETIME*2 // time-delay after map start at which all movers should be spawned #define START_TIME_REMOVE_ENTS FRAMETIME*3 // time-delay after map start to remove temporary ents #define START_TIME_NAV_CALC FRAMETIME*4 // time-delay after map start to connect waypoints and calc routes #define START_TIME_FIND_WAYPOINT FRAMETIME*5 // time-delay after map start after which it's okay to try to find your best waypoint // gentity->flags #define FL_SHIELDED 0x00000001 // protected from all damage except lightsabers #define FL_DMG_BY_HEAVY_WEAP_ONLY 0x00000002 // protected from all damage except heavy weap class missiles #define FL_DMG_BY_SABER_ONLY 0x00000004 //protected from all damage except saber damage #define FL_GODMODE 0x00000010 #define FL_NOTARGET 0x00000020 #define FL_TEAMSLAVE 0x00000400 // not the first on the team #define FL_NO_KNOCKBACK 0x00000800 #define FL_DROPPED_ITEM 0x00001000 #define FL_DONT_SHOOT 0x00002000 // Can target him, but not shoot him #define FL_UNDYING 0x00004000 // Takes damage down to 1 point, but does not die //#define FL_OVERCHARGED 0x00008000 // weapon shot is an overcharged version....probably a lame place to be putting this flag... #define FL_LOCK_PLAYER_WEAPONS 0x00010000 // player can't switch weapons... ask james if there's a better spot for this #define FL_DISINTEGRATED 0x00020000 // marks that the corpse has already been disintegrated #define FL_FORCE_PULLABLE_ONLY 0x00040000 // cannot be force pushed #define FL_NO_IMPACT_DMG 0x00080000 // Will not take impact damage //Pointer safety utilities #define VALID( a ) ( a != NULL ) #define VALIDATE( a ) ( assert( a ) ) #define VALIDATEV( a ) if ( a == NULL ) { assert(0); return; } #define VALIDATEB( a ) if ( a == NULL ) { assert(0); return qfalse; } #define VALIDATEP( a ) if ( a == NULL ) { assert(0); return NULL; } #define VALIDSTRING( a ) ( ( a != NULL ) && ( a[0] != '\0' ) ) //Interest points #define MAX_INTEREST_POINTS 64 typedef struct { vec3_t origin; char *target; } interestPoint_t; //Combat points #define MAX_COMBAT_POINTS 512 typedef struct { vec3_t origin; int flags; // char *NPC_targetname; // team_t team; qboolean occupied; int waypoint; int dangerTime; } combatPoint_t; // Alert events #define MAX_ALERT_EVENTS 32 enum alertEventType_e { AET_SIGHT, AET_SOUND, }; enum alertEventLevel_e { AEL_MINOR, //Enemy responds to the sound, but only by looking AEL_SUSPICIOUS, //Enemy looks at the sound, and will also investigate it AEL_DISCOVERED, //Enemy knows the player is around, and will actively hunt AEL_DANGER, //Enemy should try to find cover AEL_DANGER_GREAT, //Enemy should run like hell! }; // !!!!!!!!! LOADSAVE-affecting struct !!!!!!!!!! class alertEvent_t { public: vec3_t position; //Where the event is located float radius; //Consideration radius alertEventLevel_e level; //Priority level of the event alertEventType_e type; //Event type (sound,sight) gentity_t *owner; //Who made the sound float light; //ambient light level at point float addLight; //additional light- makes it more noticable, even in darkness int ID; //unique... if get a ridiculous number, this will repeat, but should not be a problem as it's just comparing it to your lastAlertID int timestamp; //when it was created void sg_export( ojk::SavedGameHelper& saved_game) const { saved_game.write<float>(position); saved_game.write<float>(radius); saved_game.write<int32_t>(level); saved_game.write<int32_t>(type); saved_game.write<int32_t>(owner); saved_game.write<float>(light); saved_game.write<float>(addLight); saved_game.write<int32_t>(ID); saved_game.write<int32_t>(timestamp); } void sg_import( ojk::SavedGameHelper& saved_game) { saved_game.read<float>(position); saved_game.read<float>(radius); saved_game.read<int32_t>(level); saved_game.read<int32_t>(type); saved_game.read<int32_t>(owner); saved_game.read<float>(light); saved_game.read<float>(addLight); saved_game.read<int32_t>(ID); saved_game.read<int32_t>(timestamp); } }; // alertEvent_t // // this structure is cleared as each map is entered // #define MAX_SPAWN_VARS 64 #define MAX_SPAWN_VARS_CHARS 2048 typedef struct { char targetname[MAX_QPATH]; char target[MAX_QPATH]; char target2[MAX_QPATH]; char target3[MAX_QPATH]; char target4[MAX_QPATH]; int nodeID; } waypointData_t; #define WF_RAINING 0x00000001 //raining #define WF_SNOWING 0x00000002 //snowing // !!!!!!!!!! LOADSAVE-affecting structure !!!!!!!!!! class level_locals_t { public: gclient_t *clients; // [maxclients] // store latched cvars here that we want to get at often int maxclients; int framenum; int time; // in msec int previousTime; // so movers can back up when blocked int globalTime; // global time at level initialization char mapname[MAX_QPATH]; // the server name (base1, etc) qboolean locationLinked; // target_locations get linked gentity_t *locationHead; // head of the location list alertEvent_t alertEvents[ MAX_ALERT_EVENTS ]; int numAlertEvents; int curAlertID; AIGroupInfo_t groups[MAX_FRAME_GROUPS]; animFileSet_t knownAnimFileSets[MAX_ANIM_FILES]; int numKnownAnimFileSets; int worldFlags; int dmState; //actually, we do want save/load the dynamic music state // ===================================== // // NOTE!!!!!! The only things beyond this point in the structure should be the ones you do NOT wish to be // affected by loading saved-games. Since loading a game first starts the map and then loads // over things like entities etc then these fields are usually the ones setup by the map loader. // If they ever get modified in-game let me know and I'll include them in the save. -Ste // #define LEVEL_LOCALS_T_SAVESTOP logFile // name of whichever field is next below this in the source fileHandle_t logFile; //Interest points- squadmates automatically look at these if standing around and close to them interestPoint_t interestPoints[MAX_INTEREST_POINTS]; int numInterestPoints; //Combat points- NPCs in bState BS_COMBAT_POINT will find their closest empty combat_point combatPoint_t combatPoints[MAX_COMBAT_POINTS]; int numCombatPoints; char spawntarget[MAX_QPATH]; // the targetname of the spawnpoint you want the player to start at int dmDebounceTime; int dmBeatTime; void sg_export( ojk::SavedGameHelper& saved_game) const { saved_game.write<int32_t>(clients); saved_game.write<int32_t>(maxclients); saved_game.write<int32_t>(framenum); saved_game.write<int32_t>(time); saved_game.write<int32_t>(previousTime); saved_game.write<int32_t>(globalTime); saved_game.write<int8_t>(mapname); saved_game.write<int32_t>(locationLinked); saved_game.write<int32_t>(locationHead); saved_game.write<>(alertEvents); saved_game.write<int32_t>(numAlertEvents); saved_game.write<int32_t>(curAlertID); saved_game.write<>(groups); saved_game.write<>(knownAnimFileSets); saved_game.write<int32_t>(numKnownAnimFileSets); saved_game.write<int32_t>(worldFlags); saved_game.write<int32_t>(dmState); } void sg_import( ojk::SavedGameHelper& saved_game) { saved_game.read<int32_t>(clients); saved_game.read<int32_t>(maxclients); saved_game.read<int32_t>(framenum); saved_game.read<int32_t>(time); saved_game.read<int32_t>(previousTime); saved_game.read<int32_t>(globalTime); saved_game.read<int8_t>(mapname); saved_game.read<int32_t>(locationLinked); saved_game.read<int32_t>(locationHead); saved_game.read<>(alertEvents); saved_game.read<int32_t>(numAlertEvents); saved_game.read<int32_t>(curAlertID); saved_game.read<>(groups); saved_game.read<>(knownAnimFileSets); saved_game.read<int32_t>(numKnownAnimFileSets); saved_game.read<int32_t>(worldFlags); saved_game.read<int32_t>(dmState); } }; // level_locals_t extern level_locals_t level; extern game_export_t globals; extern cvar_t *g_gravity; extern cvar_t *g_speed; extern cvar_t *g_cheats; extern cvar_t *g_developer; extern cvar_t *g_knockback; extern cvar_t *g_inactivity; extern cvar_t *g_debugMove; extern cvar_t *g_subtitles; extern cvar_t *g_removeDoors; extern cvar_t *g_ICARUSDebug; extern gentity_t *player; // // g_spawn.c // qboolean G_SpawnString( const char *key, const char *defaultString, char **out ); // spawn string returns a temporary reference, you must CopyString() if you want to keep it qboolean G_SpawnFloat( const char *key, const char *defaultString, float *out ); qboolean G_SpawnInt( const char *key, const char *defaultString, int *out ); qboolean G_SpawnVector( const char *key, const char *defaultString, float *out ); qboolean G_SpawnVector4( const char *key, const char *defaultString, float *out ); qboolean G_SpawnAngleHack( const char *key, const char *defaultString, float *out ); void G_SpawnEntitiesFromString( const char *entities ); // // g_cmds.c // void Cmd_Score_f (gentity_t *ent); // // g_items.c // void G_RunItem( gentity_t *ent ); void RespawnItem( gentity_t *ent ); void UseHoldableItem( gentity_t *ent ); void PrecacheItem (gitem_t *it); gentity_t *Drop_Item( gentity_t *ent, gitem_t *item, float angle, qboolean copytarget ); void SetRespawn (gentity_t *ent, float delay); void G_SpawnItem (gentity_t *ent, gitem_t *item); void FinishSpawningItem( gentity_t *ent ); void Think_Weapon (gentity_t *ent); int ArmorIndex (gentity_t *ent); void Add_Ammo (gentity_t *ent, int weapon, int count); void Touch_Item (gentity_t *ent, gentity_t *other, trace_t *trace); void ClearRegisteredItems( void ); void RegisterItem( gitem_t *item ); void SaveRegisteredItems( void ); // // g_utils.c // int G_ModelIndex( const char *name ); int G_SoundIndex( const char *name ); /* Ghoul2 Insert Start */ int G_SkinIndex( const char *name ); void G_SetBoltSurfaceRemoval( const int entNum, const int modelIndex, const int boltIndex, const int surfaceIndex = -1, float duration = 5000 ); /* Ghoul2 Insert End */ int G_EffectIndex( const char *name ); void G_PlayEffect( const char *name, vec3_t origin ); void G_PlayEffect( const char *name, int clientNum ); void G_PlayEffect( const char *name, vec3_t origin, vec3_t fwd ); void G_PlayEffect( const char *name, vec3_t origin, vec3_t axis[3] ); void G_PlayEffect( const char *name, const int modelIndex, const int boltIndex, const int entNum); void G_PlayEffect( int fxID, vec3_t origin, vec3_t fwd ); void G_PlayEffect( int fxID, vec3_t origin, vec3_t axis[3] ); void G_PlayEffect( int fxID, const int modelIndex, const int boltIndex, const int entNum); void G_PlayEffect( int fxID, int entNum, vec3_t fwd ); void G_KillBox (gentity_t *ent); gentity_t *G_Find (gentity_t *from, int fieldofs, const char *match); int G_RadiusList ( vec3_t origin, float radius, gentity_t *ignore, qboolean takeDamage, gentity_t *ent_list[MAX_GENTITIES]); gentity_t *G_PickTarget (char *targetname); void G_UseTargets (gentity_t *ent, gentity_t *activator); void G_UseTargets2 (gentity_t *ent, gentity_t *activator, const char *string); void G_SetMovedir ( vec3_t angles, vec3_t movedir); void G_InitGentity( gentity_t *e ); gentity_t *G_Spawn (void); gentity_t *G_TempEntity( vec3_t origin, int event ); void G_Sound( gentity_t *ent, int soundIndex ); void G_FreeEntity( gentity_t *e ); void G_TouchTriggers (gentity_t *ent); void G_TouchTeamClients (gentity_t *ent); void G_TouchSolids (gentity_t *ent); float *tv (float x, float y, float z); char *vtos( const vec3_t v ); float vectoyaw( const vec3_t vec ); void G_AddEvent( gentity_t *ent, int event, int eventParm ); void G_SetOrigin( gentity_t *ent, const vec3_t origin ); void G_SetAngles( gentity_t *ent, const vec3_t angles ); void G_DebugLine(vec3_t A, vec3_t B, int duration, int color, qboolean deleteornot); // // g_combat.c // qboolean CanDamage (gentity_t *targ, vec3_t origin); void G_Damage( gentity_t *targ, gentity_t *inflictor, gentity_t *attacker, vec3_t dir, vec3_t point, int damage, int dflags, int mod, int hitLoc=HL_NONE ); void G_RadiusDamage (vec3_t origin, gentity_t *attacker, float damage, float radius, gentity_t *ignore, int mod); gentity_t *TossClientItems( gentity_t *self ); void ExplodeDeath_Wait( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath,int dFlags,int hitLoc ); void ExplodeDeath( gentity_t *self ); void GoExplodeDeath( gentity_t *self, gentity_t *other, gentity_t *activator); void G_ApplyKnockback( gentity_t *targ, vec3_t newDir, float knockback ); void G_Throw( gentity_t *targ, vec3_t newDir, float push ); // damage flags #define DAMAGE_RADIUS 0x00000001 // damage was indirect #define DAMAGE_NO_ARMOR 0x00000002 // armour does not protect from this damage #define DAMAGE_NO_KNOCKBACK 0x00000008 // do not affect velocity, just view angles #define DAMAGE_NO_HIT_LOC 0x00000010 // do not modify damage by hit loc #define DAMAGE_NO_PROTECTION 0x00000020 // armor, shields, invulnerability, and godmode have no effect #define DAMAGE_EXTRA_KNOCKBACK 0x00000040 // add extra knockback to this damage #define DAMAGE_DEATH_KNOCKBACK 0x00000080 // only does knockback on death of target #define DAMAGE_IGNORE_TEAM 0x00000100 // damage is always done, regardless of teams #define DAMAGE_NO_DAMAGE 0x00000200 // do no actual damage but react as if damage was taken #define DAMAGE_DISMEMBER 0x00000400 // do dismemberment #define DAMAGE_NO_KILL 0x00000800 // do damage, but don't kill them #define DAMAGE_HEAVY_WEAP_CLASS 0x00001000 // doing heavy weapon type damage, certain objects may only take damage by missiles containing this flag #define DAMAGE_CUSTOM_HUD 0x00002000 // really dumb, but.... // // g_missile.c // void G_RunMissile( gentity_t *ent ); gentity_t *fire_blaster (gentity_t *self, vec3_t start, vec3_t aimdir); gentity_t *fire_plasma (gentity_t *self, vec3_t start, vec3_t aimdir); gentity_t *fire_grenade (gentity_t *self, vec3_t start, vec3_t aimdir); gentity_t *fire_rocket (gentity_t *self, vec3_t start, vec3_t dir); // // g_mover.c // void G_RunMover( gentity_t *ent ); // // g_misc.c // void TeleportPlayer( gentity_t *player, vec3_t origin, vec3_t angles ); // // g_weapon.c // //void CalcMuzzlePoint ( gentity_t *ent, vec3_t forward, vec3_t right, vec3_t up, vec3_t muzzlePoint ); //void SnapVectorTowards( vec3_t v, vec3_t to ); //qboolean CheckGauntletAttack( gentity_t *ent ); void WP_LoadWeaponParms (void); void IT_LoadItemParms( void ); // // g_client.c // team_t PickTeam( int ignoreClientNum ); void SetClientViewAngle( gentity_t *ent, vec3_t angle ); gentity_t *SelectSpawnPoint ( vec3_t avoidPoint, team_t team, vec3_t origin, vec3_t angles ); void respawn (gentity_t *ent); void InitClientPersistant (gclient_t *client); void InitClientResp (gclient_t *client); qboolean ClientSpawn( gentity_t *ent, SavedGameJustLoaded_e eSavedGameJustLoaded ); void player_die (gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod, int dFlags, int hitLoc); void AddScore( gentity_t *ent, int score ); qboolean SpotWouldTelefrag( gentity_t *spot, team_t checkteam ); // // g_svcmds.c // qboolean ConsoleCommand( void ); // // g_weapon.c // void FireWeapon( gentity_t *ent, qboolean alt_fire ); // // p_hud.c // void MoveClientToIntermission (gentity_t *client); void G_SetStats (gentity_t *ent); void DeathmatchScoreboardMessage (gentity_t *client); // // g_pweapon.c // // // g_main.c // void G_RunThink (gentity_t *ent); void QDECL G_Error( const char *fmt, ... ); void ClearAllInUse(void); void SetInUse(gentity_t *ent); void ClearInUse(gentity_t *ent); qboolean PInUse(unsigned int entNum); qboolean PInUse2(gentity_t *ent); void WriteInUseBits(void); void ReadInUseBits(void); // // g_nav.cpp // void Svcmd_Nav_f (void); // // g_squad.cpp // void Svcmd_Comm_f (void); void Svcmd_Hail_f (void); void Svcmd_Form_f (void); // // g_utils.cpp // void Svcmd_Use_f (void); // // g_weapons.cpp // // // g_client.c // char *ClientConnect( int clientNum, qboolean firstTime, SavedGameJustLoaded_e eSavedGameJustLoaded ); void ClientUserinfoChanged( int clientNum ); void ClientDisconnect( int clientNum ); void ClientBegin( int clientNum, usercmd_t *cmd, SavedGameJustLoaded_e eSavedGameJustLoaded ); void ClientCommand( int clientNum ); // // g_active.c // void ClientThink( int clientNum, usercmd_t *cmd ); void ClientEndFrame (gentity_t *ent); // // g_inventory.cpp // extern qboolean INV_GoodieKeyGive( gentity_t *target ); extern qboolean INV_GoodieKeyTake( gentity_t *target ); extern int INV_GoodieKeyCheck( gentity_t *target ); extern qboolean INV_SecurityKeyGive( gentity_t *target, const char *keyname ); extern void INV_SecurityKeyTake( gentity_t *target, char *keyname ); extern qboolean INV_SecurityKeyCheck( gentity_t *target, char *keyname ); // // g_team.c // qboolean OnSameTeam( gentity_t *ent1, gentity_t *ent2 ); // // g_mem.c // void *G_Alloc( int size ); void G_InitMemory( void ); void Svcmd_GameMem_f( void ); // // g_session.c // void G_ReadSessionData( gclient_t *client ); void G_InitSessionData( gclient_t *client, char *userinfo ); void G_InitWorldSession( void ); void G_WriteSessionData( void ); // // NPC_senses.cpp // extern void AddSightEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, float addLight=0.0f ); extern void AddSoundEvent( gentity_t *owner, vec3_t position, float radius, alertEventLevel_e alertLevel, qboolean needLOS = qfalse ); extern qboolean G_CheckForDanger( gentity_t *self, int alertEvent ); extern int G_CheckAlertEvents( gentity_t *self, qboolean checkSight, qboolean checkSound, float maxSeeDist, float maxHearDist, int ignoreAlert = -1, qboolean mustHaveOwner = qfalse, int minAlertLevel = AEL_MINOR ); extern qboolean G_CheckForDanger( gentity_t *self, int alertEvent ); extern qboolean G_ClearLOS( gentity_t *self, const vec3_t start, const vec3_t end ); extern qboolean G_ClearLOS( gentity_t *self, gentity_t *ent, const vec3_t end ); extern qboolean G_ClearLOS( gentity_t *self, const vec3_t start, gentity_t *ent ); extern qboolean G_ClearLOS( gentity_t *self, gentity_t *ent ); extern qboolean G_ClearLOS( gentity_t *self, const vec3_t end ); //============================================================================ //Tags // Reference tags #define MAX_REFTAGS 128 // Probably more than we'll ever need #define MAX_REFNAME 32 #define RTF_NONE 0 #define RTF_NAVGOAL 0x00000001 typedef struct reference_tag_s { char name[MAX_REFNAME]; vec3_t origin; vec3_t angles; int flags; //Just in case int radius; //For nav goals } reference_tag_t; extern void TAG_Init( void ); extern reference_tag_t *TAG_Add( const char *name, const char *owner, vec3_t origin, vec3_t angles, int radius, int flags ); extern int TAG_GetOrigin( const char *owner, const char *name, vec3_t origin ); extern int TAG_GetAngles( const char *owner, const char *name, vec3_t angles ); extern int TAG_GetRadius( const char *owner, const char *name ); extern int TAG_GetFlags( const char *owner, const char *name ); void TAG_ShowTags( int flags ); // Reference tags END typedef struct pscript_s { char *buffer; long length; } pscript_t; typedef std::map < std::string, int, std::less<std::string>, std::allocator<int> > entlist_t; typedef std::map < std::string, pscript_t*, std::less<std::string>, std::allocator<pscript_t*> > bufferlist_t; extern char *G_NewString( const char *string ); // some stuff for savegames... // void WriteLevel(qboolean qbAutosave); void ReadLevel(qboolean qbAutosave, qboolean qbLoadTransition); qboolean GameAllowedToSaveHere(void); extern qboolean G_ActivateBehavior( gentity_t *ent, int bset ); //Timing information void TIMER_Clear( void ); void TIMER_Clear( gentity_t *ent ); void TIMER_Save( void ); void TIMER_Load( void ); void TIMER_Set( gentity_t *ent, const char *identifier, int duration ); int TIMER_Get( gentity_t *ent, const char *identifier ); qboolean TIMER_Done( gentity_t *ent, const char *identifier ); qboolean TIMER_Start( gentity_t *self, const char *identifier, int duration ); qboolean TIMER_Done2( gentity_t *ent, const char *identifier, qboolean remove = qfalse ); qboolean TIMER_Exists( gentity_t *ent, const char *identifier ); void TIMER_Remove( gentity_t *ent, const char *identifier ); float NPC_GetHFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float hFOV ); float NPC_GetVFOVPercentage( vec3_t spot, vec3_t from, vec3_t facing, float vFOV ); #endif//#ifndef __G_LOCAL_H__
AlexCSilva/OpenJK
codeJK2/game/g_local.h
C
gpl-2.0
22,512
<?php /** * Contains EWSType_ExchangeImpersonationType. */ /** * Represents the account to impersonate within a request. * * @package php-ews\Types */ class EWSType_ExchangeImpersonationType extends EWSType { /** * Represents an account to impersonate when you are using the * ExchangeImpersonation SOAP header. * * @since Exchange 2007 * * @var EWSType_ConnectingSIDType */ public $ConnectingSID; }
andrewwippler/rpi-wayfinding
php-ews/EWSType/ExchangeImpersonationType.php
PHP
gpl-2.0
450
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="robots" content="noindex"> <title>File account/modules.php | Cypht Documentation</title> <link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Packages</h3> <ul> <li> <a href="package-framework.html"> framework<span></span> </a> <ul> <li> <a href="package-framework.auth.html"> auth </a> </li> <li> <a href="package-framework.cache.html"> cache </a> </li> <li> <a href="package-framework.config.html"> config </a> </li> <li> <a href="package-framework.crypt.html"> crypt </a> </li> <li> <a href="package-framework.db.html"> db </a> </li> <li> <a href="package-framework.dispatch.html"> dispatch </a> </li> <li> <a href="package-framework.format.html"> format </a> </li> <li> <a href="package-framework.module.html"> module </a> </li> <li> <a href="package-framework.modules.html"> modules </a> </li> <li> <a href="package-framework.oauth2.html"> oauth2 </a> </li> <li> <a href="package-framework.output.html"> output </a> </li> <li> <a href="package-framework.request.html"> request </a> </li> <li> <a href="package-framework.servers.html"> servers </a> </li> <li> <a href="package-framework.session.html"> session </a> </li> <li> <a href="package-framework.setup.html"> setup </a> </li> </ul></li> <li> <a href="package-modules.html"> modules<span></span> </a> <ul> <li> <a href="package-modules.account.html"> account<span></span> </a> <ul> <li> <a href="package-modules.account.handler.html"> handler </a> </li> <li> <a href="package-modules.account.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.calendar.html"> calendar<span></span> </a> <ul> <li> <a href="package-modules.calendar.handler.html"> handler </a> </li> <li> <a href="package-modules.calendar.lib.html"> lib </a> </li> <li> <a href="package-modules.calendar.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.contacts.html"> contacts<span></span> </a> <ul> <li> <a href="package-modules.contacts.handler.html"> handler </a> </li> <li> <a href="package-modules.contacts.lib.html"> lib </a> </li> <li> <a href="package-modules.contacts.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.core.html"> core<span></span> </a> <ul> <li> <a href="package-modules.core.functions.html"> functions </a> </li> <li> <a href="package-modules.core.handler.html"> handler </a> </li> <li> <a href="package-modules.core.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.developer.html"> developer<span></span> </a> <ul> <li> <a href="package-modules.developer.handler.html"> handler </a> </li> <li> <a href="package-modules.developer.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.feeds.html"> feeds<span></span> </a> <ul> <li> <a href="package-modules.feeds.functions.html"> functions </a> </li> <li> <a href="package-modules.feeds.handler.html"> handler </a> </li> <li> <a href="package-modules.feeds.lib.html"> lib </a> </li> <li> <a href="package-modules.feeds.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.github.html"> github<span></span> </a> <ul> <li> <a href="package-modules.github.functions.html"> functions </a> </li> <li> <a href="package-modules.github.handler.html"> handler </a> </li> <li> <a href="package-modules.github.lib.html"> lib </a> </li> <li> <a href="package-modules.github.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.helloworld.html"> helloworld<span></span> </a> <ul> <li> <a href="package-modules.helloworld.handler.html"> handler </a> </li> <li> <a href="package-modules.helloworld.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.idletimer.html"> idletimer<span></span> </a> <ul> <li> <a href="package-modules.idletimer.handler.html"> handler </a> </li> <li> <a href="package-modules.idletimer.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.imap.html"> imap<span></span> </a> <ul> <li> <a href="package-modules.imap.functions.html"> functions </a> </li> <li> <a href="package-modules.imap.handler.html"> handler </a> </li> <li> <a href="package-modules.imap.lib.html"> lib </a> </li> <li> <a href="package-modules.imap.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.nux.html"> nux<span></span> </a> <ul> <li> <a href="package-modules.nux.functions.html"> functions </a> </li> <li> <a href="package-modules.nux.handler.html"> handler </a> </li> <li> <a href="package-modules.nux.lib.html"> lib </a> </li> <li> <a href="package-modules.nux.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.pop3.html"> pop3<span></span> </a> <ul> <li> <a href="package-modules.pop3.functions.html"> functions </a> </li> <li> <a href="package-modules.pop3.handler.html"> handler </a> </li> <li> <a href="package-modules.pop3.lib.html"> lib </a> </li> <li> <a href="package-modules.pop3.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.profile.html"> profile<span></span> </a> <ul> <li> <a href="package-modules.profile.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.smtp.html"> smtp<span></span> </a> <ul> <li> <a href="package-modules.smtp.functions.html"> functions </a> </li> <li> <a href="package-modules.smtp.handler.html"> handler </a> </li> <li> <a href="package-modules.smtp.lib.html"> lib </a> </li> <li> <a href="package-modules.smtp.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.swipe2fa.html"> swipe2fa<span></span> </a> <ul> <li> <a href="package-modules.swipe2fa.functions.html"> functions </a> </li> <li> <a href="package-modules.swipe2fa.handler.html"> handler </a> </li> <li> <a href="package-modules.swipe2fa.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.themes.html"> themes<span></span> </a> <ul> <li> <a href="package-modules.themes.functions.html"> functions </a> </li> <li> <a href="package-modules.themes.handler.html"> handler </a> </li> <li> <a href="package-modules.themes.output.html"> output </a> </li> </ul></li> <li> <a href="package-modules.wordpress.html"> wordpress<span></span> </a> <ul> <li> <a href="package-modules.wordpress.functions.html"> functions </a> </li> <li> <a href="package-modules.wordpress.handler.html"> handler </a> </li> <li> <a href="package-modules.wordpress.output.html"> output </a> </li> </ul></li></ul></li> </ul> </div> <hr> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-Hm_Auth.html">Hm_Auth</a></li> <li><a href="class-Hm_Auth_DB.html">Hm_Auth_DB</a></li> <li><a href="class-Hm_Auth_IMAP.html">Hm_Auth_IMAP</a></li> <li><a href="class-Hm_Auth_None.html">Hm_Auth_None</a></li> <li><a href="class-Hm_Auth_POP3.html">Hm_Auth_POP3</a></li> <li><a href="class-Hm_Cal_Data.html">Hm_Cal_Data</a></li> <li><a href="class-Hm_Cal_Output.html">Hm_Cal_Output</a></li> <li><a href="class-Hm_Config.html">Hm_Config</a></li> <li><a href="class-Hm_Contact.html">Hm_Contact</a></li> <li><a href="class-Hm_Contact_Store.html">Hm_Contact_Store</a></li> <li><a href="class-Hm_Contact_Store_DB.html">Hm_Contact_Store_DB</a></li> <li><a href="class-Hm_Contact_Store_File.html">Hm_Contact_Store_File</a></li> <li><a href="class-Hm_Contact_Store_Test.html">Hm_Contact_Store_Test</a></li> <li><a href="class-Hm_Crypt.html">Hm_Crypt</a></li> <li><a href="class-Hm_DB.html">Hm_DB</a></li> <li><a href="class-Hm_DB_Session.html">Hm_DB_Session</a></li> <li><a href="class-Hm_Debug.html">Hm_Debug</a></li> <li><a href="class-Hm_Dispatch.html">Hm_Dispatch</a></li> <li><a href="class-Hm_Feed.html">Hm_Feed</a></li> <li><a href="class-Hm_Feed_List.html">Hm_Feed_List</a></li> <li><a href="class-Hm_Feed_Uid_Cache.html">Hm_Feed_Uid_Cache</a></li> <li><a href="class-HM_Format.html">HM_Format</a></li> <li><a href="class-Hm_Format_HTML5.html">Hm_Format_HTML5</a></li> <li><a href="class-Hm_Format_JSON.html">Hm_Format_JSON</a></li> <li><a href="class-Hm_Functions.html">Hm_Functions</a></li> <li><a href="class-Hm_Github_Uid_Cache.html">Hm_Github_Uid_Cache</a></li> <li><a href="class-Hm_Handler_add_feeds_to_page_data.html">Hm_Handler_add_feeds_to_page_data</a></li> <li><a href="class-Hm_Handler_add_imap_servers_to_page_data.html">Hm_Handler_add_imap_servers_to_page_data</a></li> <li><a href="class-Hm_Handler_add_pop3_servers_to_page_data.html">Hm_Handler_add_pop3_servers_to_page_data</a></li> <li><a href="class-Hm_Handler_add_smtp_servers_to_page_data.html">Hm_Handler_add_smtp_servers_to_page_data</a></li> <li><a href="class-Hm_Handler_check_internal_users.html">Hm_Handler_check_internal_users</a></li> <li><a href="class-Hm_Handler_close_session_early.html">Hm_Handler_close_session_early</a></li> <li><a href="class-Hm_Handler_date.html">Hm_Handler_date</a></li> <li><a href="class-Hm_Handler_default_page_data.html">Hm_Handler_default_page_data</a></li> <li><a href="class-Hm_Handler_delete_feed.html">Hm_Handler_delete_feed</a></li> <li><a href="class-Hm_Handler_feed_connect.html">Hm_Handler_feed_connect</a></li> <li><a href="class-Hm_Handler_feed_item_content.html">Hm_Handler_feed_item_content</a></li> <li><a href="class-Hm_Handler_feed_list_content.html">Hm_Handler_feed_list_content</a></li> <li><a href="class-Hm_Handler_feed_list_type.html">Hm_Handler_feed_list_type</a></li> <li><a href="class-Hm_Handler_feed_message_action.html">Hm_Handler_feed_message_action</a></li> <li><a href="class-Hm_Handler_feed_status.html">Hm_Handler_feed_status</a></li> <li><a href="class-Hm_Handler_flag_imap_message.html">Hm_Handler_flag_imap_message</a></li> <li><a href="class-Hm_Handler_get_calendar_date.html">Hm_Handler_get_calendar_date</a></li> <li><a href="class-Hm_Handler_get_wp_notice_data.html">Hm_Handler_get_wp_notice_data</a></li> <li><a href="class-Hm_Handler_github_disconnect.html">Hm_Handler_github_disconnect</a></li> <li><a href="class-Hm_Handler_github_event_detail.html">Hm_Handler_github_event_detail</a></li> <li><a href="class-Hm_Handler_github_folders_data.html">Hm_Handler_github_folders_data</a></li> <li><a href="class-Hm_Handler_github_list_data.html">Hm_Handler_github_list_data</a></li> <li><a href="class-Hm_Handler_github_list_type.html">Hm_Handler_github_list_type</a></li> <li><a href="class-Hm_Handler_github_message_action.html">Hm_Handler_github_message_action</a></li> <li><a href="class-Hm_Handler_github_process_add_repo.html">Hm_Handler_github_process_add_repo</a></li> <li><a href="class-Hm_Handler_github_process_remove_repo.html">Hm_Handler_github_process_remove_repo</a></li> <li><a href="class-Hm_Handler_github_status.html">Hm_Handler_github_status</a></li> <li><a href="class-Hm_Handler_hello_world_page_handler.html">Hm_Handler_hello_world_page_handler</a></li> <li><a href="class-Hm_Handler_http_headers.html">Hm_Handler_http_headers</a></li> <li><a href="class-Hm_Handler_imap_bust_cache.html">Hm_Handler_imap_bust_cache</a></li> <li><a href="class-Hm_Handler_imap_combined_inbox.html">Hm_Handler_imap_combined_inbox</a></li> <li><a href="class-Hm_Handler_imap_connect.html">Hm_Handler_imap_connect</a></li> <li><a href="class-Hm_Handler_imap_delete.html">Hm_Handler_imap_delete</a></li> <li><a href="class-Hm_Handler_imap_download_message.html">Hm_Handler_imap_download_message</a></li> <li><a href="class-Hm_Handler_imap_flagged.html">Hm_Handler_imap_flagged</a></li> <li><a href="class-Hm_Handler_imap_folder_expand.html">Hm_Handler_imap_folder_expand</a></li> <li><a href="class-Hm_Handler_imap_folder_page.html">Hm_Handler_imap_folder_page</a></li> <li><a href="class-Hm_Handler_imap_forget.html">Hm_Handler_imap_forget</a></li> <li><a href="class-Hm_Handler_imap_hide.html">Hm_Handler_imap_hide</a></li> <li><a href="class-Hm_Handler_imap_message_action.html">Hm_Handler_imap_message_action</a></li> <li><a href="class-Hm_Handler_imap_message_content.html">Hm_Handler_imap_message_content</a></li> <li><a href="class-Hm_Handler_imap_message_list_type.html">Hm_Handler_imap_message_list_type</a></li> <li><a href="class-Hm_Handler_imap_oauth2_token_check.html">Hm_Handler_imap_oauth2_token_check</a></li> <li><a href="class-Hm_Handler_imap_save.html">Hm_Handler_imap_save</a></li> <li><a href="class-Hm_Handler_imap_search.html">Hm_Handler_imap_search</a></li> <li><a href="class-Hm_Handler_imap_status.html">Hm_Handler_imap_status</a></li> <li><a href="class-Hm_Handler_imap_unread.html">Hm_Handler_imap_unread</a></li> <li><a href="class-Hm_Handler_language.html">Hm_Handler_language</a></li> <li><a href="class-Hm_Handler_load_feed_folders.html">Hm_Handler_load_feed_folders</a></li> <li><a href="class-Hm_Handler_load_feeds_for_message_list.html">Hm_Handler_load_feeds_for_message_list</a></li> <li><a href="class-Hm_Handler_load_feeds_for_search.html">Hm_Handler_load_feeds_for_search</a></li> <li><a href="class-Hm_Handler_load_feeds_from_config.html">Hm_Handler_load_feeds_from_config</a></li> <li><a href="class-Hm_Handler_load_github_repos.html">Hm_Handler_load_github_repos</a></li> <li><a href="class-Hm_Handler_load_imap_folders.html">Hm_Handler_load_imap_folders</a></li> <li><a href="class-Hm_Handler_load_imap_servers_for_message_list.html">Hm_Handler_load_imap_servers_for_message_list</a></li> <li><a href="class-Hm_Handler_load_imap_servers_for_search.html">Hm_Handler_load_imap_servers_for_search</a></li> <li><a href="class-Hm_Handler_load_imap_servers_from_config.html">Hm_Handler_load_imap_servers_from_config</a></li> <li><a href="class-Hm_Handler_load_pop3_cache.html">Hm_Handler_load_pop3_cache</a></li> <li><a href="class-Hm_Handler_load_pop3_folders.html">Hm_Handler_load_pop3_folders</a></li> <li><a href="class-Hm_Handler_load_pop3_servers_for_message_list.html">Hm_Handler_load_pop3_servers_for_message_list</a></li> <li><a href="class-Hm_Handler_load_pop3_servers_for_search.html">Hm_Handler_load_pop3_servers_for_search</a></li> <li><a href="class-Hm_Handler_load_pop3_servers_from_config.html">Hm_Handler_load_pop3_servers_from_config</a></li> <li><a href="class-Hm_Handler_load_smtp_servers_from_config.html">Hm_Handler_load_smtp_servers_from_config</a></li> <li><a href="class-Hm_Handler_load_theme.html">Hm_Handler_load_theme</a></li> <li><a href="class-Hm_Handler_load_user_data.html">Hm_Handler_load_user_data</a></li> <li><a href="class-Hm_Handler_login.html">Hm_Handler_login</a></li> <li><a href="class-Hm_Handler_logout.html">Hm_Handler_logout</a></li> <li><a href="class-Hm_Handler_message_list_type.html">Hm_Handler_message_list_type</a></li> <li><a href="class-Hm_Handler_Module.html">Hm_Handler_Module</a></li> <li><a href="class-Hm_Handler_Modules.html">Hm_Handler_Modules</a></li> <li><a href="class-Hm_Handler_nux_dev_news.html">Hm_Handler_nux_dev_news</a></li> <li><a href="class-Hm_Handler_nux_homepage_data.html">Hm_Handler_nux_homepage_data</a></li> <li><a href="class-Hm_Handler_pop3_connect.html">Hm_Handler_pop3_connect</a></li> <li><a href="class-Hm_Handler_pop3_delete.html">Hm_Handler_pop3_delete</a></li> <li><a href="class-Hm_Handler_pop3_folder_page.html">Hm_Handler_pop3_folder_page</a></li> <li><a href="class-Hm_Handler_pop3_forget.html">Hm_Handler_pop3_forget</a></li> <li><a href="class-Hm_Handler_pop3_message_action.html">Hm_Handler_pop3_message_action</a></li> <li><a href="class-Hm_Handler_pop3_message_content.html">Hm_Handler_pop3_message_content</a></li> <li><a href="class-Hm_Handler_pop3_message_list_type.html">Hm_Handler_pop3_message_list_type</a></li> <li><a href="class-Hm_Handler_pop3_save.html">Hm_Handler_pop3_save</a></li> <li><a href="class-Hm_Handler_pop3_status.html">Hm_Handler_pop3_status</a></li> <li><a href="class-Hm_Handler_process_add_contact.html">Hm_Handler_process_add_contact</a></li> <li><a href="class-Hm_Handler_process_add_feed.html">Hm_Handler_process_add_feed</a></li> <li><a href="class-Hm_Handler_process_add_imap_server.html">Hm_Handler_process_add_imap_server</a></li> <li><a href="class-Hm_Handler_process_add_pop3_server.html">Hm_Handler_process_add_pop3_server</a></li> <li><a href="class-Hm_Handler_process_add_smtp_server.html">Hm_Handler_process_add_smtp_server</a></li> <li><a href="class-Hm_Handler_process_all_email_since_setting.html">Hm_Handler_process_all_email_since_setting</a></li> <li><a href="class-Hm_Handler_process_all_email_source_max_setting.html">Hm_Handler_process_all_email_source_max_setting</a></li> <li><a href="class-Hm_Handler_process_all_since_setting.html">Hm_Handler_process_all_since_setting</a></li> <li><a href="class-Hm_Handler_process_all_source_max_setting.html">Hm_Handler_process_all_source_max_setting</a></li> <li><a href="class-Hm_Handler_process_change_password.html">Hm_Handler_process_change_password</a></li> <li><a href="class-Hm_Handler_process_compose_form_submit.html">Hm_Handler_process_compose_form_submit</a></li> <li><a href="class-Hm_Handler_process_compose_type.html">Hm_Handler_process_compose_type</a></li> <li><a href="class-Hm_Handler_process_create_account.html">Hm_Handler_process_create_account</a></li> <li><a href="class-Hm_Handler_process_feed_limit_setting.html">Hm_Handler_process_feed_limit_setting</a></li> <li><a href="class-Hm_Handler_process_feed_since_setting.html">Hm_Handler_process_feed_since_setting</a></li> <li><a href="class-Hm_Handler_process_flagged_since_setting.html">Hm_Handler_process_flagged_since_setting</a></li> <li><a href="class-Hm_Handler_process_flagged_source_max_setting.html">Hm_Handler_process_flagged_source_max_setting</a></li> <li><a href="class-Hm_Handler_process_github_authorization.html">Hm_Handler_process_github_authorization</a></li> <li><a href="class-Hm_Handler_process_idle_time.html">Hm_Handler_process_idle_time</a></li> <li><a href="class-Hm_Handler_process_idle_time_setting.html">Hm_Handler_process_idle_time_setting</a></li> <li><a href="class-Hm_Handler_process_imap_source_update.html">Hm_Handler_process_imap_source_update</a></li> <li><a href="class-Hm_Handler_process_language_setting.html">Hm_Handler_process_language_setting</a></li> <li><a href="class-Hm_Handler_process_list_style_setting.html">Hm_Handler_process_list_style_setting</a></li> <li><a href="class-Hm_Handler_process_nux_add_service.html">Hm_Handler_process_nux_add_service</a></li> <li><a href="class-Hm_Handler_process_nux_service.html">Hm_Handler_process_nux_service</a></li> <li><a href="class-Hm_Handler_process_oauth2_authorization.html">Hm_Handler_process_oauth2_authorization</a></li> <li><a href="class-Hm_Handler_process_pop3_limit_setting.html">Hm_Handler_process_pop3_limit_setting</a></li> <li><a href="class-Hm_Handler_process_pop3_since_setting.html">Hm_Handler_process_pop3_since_setting</a></li> <li><a href="class-Hm_Handler_process_save_form.html">Hm_Handler_process_save_form</a></li> <li><a href="class-Hm_Handler_process_search_terms.html">Hm_Handler_process_search_terms</a></li> <li><a href="class-Hm_Handler_process_server_info.html">Hm_Handler_process_server_info</a></li> <li><a href="class-Hm_Handler_process_theme_setting.html">Hm_Handler_process_theme_setting</a></li> <li><a href="class-Hm_Handler_process_timezone_setting.html">Hm_Handler_process_timezone_setting</a></li> <li><a href="class-Hm_Handler_process_unread_feeds_setting.html">Hm_Handler_process_unread_feeds_setting</a></li> <li><a href="class-Hm_Handler_process_unread_since_setting.html">Hm_Handler_process_unread_since_setting</a></li> <li><a href="class-Hm_Handler_process_unread_source_max_setting.html">Hm_Handler_process_unread_source_max_setting</a></li> <li><a href="class-Hm_Handler_process_wordpress_authorization.html">Hm_Handler_process_wordpress_authorization</a></li> <li><a href="class-Hm_Handler_reload_folder_cookie.html">Hm_Handler_reload_folder_cookie</a></li> <li><a href="class-Hm_Handler_save_feeds.html">Hm_Handler_save_feeds</a></li> <li><a href="class-Hm_Handler_save_imap_cache.html">Hm_Handler_save_imap_cache</a></li> <li><a href="class-Hm_Handler_save_imap_servers.html">Hm_Handler_save_imap_servers</a></li> <li><a href="class-Hm_Handler_save_pop3_cache.html">Hm_Handler_save_pop3_cache</a></li> <li><a href="class-Hm_Handler_save_pop3_servers.html">Hm_Handler_save_pop3_servers</a></li> <li><a href="class-Hm_Handler_save_smtp_servers.html">Hm_Handler_save_smtp_servers</a></li> <li><a href="class-Hm_Handler_save_user_data.html">Hm_Handler_save_user_data</a></li> <li><a href="class-Hm_Handler_save_user_settings.html">Hm_Handler_save_user_settings</a></li> <li><a href="class-Hm_Handler_setup_github_connect.html">Hm_Handler_setup_github_connect</a></li> <li><a href="class-Hm_Handler_setup_nux.html">Hm_Handler_setup_nux</a></li> <li><a href="class-Hm_Handler_setup_wordpress_connect.html">Hm_Handler_setup_wordpress_connect</a></li> <li><a href="class-Hm_Handler_smtp_connect.html">Hm_Handler_smtp_connect</a></li> <li><a href="class-Hm_Handler_smtp_default_server.html">Hm_Handler_smtp_default_server</a></li> <li><a href="class-Hm_Handler_smtp_delete.html">Hm_Handler_smtp_delete</a></li> <li><a href="class-Hm_Handler_smtp_forget.html">Hm_Handler_smtp_forget</a></li> <li><a href="class-Hm_Handler_smtp_save.html">Hm_Handler_smtp_save</a></li> <li><a href="class-Hm_Handler_smtp_save_draft.html">Hm_Handler_smtp_save_draft</a></li> <li><a href="class-Hm_Handler_swipe_2fa_check.html">Hm_Handler_swipe_2fa_check</a></li> <li><a href="class-Hm_Handler_title.html">Hm_Handler_title</a></li> <li><a href="class-Hm_Handler_wordpress_disconnect.html">Hm_Handler_wordpress_disconnect</a></li> <li><a href="class-Hm_Handler_wordpress_folders_data.html">Hm_Handler_wordpress_folders_data</a></li> <li><a href="class-Hm_Handler_wordpress_list_type.html">Hm_Handler_wordpress_list_type</a></li> <li><a href="class-Hm_Handler_wordpress_msg_action.html">Hm_Handler_wordpress_msg_action</a></li> <li><a href="class-Hm_Handler_wp_freshly_pressed_data.html">Hm_Handler_wp_freshly_pressed_data</a></li> <li><a href="class-Hm_Handler_wp_load_sources.html">Hm_Handler_wp_load_sources</a></li> <li><a href="class-Hm_Handler_wp_notification_data.html">Hm_Handler_wp_notification_data</a></li> <li><a href="class-Hm_Image_Sources.html">Hm_Image_Sources</a></li> <li><a href="class-Hm_IMAP.html">Hm_IMAP</a></li> <li><a href="class-Hm_IMAP_Base.html">Hm_IMAP_Base</a></li> <li><a href="class-Hm_IMAP_Cache.html">Hm_IMAP_Cache</a></li> <li><a href="class-Hm_IMAP_List.html">Hm_IMAP_List</a></li> <li><a href="class-Hm_IMAP_Parser.html">Hm_IMAP_Parser</a></li> <li><a href="class-Hm_IMAP_Struct.html">Hm_IMAP_Struct</a></li> <li><a href="class-Hm_MIME_Msg.html">Hm_MIME_Msg</a></li> <li><a href="class-Hm_Module_Exec.html">Hm_Module_Exec</a></li> <li><a href="class-Hm_Msgs.html">Hm_Msgs</a></li> <li><a href="class-Hm_Oauth2.html">Hm_Oauth2</a></li> <li><a href="class-Hm_Output.html">Hm_Output</a></li> <li><a href="class-Hm_Output_add_feed_dialog.html">Hm_Output_add_feed_dialog</a></li> <li><a href="class-Hm_Output_add_imap_server_dialog.html">Hm_Output_add_imap_server_dialog</a></li> <li><a href="class-Hm_Output_add_pop3_server_dialog.html">Hm_Output_add_pop3_server_dialog</a></li> <li><a href="class-Hm_Output_add_smtp_server_dialog.html">Hm_Output_add_smtp_server_dialog</a></li> <li><a href="class-Hm_Output_all_email_since_setting.html">Hm_Output_all_email_since_setting</a></li> <li><a href="class-Hm_Output_all_email_source_max_setting.html">Hm_Output_all_email_source_max_setting</a></li> <li><a href="class-Hm_Output_all_since_setting.html">Hm_Output_all_since_setting</a></li> <li><a href="class-Hm_Output_all_source_max_setting.html">Hm_Output_all_source_max_setting</a></li> <li><a href="class-Hm_Output_calendar_content.html">Hm_Output_calendar_content</a></li> <li><a href="class-Hm_Output_calendar_page_link.html">Hm_Output_calendar_page_link</a></li> <li><a href="class-Hm_Output_change_password.html">Hm_Output_change_password</a></li> <li><a href="class-Hm_Output_change_password_link.html">Hm_Output_change_password_link</a></li> <li><a href="class-Hm_Output_compose_form.html">Hm_Output_compose_form</a></li> <li><a href="class-Hm_Output_compose_page_link.html">Hm_Output_compose_page_link</a></li> <li><a href="class-Hm_Output_compose_type_setting.html">Hm_Output_compose_type_setting</a></li> <li><a href="class-Hm_Output_config_map.html">Hm_Output_config_map</a></li> <li><a href="class-Hm_Output_contacts_content_add_form.html">Hm_Output_contacts_content_add_form</a></li> <li><a href="class-Hm_Output_contacts_content_end.html">Hm_Output_contacts_content_end</a></li> <li><a href="class-Hm_Output_contacts_content_start.html">Hm_Output_contacts_content_start</a></li> <li><a href="class-Hm_Output_contacts_page_link.html">Hm_Output_contacts_page_link</a></li> <li><a href="class-Hm_Output_content_end.html">Hm_Output_content_end</a></li> <li><a href="class-Hm_Output_content_section_end.html">Hm_Output_content_section_end</a></li> <li><a href="class-Hm_Output_content_section_start.html">Hm_Output_content_section_start</a></li> <li><a href="class-Hm_Output_content_start.html">Hm_Output_content_start</a></li> <li><a href="class-Hm_Output_create_account_link.html">Hm_Output_create_account_link</a></li> <li><a href="class-Hm_Output_create_form.html">Hm_Output_create_form</a></li> <li><a href="class-Hm_Output_date.html">Hm_Output_date</a></li> <li><a href="class-Hm_Output_dev_content.html">Hm_Output_dev_content</a></li> <li><a href="class-Hm_Output_developer_doc_link.html">Hm_Output_developer_doc_link</a></li> <li><a href="class-Hm_Output_display_configured_feeds.html">Hm_Output_display_configured_feeds</a></li> <li><a href="class-Hm_Output_display_configured_imap_servers.html">Hm_Output_display_configured_imap_servers</a></li> <li><a href="class-Hm_Output_display_configured_pop3_servers.html">Hm_Output_display_configured_pop3_servers</a></li> <li><a href="class-Hm_Output_display_configured_smtp_servers.html">Hm_Output_display_configured_smtp_servers</a></li> <li><a href="class-Hm_Output_display_feeds_status.html">Hm_Output_display_feeds_status</a></li> <li><a href="class-Hm_Output_display_github_status.html">Hm_Output_display_github_status</a></li> <li><a href="class-Hm_Output_display_imap_status.html">Hm_Output_display_imap_status</a></li> <li><a href="class-Hm_Output_display_pop3_status.html">Hm_Output_display_pop3_status</a></li> <li><a href="class-Hm_Output_email_menu_content.html">Hm_Output_email_menu_content</a></li> <li><a href="class-Hm_Output_end_settings_form.html">Hm_Output_end_settings_form</a></li> <li><a href="class-Hm_Output_feed_ids.html">Hm_Output_feed_ids</a></li> <li><a href="class-Hm_Output_feed_limit_setting.html">Hm_Output_feed_limit_setting</a></li> <li><a href="class-Hm_Output_feed_since_setting.html">Hm_Output_feed_since_setting</a></li> <li><a href="class-Hm_Output_filter_all_email.html">Hm_Output_filter_all_email</a></li> <li><a href="class-Hm_Output_filter_combined_inbox.html">Hm_Output_filter_combined_inbox</a></li> <li><a href="class-Hm_Output_filter_expanded_folder_data.html">Hm_Output_filter_expanded_folder_data</a></li> <li><a href="class-Hm_Output_filter_feed_folders.html">Hm_Output_filter_feed_folders</a></li> <li><a href="class-Hm_Output_filter_feed_item_content.html">Hm_Output_filter_feed_item_content</a></li> <li><a href="class-Hm_Output_filter_feed_list_data.html">Hm_Output_filter_feed_list_data</a></li> <li><a href="class-Hm_Output_filter_feed_status_data.html">Hm_Output_filter_feed_status_data</a></li> <li><a href="class-Hm_Output_filter_flagged_data.html">Hm_Output_filter_flagged_data</a></li> <li><a href="class-Hm_Output_filter_folder_page.html">Hm_Output_filter_folder_page</a></li> <li><a href="class-Hm_Output_filter_github_data.html">Hm_Output_filter_github_data</a></li> <li><a href="class-Hm_Output_filter_github_event_detail.html">Hm_Output_filter_github_event_detail</a></li> <li><a href="class-Hm_Output_filter_github_status.html">Hm_Output_filter_github_status</a></li> <li><a href="class-Hm_Output_filter_imap_folders.html">Hm_Output_filter_imap_folders</a></li> <li><a href="class-Hm_Output_filter_imap_search.html">Hm_Output_filter_imap_search</a></li> <li><a href="class-Hm_Output_filter_imap_status_data.html">Hm_Output_filter_imap_status_data</a></li> <li><a href="class-Hm_Output_filter_message_body.html">Hm_Output_filter_message_body</a></li> <li><a href="class-Hm_Output_filter_message_headers.html">Hm_Output_filter_message_headers</a></li> <li><a href="class-Hm_Output_filter_message_struct.html">Hm_Output_filter_message_struct</a></li> <li><a href="class-Hm_Output_filter_pop3_folders.html">Hm_Output_filter_pop3_folders</a></li> <li><a href="class-Hm_Output_filter_pop3_message_content.html">Hm_Output_filter_pop3_message_content</a></li> <li><a href="class-Hm_Output_filter_pop3_message_list.html">Hm_Output_filter_pop3_message_list</a></li> <li><a href="class-Hm_Output_filter_pop3_status_data.html">Hm_Output_filter_pop3_status_data</a></li> <li><a href="class-Hm_Output_filter_service_select.html">Hm_Output_filter_service_select</a></li> <li><a href="class-Hm_Output_filter_unread_data.html">Hm_Output_filter_unread_data</a></li> <li><a href="class-Hm_Output_filter_wp_freshly_pressed_data.html">Hm_Output_filter_wp_freshly_pressed_data</a></li> <li><a href="class-Hm_Output_filter_wp_notice_data.html">Hm_Output_filter_wp_notice_data</a></li> <li><a href="class-Hm_Output_filter_wp_notification_data.html">Hm_Output_filter_wp_notification_data</a></li> <li><a href="class-Hm_Output_flagged_since_setting.html">Hm_Output_flagged_since_setting</a></li> <li><a href="class-Hm_Output_flagged_source_max_setting.html">Hm_Output_flagged_source_max_setting</a></li> <li><a href="class-Hm_Output_folder_list_content_end.html">Hm_Output_folder_list_content_end</a></li> <li><a href="class-Hm_Output_folder_list_content_start.html">Hm_Output_folder_list_content_start</a></li> <li><a href="class-Hm_Output_folder_list_end.html">Hm_Output_folder_list_end</a></li> <li><a href="class-Hm_Output_folder_list_start.html">Hm_Output_folder_list_start</a></li> <li><a href="class-Hm_Output_github_add_repo.html">Hm_Output_github_add_repo</a></li> <li><a href="class-Hm_Output_github_connect_section.html">Hm_Output_github_connect_section</a></li> <li><a href="class-Hm_Output_github_folders.html">Hm_Output_github_folders</a></li> <li><a href="class-Hm_Output_header_content.html">Hm_Output_header_content</a></li> <li><a href="class-Hm_Output_header_css.html">Hm_Output_header_css</a></li> <li><a href="class-Hm_Output_header_end.html">Hm_Output_header_end</a></li> <li><a href="class-Hm_Output_header_start.html">Hm_Output_header_start</a></li> <li><a href="class-Hm_Output_hello_world_ajax_content.html">Hm_Output_hello_world_ajax_content</a></li> <li><a href="class-Hm_Output_hello_world_home_page.html">Hm_Output_hello_world_home_page</a></li> <li><a href="class-Hm_Output_hello_world_page_content.html">Hm_Output_hello_world_page_content</a></li> <li><a href="class-Hm_Output_home_heading.html">Hm_Output_home_heading</a></li> <li><a href="class-Hm_Output_HTTP.html">Hm_Output_HTTP</a></li> <li><a href="class-Hm_Output_idle_time_setting.html">Hm_Output_idle_time_setting</a></li> <li><a href="class-Hm_Output_imap_custom_controls.html">Hm_Output_imap_custom_controls</a></li> <li><a href="class-Hm_Output_imap_server_ids.html">Hm_Output_imap_server_ids</a></li> <li><a href="class-Hm_Output_info_heading.html">Hm_Output_info_heading</a></li> <li><a href="class-Hm_Output_info_page_link.html">Hm_Output_info_page_link</a></li> <li><a href="class-Hm_Output_js_data.html">Hm_Output_js_data</a></li> <li><a href="class-Hm_Output_js_search_data.html">Hm_Output_js_search_data</a></li> <li><a href="class-Hm_Output_language_setting.html">Hm_Output_language_setting</a></li> <li><a href="class-Hm_Output_list_style_setting.html">Hm_Output_list_style_setting</a></li> <li><a href="class-Hm_Output_loading_icon.html">Hm_Output_loading_icon</a></li> <li><a href="class-Hm_Output_login.html">Hm_Output_login</a></li> <li><a href="class-Hm_Output_logout_menu_item.html">Hm_Output_logout_menu_item</a></li> <li><a href="class-Hm_Output_main_menu_content.html">Hm_Output_main_menu_content</a></li> <li><a href="class-Hm_Output_main_menu_end.html">Hm_Output_main_menu_end</a></li> <li><a href="class-Hm_Output_main_menu_start.html">Hm_Output_main_menu_start</a></li> <li><a href="class-Hm_Output_message_end.html">Hm_Output_message_end</a></li> <li><a href="class-Hm_Output_message_list_end.html">Hm_Output_message_list_end</a></li> <li><a href="class-Hm_Output_message_list_heading.html">Hm_Output_message_list_heading</a></li> <li><a href="class-Hm_Output_message_list_start.html">Hm_Output_message_list_start</a></li> <li><a href="class-Hm_Output_message_start.html">Hm_Output_message_start</a></li> <li><a href="class-Hm_Output_Module.html">Hm_Output_Module</a></li> <li><a href="class-Hm_Output_Modules.html">Hm_Output_Modules</a></li> <li><a href="class-Hm_Output_msgs.html">Hm_Output_msgs</a></li> <li><a href="class-Hm_Output_notfound_content.html">Hm_Output_notfound_content</a></li> <li><a href="class-Hm_Output_nux_dev_news.html">Hm_Output_nux_dev_news</a></li> <li><a href="class-Hm_Output_nux_help.html">Hm_Output_nux_help</a></li> <li><a href="class-Hm_Output_page_js.html">Hm_Output_page_js</a></li> <li><a href="class-Hm_Output_pop3_limit_setting.html">Hm_Output_pop3_limit_setting</a></li> <li><a href="class-Hm_Output_pop3_server_ids.html">Hm_Output_pop3_server_ids</a></li> <li><a href="class-Hm_Output_pop3_since_setting.html">Hm_Output_pop3_since_setting</a></li> <li><a href="class-Hm_Output_profile_content.html">Hm_Output_profile_content</a></li> <li><a href="class-Hm_Output_profile_page_link.html">Hm_Output_profile_page_link</a></li> <li><a href="class-Hm_Output_quick_add_dialog.html">Hm_Output_quick_add_dialog</a></li> <li><a href="class-Hm_Output_quick_add_section.html">Hm_Output_quick_add_section</a></li> <li><a href="class-Hm_Output_save_form.html">Hm_Output_save_form</a></li> <li><a href="class-Hm_Output_save_reminder.html">Hm_Output_save_reminder</a></li> <li><a href="class-Hm_Output_search_content_end.html">Hm_Output_search_content_end</a></li> <li><a href="class-Hm_Output_search_content_start.html">Hm_Output_search_content_start</a></li> <li><a href="class-Hm_Output_search_form.html">Hm_Output_search_form</a></li> <li><a href="class-Hm_Output_search_from_folder_list.html">Hm_Output_search_from_folder_list</a></li> <li><a href="class-Hm_Output_search_results_table_end.html">Hm_Output_search_results_table_end</a></li> <li><a href="class-Hm_Output_server_content_end.html">Hm_Output_server_content_end</a></li> <li><a href="class-Hm_Output_server_content_start.html">Hm_Output_server_content_start</a></li> <li><a href="class-Hm_Output_server_information.html">Hm_Output_server_information</a></li> <li><a href="class-Hm_Output_server_status_end.html">Hm_Output_server_status_end</a></li> <li><a href="class-Hm_Output_server_status_start.html">Hm_Output_server_status_start</a></li> <li><a href="class-Hm_Output_settings_menu_content.html">Hm_Output_settings_menu_content</a></li> <li><a href="class-Hm_Output_settings_menu_end.html">Hm_Output_settings_menu_end</a></li> <li><a href="class-Hm_Output_settings_menu_start.html">Hm_Output_settings_menu_start</a></li> <li><a href="class-Hm_Output_start_all_email_settings.html">Hm_Output_start_all_email_settings</a></li> <li><a href="class-Hm_Output_start_everything_settings.html">Hm_Output_start_everything_settings</a></li> <li><a href="class-Hm_Output_start_feed_settings.html">Hm_Output_start_feed_settings</a></li> <li><a href="class-Hm_Output_start_flagged_settings.html">Hm_Output_start_flagged_settings</a></li> <li><a href="class-Hm_Output_start_general_settings.html">Hm_Output_start_general_settings</a></li> <li><a href="class-Hm_Output_start_pop3_settings.html">Hm_Output_start_pop3_settings</a></li> <li><a href="class-Hm_Output_start_settings_form.html">Hm_Output_start_settings_form</a></li> <li><a href="class-Hm_Output_start_unread_settings.html">Hm_Output_start_unread_settings</a></li> <li><a href="class-Hm_Output_swipe_2fa_dialog.html">Hm_Output_swipe_2fa_dialog</a></li> <li><a href="class-Hm_Output_theme_css.html">Hm_Output_theme_css</a></li> <li><a href="class-Hm_Output_theme_setting.html">Hm_Output_theme_setting</a></li> <li><a href="class-Hm_Output_timezone_setting.html">Hm_Output_timezone_setting</a></li> <li><a href="class-Hm_Output_unread_feeds_included.html">Hm_Output_unread_feeds_included</a></li> <li><a href="class-Hm_Output_unread_since_setting.html">Hm_Output_unread_since_setting</a></li> <li><a href="class-Hm_Output_unread_source_max_setting.html">Hm_Output_unread_source_max_setting</a></li> <li><a href="class-Hm_Output_welcome_dialog.html">Hm_Output_welcome_dialog</a></li> <li><a href="class-Hm_Output_wordpress_connect_section.html">Hm_Output_wordpress_connect_section</a></li> <li><a href="class-Hm_Output_wordpress_folders.html">Hm_Output_wordpress_folders</a></li> <li><a href="class-Hm_Page_Cache.html">Hm_Page_Cache</a></li> <li><a href="class-Hm_PHP_Session.html">Hm_PHP_Session</a></li> <li><a href="class-Hm_POP3.html">Hm_POP3</a></li> <li><a href="class-Hm_POP3_Base.html">Hm_POP3_Base</a></li> <li><a href="class-Hm_POP3_List.html">Hm_POP3_List</a></li> <li><a href="class-Hm_POP3_Uid_Cache.html">Hm_POP3_Uid_Cache</a></li> <li><a href="class-Hm_Request.html">Hm_Request</a></li> <li><a href="class-Hm_Request_Key.html">Hm_Request_Key</a></li> <li><a href="class-Hm_Session.html">Hm_Session</a></li> <li><a href="class-Hm_Site_Config_File.html">Hm_Site_Config_File</a></li> <li><a href="class-Hm_SMTP.html">Hm_SMTP</a></li> <li><a href="class-Hm_SMTP_List.html">Hm_SMTP_List</a></li> <li><a href="class-Hm_User_Config_DB.html">Hm_User_Config_DB</a></li> <li><a href="class-Hm_User_Config_File.html">Hm_User_Config_File</a></li> <li><a href="class-Nux_Quick_Services.html">Nux_Quick_Services</a></li> </ul> <h3>Traits</h3> <ul> <li><a href="class-Hm_Handler_Module_Exec.html">Hm_Handler_Module_Exec</a></li> <li><a href="class-Hm_List.html">Hm_List</a></li> <li><a href="class-Hm_Module_Output.html">Hm_Module_Output</a></li> <li><a href="class-Hm_Modules.html">Hm_Modules</a></li> <li><a href="class-Hm_Output_Module_Exec.html">Hm_Output_Module_Exec</a></li> <li><a href="class-Hm_Server_List.html">Hm_Server_List</a></li> <li><a href="class-Hm_Session_Fingerprint.html">Hm_Session_Fingerprint</a></li> <li><a href="class-Hm_Uid_Cache.html">Hm_Uid_Cache</a></li> </ul> <h3>Functions</h3> <ul> <li><a href="function-add_attached_images.html">add_attached_images</a></li> <li><a href="function-add_handler.html">add_handler</a></li> <li><a href="function-add_module_to_all_pages.html">add_module_to_all_pages</a></li> <li><a href="function-add_output.html">add_output</a></li> <li><a href="function-address_from_url.html">address_from_url</a></li> <li><a href="function-build_github_subject.html">build_github_subject</a></li> <li><a href="function-build_mime_msg.html">build_mime_msg</a></li> <li><a href="function-build_page_links.html">build_page_links</a></li> <li><a href="function-checkbox_callback.html">checkbox_callback</a></li> <li><a href="function-convert_html_to_text.html">convert_html_to_text</a></li> <li><a href="function-credentials_form.html">credentials_form</a></li> <li><a href="function-data_source_available.html">data_source_available</a></li> <li><a href="function-date_callback.html">date_callback</a></li> <li><a href="function-display_value.html">display_value</a></li> <li><a href="function-elog.html">elog</a></li> <li><a href="function-email_is_active.html">email_is_active</a></li> <li><a href="function-format_data_sources.html">format_data_sources</a></li> <li><a href="function-format_imap_folder_section.html">format_imap_folder_section</a></li> <li><a href="function-format_imap_message_list.html">format_imap_message_list</a></li> <li><a href="function-format_msg_html.html">format_msg_html</a></li> <li><a href="function-format_msg_image.html">format_msg_image</a></li> <li><a href="function-format_msg_part_row.html">format_msg_part_row</a></li> <li><a href="function-format_msg_part_section.html">format_msg_part_section</a></li> <li><a href="function-format_msg_text.html">format_msg_text</a></li> <li><a href="function-format_pop3_message_list.html">format_pop3_message_list</a></li> <li><a href="function-format_reply_as_html.html">format_reply_as_html</a></li> <li><a href="function-format_reply_as_text.html">format_reply_as_text</a></li> <li><a href="function-format_reply_fields.html">format_reply_fields</a></li> <li><a href="function-format_reply_text.html">format_reply_text</a></li> <li><a href="function-get_imap_part_name.html">get_imap_part_name</a></li> <li><a href="function-get_message_list_settings.html">get_message_list_settings</a></li> <li><a href="function-get_oauth2_data.html">get_oauth2_data</a></li> <li><a href="function-get_secondfactor_state.html">get_secondfactor_state</a></li> <li><a href="function-github_connect_details.html">github_connect_details</a></li> <li><a href="function-github_fetch_content.html">github_fetch_content</a></li> <li><a href="function-github_parse_headers.html">github_parse_headers</a></li> <li><a href="function-github_parse_payload.html">github_parse_payload</a></li> <li><a href="function-group_data_sources.html">group_data_sources</a></li> <li><a href="function-handler_source.html">handler_source</a></li> <li><a href="function-hm_theme_white_icons.html">hm_theme_white_icons</a></li> <li><a href="function-hm_themes.html">hm_themes</a></li> <li><a href="function-human_readable_interval.html">human_readable_interval</a></li> <li><a href="function-icon_callback.html">icon_callback</a></li> <li><a href="function-imap_data_sources.html">imap_data_sources</a></li> <li><a href="function-imap_refresh_oauth2_token.html">imap_refresh_oauth2_token</a></li> <li><a href="function-interface_langs.html">interface_langs</a></li> <li><a href="function-is_email.html">is_email</a></li> <li><a href="function-is_feed.html">is_feed</a></li> <li><a href="function-list_controls.html">list_controls</a></li> <li><a href="function-list_sources.html">list_sources</a></li> <li><a href="function-load_user_config_object.html">load_user_config_object</a></li> <li><a href="function-max_source_setting_callback.html">max_source_setting_callback</a></li> <li><a href="function-merge_imap_search_results.html">merge_imap_search_results</a></li> <li><a href="function-message_controls.html">message_controls</a></li> <li><a href="function-message_list_meta.html">message_list_meta</a></li> <li><a href="function-message_list_row.html">message_list_row</a></li> <li><a href="function-message_since_dropdown.html">message_since_dropdown</a></li> <li><a href="function-oauth2_form.html">oauth2_form</a></li> <li><a href="function-output_source.html">output_source</a></li> <li><a href="function-payload_search.html">payload_search</a></li> <li><a href="function-prepare_imap_message_list.html">prepare_imap_message_list</a></li> <li><a href="function-process_imap_message_ids.html">process_imap_message_ids</a></li> <li><a href="function-process_since_argument.html">process_since_argument</a></li> <li><a href="function-process_site_setting.html">process_site_setting</a></li> <li><a href="function-replace_module.html">replace_module</a></li> <li><a href="function-reply_format_body.html">reply_format_body</a></li> <li><a href="function-reply_lead_in.html">reply_lead_in</a></li> <li><a href="function-reply_to_address.html">reply_to_address</a></li> <li><a href="function-reply_to_subject.html">reply_to_subject</a></li> <li><a href="function-safe_output_callback.html">safe_output_callback</a></li> <li><a href="function-save_user_settings.html">save_user_settings</a></li> <li><a href="function-search_feed_item.html">search_feed_item</a></li> <li><a href="function-search_field_selection.html">search_field_selection</a></li> <li><a href="function-search_for_feeds.html">search_for_feeds</a></li> <li><a href="function-search_pop3_msg.html">search_pop3_msg</a></li> <li><a href="function-setup_base_page.html">setup_base_page</a></li> <li><a href="function-setup_session.html">setup_session</a></li> <li><a href="function-setup_swipe_api.html">setup_swipe_api</a></li> <li><a href="function-since_setting_callback.html">since_setting_callback</a></li> <li><a href="function-smtp_refresh_oauth2_token.html">smtp_refresh_oauth2_token</a></li> <li><a href="function-smtp_server_dropdown.html">smtp_server_dropdown</a></li> <li><a href="function-sort_by_internal_date.html">sort_by_internal_date</a></li> <li><a href="function-start_api.html">start_api</a></li> <li><a href="function-subject_callback.html">subject_callback</a></li> <li><a href="function-translate_time_str.html">translate_time_str</a></li> <li><a href="function-validate_domain_full.html">validate_domain_full</a></li> <li><a href="function-validate_local_full.html">validate_local_full</a></li> <li><a href="function-validate_search_fld.html">validate_search_fld</a></li> <li><a href="function-validate_search_terms.html">validate_search_terms</a></li> <li><a href="function-wp_build_notice_headers.html">wp_build_notice_headers</a></li> <li><a href="function-wp_build_notice_text.html">wp_build_notice_text</a></li> <li><a href="function-wp_connect_details.html">wp_connect_details</a></li> <li><a href="function-wp_fetch_content.html">wp_fetch_content</a></li> <li><a href="function-wp_get_freshly_pressed.html">wp_get_freshly_pressed</a></li> <li><a href="function-wp_get_notice_detail.html">wp_get_notice_detail</a></li> <li><a href="function-wp_get_notifications.html">wp_get_notifications</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li> <span>Package</span> </li> <li> <span>Class</span> </li> </ul> <ul> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> <li> <a href="annotation-group-deprecated.html" title="List of elements with deprecated annotation"> <span>Deprecated</span> </a> </li> <li> <a href="annotation-group-todo.html" title="List of elements with todo annotation"> <span>Todo</span> </a> </li> </ul> <ul> <li> <a href="-API-documentation.zip" title="Download documentation as ZIP archive"><span>Download</span></a> </li> </ul> </div> <pre><code><span id="1" class="l"><a href="#1"> 1: </a><span class="xlang">&lt;?php</span> </span><span id="2" class="l"><a href="#2"> 2: </a> </span><span id="3" class="l"><a href="#3"> 3: </a><span class="php-comment">/** </span></span><span id="4" class="l"><a href="#4"> 4: </a><span class="php-comment"> * Account modules </span></span><span id="5" class="l"><a href="#5"> 5: </a><span class="php-comment"> * @package modules </span></span><span id="6" class="l"><a href="#6"> 6: </a><span class="php-comment"> * @subpackage account </span></span><span id="7" class="l"><a href="#7"> 7: </a><span class="php-comment"> */</span> </span><span id="8" class="l"><a href="#8"> 8: </a><span class="php-keyword1">if</span> (!<span class="php-keyword2">defined</span>(<span class="php-quote">'DEBUG_MODE'</span>)) { <span class="php-keyword1">die</span>(); } </span><span id="9" class="l"><a href="#9"> 9: </a> </span><span id="10" class="l"><a href="#10"> 10: </a><span class="php-comment">/** </span></span><span id="11" class="l"><a href="#11"> 11: </a><span class="php-comment"> * @subpackage account/handler </span></span><span id="12" class="l"><a href="#12"> 12: </a><span class="php-comment"> */</span> </span><span id="13" class="l"><a href="#13"> 13: </a><span class="php-keyword1">class</span> Hm_Handler_process_change_password <span class="php-keyword1">extends</span> Hm_Handler_Module { </span><span id="14" class="l"><a href="#14"> 14: </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> process() { </span><span id="15" class="l"><a href="#15"> 15: </a> <span class="php-keyword1">if</span> (!<span class="php-var">$this</span>-&gt;session-&gt;internal_users) { </span><span id="16" class="l"><a href="#16"> 16: </a> <span class="php-keyword1">return</span>; </span><span id="17" class="l"><a href="#17"> 17: </a> } </span><span id="18" class="l"><a href="#18"> 18: </a> </span><span id="19" class="l"><a href="#19"> 19: </a> <span class="php-keyword1">list</span>(<span class="php-var">$success</span>, <span class="php-var">$form</span>) = <span class="php-var">$this</span>-&gt;process_form(<span class="php-keyword1">array</span>(<span class="php-quote">'new_pass1'</span>, <span class="php-quote">'new_pass2'</span>, <span class="php-quote">'old_pass'</span>, <span class="php-quote">'change_password'</span>)); </span><span id="20" class="l"><a href="#20"> 20: </a> <span class="php-keyword1">if</span> (<span class="php-var">$success</span>) { </span><span id="21" class="l"><a href="#21"> 21: </a> <span class="php-keyword1">if</span> (<span class="php-var">$form</span>[<span class="php-quote">'new_pass1'</span>] !== <span class="php-var">$form</span>[<span class="php-quote">'new_pass2'</span>]) { </span><span id="22" class="l"><a href="#22"> 22: </a> Hm_Msgs::add(<span class="php-quote">&quot;ERRNew passwords don't not match&quot;</span>); </span><span id="23" class="l"><a href="#23"> 23: </a> <span class="php-keyword1">return</span>; </span><span id="24" class="l"><a href="#24"> 24: </a> } </span><span id="25" class="l"><a href="#25"> 25: </a> <span class="php-var">$user</span> = <span class="php-var">$this</span>-&gt;session-&gt;get(<span class="php-quote">'username'</span>, <span class="php-keyword1">false</span>); </span><span id="26" class="l"><a href="#26"> 26: </a> <span class="php-keyword1">if</span> (!<span class="php-var">$this</span>-&gt;session-&gt;auth(<span class="php-var">$user</span>, <span class="php-var">$form</span>[<span class="php-quote">'old_pass'</span>])) { </span><span id="27" class="l"><a href="#27"> 27: </a> Hm_Msgs::add(<span class="php-quote">&quot;ERRCurrent password is incorrect&quot;</span>); </span><span id="28" class="l"><a href="#28"> 28: </a> <span class="php-keyword1">return</span>; </span><span id="29" class="l"><a href="#29"> 29: </a> } </span><span id="30" class="l"><a href="#30"> 30: </a> <span class="php-var">$user_config</span> = load_user_config_object(<span class="php-var">$this</span>-&gt;config); </span><span id="31" class="l"><a href="#31"> 31: </a> <span class="php-keyword1">if</span> (!<span class="php-var">$this</span>-&gt;session-&gt;change_pass(<span class="php-var">$user</span>, <span class="php-var">$form</span>[<span class="php-quote">'new_pass1'</span>])) { </span><span id="32" class="l"><a href="#32"> 32: </a> Hm_Msgs::add(<span class="php-quote">&quot;ERRAn error Occurred&quot;</span>); </span><span id="33" class="l"><a href="#33"> 33: </a> } </span><span id="34" class="l"><a href="#34"> 34: </a> <span class="php-var">$user_config</span>-&gt;load(<span class="php-var">$user</span>, <span class="php-var">$form</span>[<span class="php-quote">'old_pass'</span>]); </span><span id="35" class="l"><a href="#35"> 35: </a> <span class="php-var">$user_config</span>-&gt;save(<span class="php-var">$user</span>, <span class="php-var">$form</span>[<span class="php-quote">'new_pass1'</span>]); </span><span id="36" class="l"><a href="#36"> 36: </a> } </span><span id="37" class="l"><a href="#37"> 37: </a> } </span><span id="38" class="l"><a href="#38"> 38: </a>} </span><span id="39" class="l"><a href="#39"> 39: </a> </span><span id="40" class="l"><a href="#40"> 40: </a><span class="php-comment">/** </span></span><span id="41" class="l"><a href="#41"> 41: </a><span class="php-comment"> * @subpackage account/handler </span></span><span id="42" class="l"><a href="#42"> 42: </a><span class="php-comment"> */</span> </span><span id="43" class="l"><a href="#43"> 43: </a><span class="php-keyword1">class</span> Hm_Handler_process_create_account <span class="php-keyword1">extends</span> Hm_Handler_Module { </span><span id="44" class="l"><a href="#44"> 44: </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> process() { </span><span id="45" class="l"><a href="#45"> 45: </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;session-&gt;is_admin()) { </span><span id="46" class="l"><a href="#46"> 46: </a> <span class="php-keyword1">list</span>(<span class="php-var">$success</span>, <span class="php-var">$form</span>) = <span class="php-var">$this</span>-&gt;process_form(<span class="php-keyword1">array</span>(<span class="php-quote">'create_username'</span>, <span class="php-quote">'create_password'</span>, <span class="php-quote">'create_password_again'</span>)); </span><span id="47" class="l"><a href="#47"> 47: </a> <span class="php-keyword1">if</span> (<span class="php-var">$success</span>) { </span><span id="48" class="l"><a href="#48"> 48: </a> <span class="php-keyword1">if</span> (<span class="php-var">$form</span>[<span class="php-quote">'create_password'</span>] == <span class="php-var">$form</span>[<span class="php-quote">'create_password_again'</span>]) { </span><span id="49" class="l"><a href="#49"> 49: </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;session-&gt;internal_users) { </span><span id="50" class="l"><a href="#50"> 50: </a> <span class="php-var">$this</span>-&gt;session-&gt;create(<span class="php-var">$this</span>-&gt;request, <span class="php-var">$form</span>[<span class="php-quote">'create_username'</span>], <span class="php-var">$form</span>[<span class="php-quote">'create_password'</span>]); </span><span id="51" class="l"><a href="#51"> 51: </a> } </span><span id="52" class="l"><a href="#52"> 52: </a> } </span><span id="53" class="l"><a href="#53"> 53: </a> <span class="php-keyword1">else</span> { </span><span id="54" class="l"><a href="#54"> 54: </a> Hm_Msgs::add(<span class="php-quote">'ERRPasswords did not match'</span>); </span><span id="55" class="l"><a href="#55"> 55: </a> } </span><span id="56" class="l"><a href="#56"> 56: </a> } </span><span id="57" class="l"><a href="#57"> 57: </a> } </span><span id="58" class="l"><a href="#58"> 58: </a> } </span><span id="59" class="l"><a href="#59"> 59: </a>} </span><span id="60" class="l"><a href="#60"> 60: </a> </span><span id="61" class="l"><a href="#61"> 61: </a><span class="php-comment">/** </span></span><span id="62" class="l"><a href="#62"> 62: </a><span class="php-comment"> * @subpackage account/handler </span></span><span id="63" class="l"><a href="#63"> 63: </a><span class="php-comment"> */</span> </span><span id="64" class="l"><a href="#64"> 64: </a><span class="php-keyword1">class</span> Hm_Handler_check_internal_users <span class="php-keyword1">extends</span> Hm_Handler_Module { </span><span id="65" class="l"><a href="#65"> 65: </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> process() { </span><span id="66" class="l"><a href="#66"> 66: </a> <span class="php-var">$this</span>-&gt;out(<span class="php-quote">'is_admin'</span>, <span class="php-var">$this</span>-&gt;session-&gt;is_admin()); </span><span id="67" class="l"><a href="#67"> 67: </a> <span class="php-var">$this</span>-&gt;out(<span class="php-quote">'internal_users'</span>, <span class="php-var">$this</span>-&gt;session-&gt;internal_users); </span><span id="68" class="l"><a href="#68"> 68: </a> } </span><span id="69" class="l"><a href="#69"> 69: </a>} </span><span id="70" class="l"><a href="#70"> 70: </a> </span><span id="71" class="l"><a href="#71"> 71: </a><span class="php-comment">/** </span></span><span id="72" class="l"><a href="#72"> 72: </a><span class="php-comment"> * @subpackage account/output </span></span><span id="73" class="l"><a href="#73"> 73: </a><span class="php-comment"> */</span> </span><span id="74" class="l"><a href="#74"> 74: </a><span class="php-keyword1">class</span> Hm_Output_create_account_link <span class="php-keyword1">extends</span> Hm_Output_Module { </span><span id="75" class="l"><a href="#75"> 75: </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> output() { </span><span id="76" class="l"><a href="#76"> 76: </a> <span class="php-keyword1">if</span> (!<span class="php-var">$this</span>-&gt;get(<span class="php-quote">'is_admin'</span>, <span class="php-keyword1">false</span>)) { </span><span id="77" class="l"><a href="#77"> 77: </a> <span class="php-var">$res</span> = <span class="php-quote">''</span>; </span><span id="78" class="l"><a href="#78"> 78: </a> } </span><span id="79" class="l"><a href="#79"> 79: </a> <span class="php-keyword1">else</span> { </span><span id="80" class="l"><a href="#80"> 80: </a> <span class="php-var">$res</span> = <span class="php-quote">'&lt;li class=&quot;menu_create_account&quot;&gt;&lt;a class=&quot;unread_link&quot; href=&quot;?page=create_account&quot;&gt;'</span>. </span><span id="81" class="l"><a href="#81"> 81: </a> <span class="php-quote">'&lt;img class=&quot;account_icon&quot; src=&quot;'</span>.<span class="php-var">$this</span>-&gt;html_safe(Hm_Image_Sources::<span class="php-var">$globe</span>).<span class="php-quote">'&quot; alt=&quot;&quot; '</span>. </span><span id="82" class="l"><a href="#82"> 82: </a> <span class="php-quote">'width=&quot;16&quot; height=&quot;16&quot; /&gt; '</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Accounts'</span>).<span class="php-quote">'&lt;/a&gt;&lt;/li&gt;'</span>; </span><span id="83" class="l"><a href="#83"> 83: </a> } </span><span id="84" class="l"><a href="#84"> 84: </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;format == <span class="php-quote">'HTML5'</span>) { </span><span id="85" class="l"><a href="#85"> 85: </a> <span class="php-keyword1">return</span> <span class="php-var">$res</span>; </span><span id="86" class="l"><a href="#86"> 86: </a> } </span><span id="87" class="l"><a href="#87"> 87: </a> <span class="php-var">$this</span>-&gt;concat(<span class="php-quote">'formatted_folder_list'</span>, <span class="php-var">$res</span>); </span><span id="88" class="l"><a href="#88"> 88: </a> } </span><span id="89" class="l"><a href="#89"> 89: </a>} </span><span id="90" class="l"><a href="#90"> 90: </a> </span><span id="91" class="l"><a href="#91"> 91: </a><span class="php-comment">/** </span></span><span id="92" class="l"><a href="#92"> 92: </a><span class="php-comment"> * @subpackage account/output </span></span><span id="93" class="l"><a href="#93"> 93: </a><span class="php-comment"> */</span> </span><span id="94" class="l"><a href="#94"> 94: </a><span class="php-keyword1">class</span> Hm_Output_create_form <span class="php-keyword1">extends</span> Hm_Output_Module { </span><span id="95" class="l"><a href="#95"> 95: </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> output() { </span><span id="96" class="l"><a href="#96"> 96: </a> <span class="php-keyword1">if</span> (!<span class="php-var">$this</span>-&gt;get(<span class="php-quote">'internal_users'</span>) || !<span class="php-var">$this</span>-&gt;get(<span class="php-quote">'is_admin'</span>, <span class="php-keyword1">false</span>)) { </span><span id="97" class="l"><a href="#97"> 97: </a> Hm_Dispatch::page_redirect(<span class="php-quote">'?page=home'</span>); </span><span id="98" class="l"><a href="#98"> 98: </a> } </span><span id="99" class="l"><a href="#99"> 99: </a> <span class="php-keyword1">return</span> <span class="php-quote">'&lt;div class=&quot;content_title&quot;&gt;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Create Account'</span>).<span class="php-quote">'&lt;/div&gt;'</span>. </span><span id="100" class="l"><a href="#100">100: </a> <span class="php-quote">'&lt;div class=&quot;create_user&quot;&gt;'</span>. </span><span id="101" class="l"><a href="#101">101: </a> <span class="php-quote">'&lt;form method=&quot;POST&quot; autocomplete=&quot;off&quot; &gt;'</span>. </span><span id="102" class="l"><a href="#102">102: </a> <span class="php-quote">'&lt;input type=&quot;hidden&quot; name=&quot;hm_page_key&quot; value=&quot;'</span>.Hm_Request_Key::generate().<span class="php-quote">'&quot; /&gt;'</span>. </span><span id="103" class="l"><a href="#103">103: </a> <span class="php-quote">'&lt;input style=&quot;display:none&quot; type=&quot;text&quot; name=&quot;fake_username&quot; /&gt;'</span>. </span><span id="104" class="l"><a href="#104">104: </a> <span class="php-quote">'&lt;input style=&quot;display:none&quot; type=&quot;password&quot; name=&quot;fake_password&quot; /&gt;'</span>. </span><span id="105" class="l"><a href="#105">105: </a> <span class="php-quote">' &lt;input required type=&quot;text&quot; placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Username'</span>).<span class="php-quote">'&quot; name=&quot;create_username&quot; value=&quot;&quot;&gt;'</span>. </span><span id="106" class="l"><a href="#106">106: </a> <span class="php-quote">' &lt;input type=&quot;password&quot; required placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Password'</span>).<span class="php-quote">'&quot; name=&quot;create_password&quot;&gt;'</span>. </span><span id="107" class="l"><a href="#107">107: </a> <span class="php-quote">' &lt;input type=&quot;password&quot; required placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Password Again'</span>).<span class="php-quote">'&quot; name=&quot;create_password_again&quot;&gt;'</span>. </span><span id="108" class="l"><a href="#108">108: </a> <span class="php-quote">' &lt;input type=&quot;submit&quot; name=&quot;create_hm_user&quot; value=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Create'</span>).<span class="php-quote">'&quot; /&gt;'</span>. </span><span id="109" class="l"><a href="#109">109: </a> <span class="php-quote">'&lt;/form&gt;&lt;/div&gt;'</span>; </span><span id="110" class="l"><a href="#110">110: </a> } </span><span id="111" class="l"><a href="#111">111: </a>} </span><span id="112" class="l"><a href="#112">112: </a> </span><span id="113" class="l"><a href="#113">113: </a><span class="php-comment">/** </span></span><span id="114" class="l"><a href="#114">114: </a><span class="php-comment"> * Adds a link to the change password page to the folder list </span></span><span id="115" class="l"><a href="#115">115: </a><span class="php-comment"> * @subpackage account/output </span></span><span id="116" class="l"><a href="#116">116: </a><span class="php-comment"> */</span> </span><span id="117" class="l"><a href="#117">117: </a><span class="php-keyword1">class</span> Hm_Output_change_password_link <span class="php-keyword1">extends</span> Hm_Output_Module { </span><span id="118" class="l"><a href="#118">118: </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> output() { </span><span id="119" class="l"><a href="#119">119: </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;get(<span class="php-quote">'internal_users'</span>)) { </span><span id="120" class="l"><a href="#120">120: </a> <span class="php-var">$res</span> = <span class="php-quote">'&lt;li class=&quot;menu_change_password&quot;&gt;&lt;a class=&quot;unread_link&quot; href=&quot;?page=change_password&quot;&gt;'</span>. </span><span id="121" class="l"><a href="#121">121: </a> <span class="php-quote">'&lt;img class=&quot;account_icon&quot; src=&quot;'</span>.<span class="php-var">$this</span>-&gt;html_safe(Hm_Image_Sources::<span class="php-var">$key</span>).<span class="php-quote">'&quot; alt=&quot;&quot; width=&quot;16&quot; height=&quot;16&quot; /&gt; '</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Password'</span>).<span class="php-quote">'&lt;/a&gt;&lt;/li&gt;'</span>; </span><span id="122" class="l"><a href="#122">122: </a> <span class="php-var">$this</span>-&gt;concat(<span class="php-quote">'formatted_folder_list'</span>, <span class="php-var">$res</span>); </span><span id="123" class="l"><a href="#123">123: </a> } </span><span id="124" class="l"><a href="#124">124: </a> } </span><span id="125" class="l"><a href="#125">125: </a>} </span><span id="126" class="l"><a href="#126">126: </a> </span><span id="127" class="l"><a href="#127">127: </a> </span><span id="128" class="l"><a href="#128">128: </a><span class="php-comment">/** </span></span><span id="129" class="l"><a href="#129">129: </a><span class="php-comment"> * @subpackage account/output </span></span><span id="130" class="l"><a href="#130">130: </a><span class="php-comment"> */</span> </span><span id="131" class="l"><a href="#131">131: </a><span class="php-keyword1">class</span> Hm_Output_change_password <span class="php-keyword1">extends</span> Hm_Output_Module { </span><span id="132" class="l"><a href="#132">132: </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> output() { </span><span id="133" class="l"><a href="#133">133: </a> <span class="php-var">$res</span> = <span class="php-quote">''</span>; </span><span id="134" class="l"><a href="#134">134: </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;get(<span class="php-quote">'internal_users'</span>)) { </span><span id="135" class="l"><a href="#135">135: </a> <span class="php-var">$res</span> .= <span class="php-quote">'&lt;div class=&quot;chg_pass_page&quot;&gt;&lt;div class=&quot;content_title&quot;&gt;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Change Password'</span>).<span class="php-quote">'&lt;/div&gt;'</span>. </span><span id="136" class="l"><a href="#136">136: </a> <span class="php-quote">'&lt;div class=&quot;change_pass&quot;&gt;&lt;form method=&quot;POST&quot;&gt;'</span>. </span><span id="137" class="l"><a href="#137">137: </a> <span class="php-quote">'&lt;input type=&quot;hidden&quot; name=&quot;hm_page_key&quot; value=&quot;'</span>.Hm_Request_Key::generate().<span class="php-quote">'&quot; /&gt;'</span>. </span><span id="138" class="l"><a href="#138">138: </a> <span class="php-quote">'&lt;label class=&quot;screen_reader&quot; for=&quot;new_pass1&quot;&gt;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'New password'</span>).<span class="php-quote">'&lt;/label&gt;'</span>. </span><span id="139" class="l"><a href="#139">139: </a> <span class="php-quote">'&lt;input required type=&quot;password&quot; id=&quot;new_pass1&quot; name=&quot;new_pass1&quot; placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'New password'</span>).<span class="php-quote">'&quot; /&gt;&lt;br /&gt;'</span>. </span><span id="140" class="l"><a href="#140">140: </a> <span class="php-quote">'&lt;label class=&quot;screen_reader&quot; for=&quot;new_pass2&quot;&gt;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'New password again'</span>).<span class="php-quote">'&lt;/label&gt;'</span>. </span><span id="141" class="l"><a href="#141">141: </a> <span class="php-quote">'&lt;input required type=&quot;password&quot; id=&quot;new_pass2&quot; name=&quot;new_pass2&quot; placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'New password again'</span>).<span class="php-quote">'&quot; /&gt;&lt;br /&gt;'</span>. </span><span id="142" class="l"><a href="#142">142: </a> <span class="php-quote">'&lt;label class=&quot;screen_reader&quot; for=&quot;old_pass&quot;&gt;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Current password'</span>).<span class="php-quote">'&lt;/label&gt;'</span>. </span><span id="143" class="l"><a href="#143">143: </a> <span class="php-quote">'&lt;input required type=&quot;password&quot; id=&quot;old_pass&quot; name=&quot;old_pass&quot; placeholder=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Current password'</span>).<span class="php-quote">'&quot; /&gt;&lt;br /&gt;'</span>. </span><span id="144" class="l"><a href="#144">144: </a> <span class="php-quote">'&lt;input type=&quot;submit&quot; name=&quot;change_password&quot; value=&quot;'</span>.<span class="php-var">$this</span>-&gt;trans(<span class="php-quote">'Update'</span>).<span class="php-quote">'&quot; /&gt;'</span>; </span><span id="145" class="l"><a href="#145">145: </a> <span class="php-var">$res</span> .= <span class="php-quote">'&lt;/form&gt;&lt;/div&gt;&lt;/div&gt;'</span>; </span><span id="146" class="l"><a href="#146">146: </a> } </span><span id="147" class="l"><a href="#147">147: </a> <span class="php-keyword1">return</span> <span class="php-var">$res</span>; </span><span id="148" class="l"><a href="#148">148: </a> } </span><span id="149" class="l"><a href="#149">149: </a>} </span><span id="150" class="l"><a href="#150">150: </a> </span><span id="151" class="l"><a href="#151">151: </a> </span><span id="152" class="l"><a href="#152">152: </a></span></code></pre> <div id="footer"> Cypht Documentation API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js?11103d5bda05b31faaed27f8dac7ff566f7e6eef"></script> <script src="elementlist.js?341a24b610ee59935e2a39085b09917a67158213"></script> </body> </html>
thetomester13/hm3
docs/code_docs/source-class-Hm_Output_create_form.html
HTML
gpl-2.0
75,074
// license:BSD-3-Clause // copyright-holders:Ramiro Polla #include "nec_p72.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** const device_type NEC_P72 = &device_creator<nec_p72_t>; //------------------------------------------------- // ROM( p72 ) //------------------------------------------------- ROM_START( p72 ) ROM_REGION(0x100000, "maincpu", 0) ROM_LOAD("p72.2c", 0x000000, 0x100000, CRC(2bc6846f) SHA1(10430f1d3b73ad413d77053515d9d53831a1341b)) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const rom_entry *nec_p72_t::device_rom_region() const { return ROM_NAME( p72 ); } //------------------------------------------------- // ADDRESS_MAP( p72_mem ) //------------------------------------------------- static ADDRESS_MAP_START( p72_mem, AS_PROGRAM, 8, nec_p72_t ) AM_RANGE(0x000000, 0x0fffff) AM_ROM /* 1Mbit firmware */ AM_RANGE(0x100000, 0x1fffff) AM_RAM /* 1Mbit external RAM */ /* TODO might be 2x1Mbit */ ADDRESS_MAP_END //------------------------------------------------- // MACHINE_DRIVER( nec_p72 ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( nec_p72 ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", V33, XTAL_16MHz/2) /* TODO it's actually a V40 */ MCFG_CPU_PROGRAM_MAP(p72_mem) MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor nec_p72_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( nec_p72 ); } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void nec_p72_t::device_start() { } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // nec_p72_t - constructor //------------------------------------------------- nec_p72_t::nec_p72_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : device_t(mconfig, NEC_P72, "NEC PinWrite P72", tag, owner, clock, "p72", __FILE__), device_centronics_peripheral_interface(mconfig, *this), m_maincpu(*this, "maincpu") { } nec_p72_t::nec_p72_t(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source) : device_t(mconfig, type, name, tag, owner, clock, shortname, __FILE__), device_centronics_peripheral_interface(mconfig, *this), m_maincpu(*this, "maincpu") { }
RJRetro/mame
src/devices/bus/centronics/nec_p72.cpp
C++
gpl-2.0
2,936
<?php /** * Cache decorator. * * PHP version 5 * * Copyright (C) Villanova University 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Config * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ namespace VuFind\Config\Reader; use Zend\Config\Reader\ReaderInterface; use Zend\Cache\Storage\StorageInterface; /** * This class decorates a configuration file reader with caching support. * * @category VuFind2 * @package Config * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ class CacheDecorator implements ReaderInterface { /** * The decorated reader. * * @var ReaderInterface */ protected $reader; /** * Cache storage. * * @var StorageInterface */ protected $storage; /** * Constructor. * * @param ReaderInterface $reader Config reader * @param StorageInterface $storage Cache storage * * @return void */ public function __construct (ReaderInterface $reader, StorageInterface $storage) { $this->reader = $reader; $this->storage = $storage; } /** * Read from a file and create an array * * @param string $filename Filename * * @return array */ public function fromFile($filename) { $absFilename = realpath($filename); $mtime = @filemtime($absFilename); $key = $this->generateKey($mtime . $absFilename); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $config = $this->reader->fromFile($filename); $this->storage->setItem($key, $config); return $config; } /** * Read from a string and create an array * * @param string $string String * * @return array|boolean */ public function fromString($string) { $key = $this->generateKey($string); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $config = $this->reader->fromString($string); $this->storage->setItem($key, $config); return $config; } /// Internal API /** * Return a cache key. * * @param string $string String * * @return string */ protected function generateKey($string) { return md5($string); } }
swissbib/sbvf2
module/VuFind/src/VuFind/Config/Reader/CacheDecorator.php
PHP
gpl-2.0
3,224
/* * fips186prf.c An implementation of the FIPS-186-2 SHA1-based PRF. * * The development of the EAP/SIM support was funded by Internet Foundation * Austria (http://www.nic.at/ipa). * * This code was written from scratch by Michael Richardson, and it is * dual licensed under both GPL and BSD. * * Version: $Id$ * * GPL notice: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * BSD notice: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Copyright 2003 Michael Richardson <mcr@sandelman.ottawa.on.ca> * Copyright 2006 The FreeRADIUS server project * */ RCSID("$Id$") #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <freeradius-devel/sha1.h> /* * we do it in 8-bit chunks, because we have to keep the numbers * in network byte order (i.e. MSB) * * make it a structure so that we can do structure assignments. */ typedef struct onesixty { uint8_t p[20]; } onesixty; static void onesixty_add_mod(onesixty *sum, onesixty *a, onesixty *b) { uint32_t s; int i, carry; carry = 0; for(i=19; i>=0; i--) { /* for(i=0; i<20; i++) { */ s = a->p[i] + b->p[i] + carry; sum->p[i] = s & 0xff; carry = s >> 8; } } /* * run the FIPS-186-2 PRF on the given Master Key (160 bits) * in order to derive 1280 bits (160 bytes) of keying data from * it. * * Given that in EAP-SIM, this is coming from a 64-bit Kc it seems * like an awful lot of "randomness" to pull out.. (MCR) * */ void fips186_2prf(uint8_t mk[20], uint8_t finalkey[160]) { fr_SHA1_CTX context; int j; onesixty xval, xkey, w_0, w_1, sum, one; uint8_t *f; uint8_t zeros[64]; /* * let XKEY := MK, * * Step 3: For j = 0 to 3 do * a. XVAL = XKEY * b. w_0 = SHA1(XVAL) * c. XKEY = (1 + XKEY + w_0) mod 2^160 * d. XVAL = XKEY * e. w_1 = SHA1(XVAL) * f. XKEY = (1 + XKEY + w_1) mod 2^160 * 3.3 x_j = w_0|w_1 * */ memcpy(&xkey, mk, sizeof(xkey)); /* make the value 1 */ memset(&one, 0, sizeof(one)); one.p[19]=1; f=finalkey; for(j=0; j<4; j++) { /* a. XVAL = XKEY */ xval = xkey; /* b. w_0 = SHA1(XVAL) */ fr_sha1_init(&context); memset(zeros + 20, 0, sizeof(zeros) - 20); memcpy(zeros, xval.p, 20); #ifndef WITH_OPENSSL_SHA1 fr_sha1_transform(context.state, zeros); #else fr_sha1_transform(&context, zeros); #endif fr_sha1_final_no_len(w_0.p, &context); /* c. XKEY = (1 + XKEY + w_0) mod 2^160 */ onesixty_add_mod(&sum, &xkey, &w_0); onesixty_add_mod(&xkey, &sum, &one); /* d. XVAL = XKEY */ xval = xkey; /* e. w_1 = SHA1(XVAL) */ fr_sha1_init(&context); memset(zeros + 20, 0, sizeof(zeros) - 20); memcpy(zeros, xval.p, 20); #ifndef WITH_OPENSSL_SHA1 fr_sha1_transform(context.state, zeros); #else fr_sha1_transform(&context, zeros); #endif fr_sha1_final_no_len(w_1.p, &context); /* f. XKEY = (1 + XKEY + w_1) mod 2^160 */ onesixty_add_mod(&sum, &xkey, &w_1); onesixty_add_mod(&xkey, &sum, &one); /* now store it away */ memcpy(f, &w_0, 20); f += 20; memcpy(f, &w_1, 20); f += 20; } } /* * test vectors * from http://csrc.nist.gov/CryptoToolkit/dss/Examples-1024bit.pdf * * page 5 * * XKEY= bd029bbe 7f51960b cf9edb2b 61f06f0f eb5a38b6 * XSEED= 00000000 00000000 00000000 00000000 00000000 * * * The first loop through step 3.2 provides: * * XVAL= bd029bbe 7f51960b cf9edb2b 61f06f0f eb5a38b6 * * Using the routine in Appendix 3.3, Constructing The Function G From SHA-1, * in step 3.2.b of the Change Notice algorithm for computing values of x * provides: * * w[0]= 2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614 * * * The following value is the updated XKEY value from step 3.2.c: * * XKEY= dd734ee0 bd0bcd3b adbaeb27 dd1eaa59 76803ecb * * The second loop through step 3.2 provides: * * XVAL= dd734ee0 bd0bcd3b adbaeb27 dd1eaa59 76803ecb * * Using the routine in Appendix 3.3, Constructing The Function G From SHA-1, * in step 3.2.b of the Change Notice algorithm for computing values of x * provides: * * w[1]= 3c6c18ba cb0f6c55 babb1378 8e20d737 a3275116 * * The following value is the updated XKEY value from step 3.2.c: * * * XKEY= 19df679b 881b3991 6875fea0 6b3f8191 19a78fe2 * * Step 3.3 provides the following values: * * w[0] || w[1]= 2070b322 3dba372f de1c0ffc 7b2e3b49 8b260614 * 3c6c18ba cb0f6c55 babb1378 8e20d737 a3275116 * */ #ifdef TEST_CASE #include <assert.h> uint8_t mk[20]={ 0xbd, 0x02, 0x9b, 0xbe, 0x7f, 0x51, 0x96, 0x0b, 0xcf, 0x9e, 0xdb, 0x2b, 0x61, 0xf0, 0x6f, 0x0f, 0xeb, 0x5a, 0x38, 0xb6 }; main(int argc, char *argv[]) { uint8_t finalkey[160]; int i, j, k; fips186_2prf(mk, finalkey); printf("Input was: |"); j=0; for (i = 0; i < 20; i++) { if(j==4) { printf("_"); j=0; } j++; printf("%02x", mk[i]); } printf("|\nOutput was: "); j=0; k=0; for (i = 0; i < 160; i++) { if(k==20) { printf("\n "); k=0; j=0; } if(j==4) { printf("_"); j=0; } k++; j++; printf("%02x", finalkey[i]); } printf("\n"); } #endif
simonflood/freeradius-server
src/modules/rlm_eap/libeap/fips186prf.c
C
gpl-2.0
6,564
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/jiffies.h> #include <linux/debugfs.h> #include <linux/io.h> #include <linux/idr.h> #include <linux/string.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/delay.h> #include <linux/completion.h> #include <linux/ipc_logging.h> #include "ipc_logging_private.h" #define LOG_PAGE_DATA_SIZE sizeof(((struct ipc_log_page *)0)->data) #define LOG_PAGE_FLAG (1 << 31) static LIST_HEAD(ipc_log_context_list); static DEFINE_RWLOCK(context_list_lock_lha1); static void *get_deserialization_func(struct ipc_log_context *ilctxt, int type); static struct ipc_log_page *get_first_page(struct ipc_log_context *ilctxt) { struct ipc_log_page_header *p_pghdr; struct ipc_log_page *pg = NULL; if (!ilctxt) return NULL; p_pghdr = list_first_entry(&ilctxt->page_list, struct ipc_log_page_header, list); pg = container_of(p_pghdr, struct ipc_log_page, hdr); return pg; } /** * is_nd_read_empty - Returns true if no data is available to read in log * * @ilctxt: logging context * @returns: > 1 if context is empty; 0 if not empty; <0 for failure * * This is for the debugfs read pointer which allows for a non-destructive read. * There may still be data in the log, but it may have already been read. */ static int is_nd_read_empty(struct ipc_log_context *ilctxt) { if (!ilctxt) return -EINVAL; return ((ilctxt->nd_read_page == ilctxt->write_page) && (ilctxt->nd_read_page->hdr.nd_read_offset == ilctxt->write_page->hdr.write_offset)); } /** * is_read_empty - Returns true if no data is available in log * * @ilctxt: logging context * @returns: > 1 if context is empty; 0 if not empty; <0 for failure * * This is for the actual log contents. If it is empty, then there * is no data at all in the log. */ static int is_read_empty(struct ipc_log_context *ilctxt) { if (!ilctxt) return -EINVAL; return ((ilctxt->read_page == ilctxt->write_page) && (ilctxt->read_page->hdr.read_offset == ilctxt->write_page->hdr.write_offset)); } /** * is_nd_read_equal_read - Return true if the non-destructive read is equal to * the destructive read * * @ilctxt: logging context * @returns: true if nd read is equal to read; false otherwise */ static bool is_nd_read_equal_read(struct ipc_log_context *ilctxt) { uint16_t read_offset; uint16_t nd_read_offset; if (ilctxt->nd_read_page == ilctxt->read_page) { read_offset = ilctxt->read_page->hdr.read_offset; nd_read_offset = ilctxt->nd_read_page->hdr.nd_read_offset; if (read_offset == nd_read_offset) return true; } return false; } static struct ipc_log_page *get_next_page(struct ipc_log_context *ilctxt, struct ipc_log_page *cur_pg) { struct ipc_log_page_header *p_pghdr; struct ipc_log_page *pg = NULL; if (!ilctxt || !cur_pg) return NULL; if (ilctxt->last_page == cur_pg) return ilctxt->first_page; p_pghdr = list_first_entry(&cur_pg->hdr.list, struct ipc_log_page_header, list); pg = container_of(p_pghdr, struct ipc_log_page, hdr); return pg; } /** * ipc_log_read - do non-destructive read of the log * * @ilctxt: Logging context * @data: Data pointer to receive the data * @data_size: Number of bytes to read (must be <= bytes available in log) * * This read will update a runtime read pointer, but will not affect the actual * contents of the log which allows for reading the logs continuously while * debugging and if the system crashes, then the full logs can still be * extracted. */ static void ipc_log_read(struct ipc_log_context *ilctxt, void *data, int data_size) { int bytes_to_read; bytes_to_read = MIN(LOG_PAGE_DATA_SIZE - ilctxt->nd_read_page->hdr.nd_read_offset, data_size); memcpy(data, (ilctxt->nd_read_page->data + ilctxt->nd_read_page->hdr.nd_read_offset), bytes_to_read); if (bytes_to_read != data_size) { /* not enough space, wrap read to next page */ ilctxt->nd_read_page->hdr.nd_read_offset = 0; ilctxt->nd_read_page = get_next_page(ilctxt, ilctxt->nd_read_page); memcpy((data + bytes_to_read), (ilctxt->nd_read_page->data + ilctxt->nd_read_page->hdr.nd_read_offset), (data_size - bytes_to_read)); bytes_to_read = (data_size - bytes_to_read); } ilctxt->nd_read_page->hdr.nd_read_offset += bytes_to_read; } /** * ipc_log_drop - do destructive read of the log * * @ilctxt: Logging context * @data: Data pointer to receive the data (or NULL) * @data_size: Number of bytes to read (must be <= bytes available in log) */ static void ipc_log_drop(struct ipc_log_context *ilctxt, void *data, int data_size) { int bytes_to_read; bool push_nd_read; bytes_to_read = MIN(LOG_PAGE_DATA_SIZE - ilctxt->read_page->hdr.read_offset, data_size); if (data) memcpy(data, (ilctxt->read_page->data + ilctxt->read_page->hdr.read_offset), bytes_to_read); if (bytes_to_read != data_size) { /* not enough space, wrap read to next page */ push_nd_read = is_nd_read_equal_read(ilctxt); ilctxt->read_page->hdr.read_offset = 0; if (push_nd_read) { ilctxt->read_page->hdr.nd_read_offset = 0; ilctxt->read_page = get_next_page(ilctxt, ilctxt->read_page); ilctxt->nd_read_page = ilctxt->read_page; } else { ilctxt->read_page = get_next_page(ilctxt, ilctxt->read_page); } if (data) memcpy((data + bytes_to_read), (ilctxt->read_page->data + ilctxt->read_page->hdr.read_offset), (data_size - bytes_to_read)); bytes_to_read = (data_size - bytes_to_read); } /* update non-destructive read pointer if necessary */ push_nd_read = is_nd_read_equal_read(ilctxt); ilctxt->read_page->hdr.read_offset += bytes_to_read; ilctxt->write_avail += data_size; if (push_nd_read) ilctxt->nd_read_page->hdr.nd_read_offset += bytes_to_read; } /** * msg_read - Reads a message. * * If a message is read successfully, then the message context * will be set to: * .hdr message header .size and .type values * .offset beginning of message data * * @ilctxt Logging context * @ectxt Message context * * @returns 0 - no message available; >0 message size; <0 error */ static int msg_read(struct ipc_log_context *ilctxt, struct encode_context *ectxt) { struct tsv_header hdr; if (!ectxt) return -EINVAL; if (is_nd_read_empty(ilctxt)) return 0; ipc_log_read(ilctxt, &hdr, sizeof(hdr)); ectxt->hdr.type = hdr.type; ectxt->hdr.size = hdr.size; ectxt->offset = sizeof(hdr); ipc_log_read(ilctxt, (ectxt->buff + ectxt->offset), (int)hdr.size); return sizeof(hdr) + (int)hdr.size; } /** * msg_drop - Drops a message. * * @ilctxt Logging context */ static void msg_drop(struct ipc_log_context *ilctxt) { struct tsv_header hdr; if (!is_read_empty(ilctxt)) { ipc_log_drop(ilctxt, &hdr, sizeof(hdr)); ipc_log_drop(ilctxt, NULL, (int)hdr.size); } } /* * Commits messages to the FIFO. If the FIFO is full, then enough * messages are dropped to create space for the new message. */ void ipc_log_write(void *ctxt, struct encode_context *ectxt) { struct ipc_log_context *ilctxt = (struct ipc_log_context *)ctxt; int bytes_to_write; unsigned long flags; if (!ilctxt || !ectxt) { pr_err("%s: Invalid ipc_log or encode context\n", __func__); return; } read_lock_irqsave(&context_list_lock_lha1, flags); spin_lock(&ilctxt->context_lock_lhb1); while (ilctxt->write_avail <= ectxt->offset) msg_drop(ilctxt); bytes_to_write = MIN(LOG_PAGE_DATA_SIZE - ilctxt->write_page->hdr.write_offset, ectxt->offset); memcpy((ilctxt->write_page->data + ilctxt->write_page->hdr.write_offset), ectxt->buff, bytes_to_write); if (bytes_to_write != ectxt->offset) { uint64_t t_now = sched_clock(); ilctxt->write_page->hdr.write_offset += bytes_to_write; ilctxt->write_page->hdr.end_time = t_now; ilctxt->write_page = get_next_page(ilctxt, ilctxt->write_page); ilctxt->write_page->hdr.write_offset = 0; ilctxt->write_page->hdr.start_time = t_now; memcpy((ilctxt->write_page->data + ilctxt->write_page->hdr.write_offset), (ectxt->buff + bytes_to_write), (ectxt->offset - bytes_to_write)); bytes_to_write = (ectxt->offset - bytes_to_write); } ilctxt->write_page->hdr.write_offset += bytes_to_write; ilctxt->write_avail -= ectxt->offset; complete(&ilctxt->read_avail); spin_unlock(&ilctxt->context_lock_lhb1); read_unlock_irqrestore(&context_list_lock_lha1, flags); } EXPORT_SYMBOL(ipc_log_write); /* * Starts a new message after which you can add serialized data and * then complete the message by calling msg_encode_end(). */ void msg_encode_start(struct encode_context *ectxt, uint32_t type) { if (!ectxt) { pr_err("%s: Invalid encode context\n", __func__); return; } ectxt->hdr.type = type; ectxt->hdr.size = 0; ectxt->offset = sizeof(ectxt->hdr); } EXPORT_SYMBOL(msg_encode_start); /* * Completes the message */ void msg_encode_end(struct encode_context *ectxt) { if (!ectxt) { pr_err("%s: Invalid encode context\n", __func__); return; } /* finalize data size */ ectxt->hdr.size = ectxt->offset - sizeof(ectxt->hdr); BUG_ON(ectxt->hdr.size > MAX_MSG_SIZE); memcpy(ectxt->buff, &ectxt->hdr, sizeof(ectxt->hdr)); } EXPORT_SYMBOL(msg_encode_end); /* * Helper funtion used to write data to a message context. * * @ectxt context initialized by calling msg_encode_start() * @data data to write * @size number of bytes of data to write */ static inline int tsv_write_data(struct encode_context *ectxt, void *data, uint32_t size) { if (!ectxt) { pr_err("%s: Invalid encode context\n", __func__); return -EINVAL; } if ((ectxt->offset + size) > MAX_MSG_SIZE) { pr_err("%s: No space to encode further\n", __func__); return -EINVAL; } memcpy((void *)(ectxt->buff + ectxt->offset), data, size); ectxt->offset += size; return 0; } /* * Helper function that writes a type to the context. * * @ectxt context initialized by calling msg_encode_start() * @type primitive type * @size size of primitive in bytes */ static inline int tsv_write_header(struct encode_context *ectxt, uint32_t type, uint32_t size) { struct tsv_header hdr; hdr.type = (unsigned char)type; hdr.size = (unsigned char)size; return tsv_write_data(ectxt, &hdr, sizeof(hdr)); } /* * Writes the current timestamp count. * * @ectxt context initialized by calling msg_encode_start() */ int tsv_timestamp_write(struct encode_context *ectxt) { int ret; uint64_t t_now = sched_clock(); ret = tsv_write_header(ectxt, TSV_TYPE_TIMESTAMP, sizeof(t_now)); if (ret) return ret; return tsv_write_data(ectxt, &t_now, sizeof(t_now)); } EXPORT_SYMBOL(tsv_timestamp_write); /* * Writes a data pointer. * * @ectxt context initialized by calling msg_encode_start() * @pointer pointer value to write */ int tsv_pointer_write(struct encode_context *ectxt, void *pointer) { int ret; ret = tsv_write_header(ectxt, TSV_TYPE_POINTER, sizeof(pointer)); if (ret) return ret; return tsv_write_data(ectxt, &pointer, sizeof(pointer)); } EXPORT_SYMBOL(tsv_pointer_write); /* * Writes a 32-bit integer value. * * @ectxt context initialized by calling msg_encode_start() * @n integer to write */ int tsv_int32_write(struct encode_context *ectxt, int32_t n) { int ret; ret = tsv_write_header(ectxt, TSV_TYPE_INT32, sizeof(n)); if (ret) return ret; return tsv_write_data(ectxt, &n, sizeof(n)); } EXPORT_SYMBOL(tsv_int32_write); /* * Writes a byte array. * * @ectxt context initialized by calling msg_write_start() * @data Beginning address of data * @data_size Size of data to be written */ int tsv_byte_array_write(struct encode_context *ectxt, void *data, int data_size) { int ret; ret = tsv_write_header(ectxt, TSV_TYPE_BYTE_ARRAY, data_size); if (ret) return ret; return tsv_write_data(ectxt, data, data_size); } EXPORT_SYMBOL(tsv_byte_array_write); /* * Helper function to log a string * * @ilctxt ipc_log_context created using ipc_log_context_create() * @fmt Data specified using format specifiers */ int ipc_log_string(void *ilctxt, const char *fmt, ...) { struct encode_context ectxt; int avail_size, data_size, hdr_size = sizeof(struct tsv_header); va_list arg_list; if (!ilctxt) return -EINVAL; msg_encode_start(&ectxt, TSV_TYPE_STRING); tsv_timestamp_write(&ectxt); avail_size = (MAX_MSG_SIZE - (ectxt.offset + hdr_size)); va_start(arg_list, fmt); data_size = vsnprintf((ectxt.buff + ectxt.offset + hdr_size), avail_size, fmt, arg_list); va_end(arg_list); tsv_write_header(&ectxt, TSV_TYPE_BYTE_ARRAY, data_size); ectxt.offset += data_size; msg_encode_end(&ectxt); ipc_log_write(ilctxt, &ectxt); return 0; } EXPORT_SYMBOL(ipc_log_string); /** * ipc_log_extract - Reads and deserializes log * * @ctxt: logging context * @buff: buffer to receive the data * @size: size of the buffer * @returns: 0 if no data read; >0 number of bytes read; < 0 error * * If no data is available to be read, then the ilctxt::read_avail * completion is reinitialized. This allows clients to block * until new log data is save. */ int ipc_log_extract(void *ctxt, char *buff, int size) { struct encode_context ectxt; struct decode_context dctxt; void (*deserialize_func)(struct encode_context *ectxt, struct decode_context *dctxt); struct ipc_log_context *ilctxt = (struct ipc_log_context *)ctxt; unsigned long flags; if (size < MAX_MSG_DECODED_SIZE) return -EINVAL; dctxt.output_format = OUTPUT_DEBUGFS; dctxt.buff = buff; dctxt.size = size; read_lock_irqsave(&context_list_lock_lha1, flags); spin_lock(&ilctxt->context_lock_lhb1); while (dctxt.size >= MAX_MSG_DECODED_SIZE && !is_nd_read_empty(ilctxt)) { msg_read(ilctxt, &ectxt); deserialize_func = get_deserialization_func(ilctxt, ectxt.hdr.type); spin_unlock(&ilctxt->context_lock_lhb1); read_unlock_irqrestore(&context_list_lock_lha1, flags); if (deserialize_func) deserialize_func(&ectxt, &dctxt); else pr_err("%s: unknown message 0x%x\n", __func__, ectxt.hdr.type); read_lock_irqsave(&context_list_lock_lha1, flags); spin_lock(&ilctxt->context_lock_lhb1); } if ((size - dctxt.size) == 0) INIT_COMPLETION(ilctxt->read_avail); spin_unlock(&ilctxt->context_lock_lhb1); read_unlock_irqrestore(&context_list_lock_lha1, flags); return size - dctxt.size; } EXPORT_SYMBOL(ipc_log_extract); /* * Helper funtion used to read data from a message context. * * @ectxt context initialized by calling msg_read() * @data data to read * @size number of bytes of data to read */ static void tsv_read_data(struct encode_context *ectxt, void *data, uint32_t size) { BUG_ON((ectxt->offset + size) > MAX_MSG_SIZE); memcpy(data, (ectxt->buff + ectxt->offset), size); ectxt->offset += size; } /* * Helper function that reads a type from the context and updates the * context pointers. * * @ectxt context initialized by calling msg_read() * @hdr type header */ static void tsv_read_header(struct encode_context *ectxt, struct tsv_header *hdr) { BUG_ON((ectxt->offset + sizeof(*hdr)) > MAX_MSG_SIZE); memcpy(hdr, (ectxt->buff + ectxt->offset), sizeof(*hdr)); ectxt->offset += sizeof(*hdr); } /* * Reads a timestamp. * * @ectxt context initialized by calling msg_read() * @dctxt deserialization context * @format output format (appended to %6u.%09u timestamp format) */ void tsv_timestamp_read(struct encode_context *ectxt, struct decode_context *dctxt, const char *format) { struct tsv_header hdr; uint64_t val; unsigned long nanosec_rem; tsv_read_header(ectxt, &hdr); BUG_ON(hdr.type != TSV_TYPE_TIMESTAMP); tsv_read_data(ectxt, &val, sizeof(val)); nanosec_rem = do_div(val, 1000000000U); IPC_SPRINTF_DECODE(dctxt, "[%6u.%09lu]%s", (unsigned)val, nanosec_rem, format); } EXPORT_SYMBOL(tsv_timestamp_read); /* * Reads a data pointer. * * @ectxt context initialized by calling msg_read() * @dctxt deserialization context * @format output format */ void tsv_pointer_read(struct encode_context *ectxt, struct decode_context *dctxt, const char *format) { struct tsv_header hdr; void *val; tsv_read_header(ectxt, &hdr); BUG_ON(hdr.type != TSV_TYPE_POINTER); tsv_read_data(ectxt, &val, sizeof(val)); IPC_SPRINTF_DECODE(dctxt, format, val); } EXPORT_SYMBOL(tsv_pointer_read); /* * Reads a 32-bit integer value. * * @ectxt context initialized by calling msg_read() * @dctxt deserialization context * @format output format */ int32_t tsv_int32_read(struct encode_context *ectxt, struct decode_context *dctxt, const char *format) { struct tsv_header hdr; int32_t val; tsv_read_header(ectxt, &hdr); BUG_ON(hdr.type != TSV_TYPE_INT32); tsv_read_data(ectxt, &val, sizeof(val)); IPC_SPRINTF_DECODE(dctxt, format, val); return val; } EXPORT_SYMBOL(tsv_int32_read); /* * Reads a byte array/string. * * @ectxt context initialized by calling msg_read() * @dctxt deserialization context * @format output format */ void tsv_byte_array_read(struct encode_context *ectxt, struct decode_context *dctxt, const char *format) { struct tsv_header hdr; tsv_read_header(ectxt, &hdr); BUG_ON(hdr.type != TSV_TYPE_BYTE_ARRAY); tsv_read_data(ectxt, dctxt->buff, hdr.size); dctxt->buff += hdr.size; dctxt->size -= hdr.size; } EXPORT_SYMBOL(tsv_byte_array_read); int add_deserialization_func(void *ctxt, int type, void (*dfunc)(struct encode_context *, struct decode_context *)) { struct ipc_log_context *ilctxt = (struct ipc_log_context *)ctxt; struct dfunc_info *df_info; unsigned long flags; if (!ilctxt || !dfunc) return -EINVAL; df_info = kmalloc(sizeof(struct dfunc_info), GFP_KERNEL); if (!df_info) return -ENOSPC; read_lock_irqsave(&context_list_lock_lha1, flags); spin_lock(&ilctxt->context_lock_lhb1); df_info->type = type; df_info->dfunc = dfunc; list_add_tail(&df_info->list, &ilctxt->dfunc_info_list); spin_unlock(&ilctxt->context_lock_lhb1); read_unlock_irqrestore(&context_list_lock_lha1, flags); return 0; } EXPORT_SYMBOL(add_deserialization_func); static void *get_deserialization_func(struct ipc_log_context *ilctxt, int type) { struct dfunc_info *df_info = NULL; if (!ilctxt) return NULL; list_for_each_entry(df_info, &ilctxt->dfunc_info_list, list) { if (df_info->type == type) return df_info->dfunc; } return NULL; } /** * ipc_log_context_create: Create a debug log context * Should not be called from atomic context * * @max_num_pages: Number of pages of logging space required (max. 10) * @mod_name : Name of the directory entry under DEBUGFS * @user_version : Version number of user-defined message formats * * returns context id on success, NULL on failure */ void *ipc_log_context_create(int max_num_pages, const char *mod_name, uint16_t user_version) { struct ipc_log_context *ctxt; struct ipc_log_page *pg = NULL; int page_cnt; unsigned long flags; ctxt = kzalloc(sizeof(struct ipc_log_context), GFP_KERNEL); if (!ctxt) { pr_err("%s: cannot create ipc_log_context\n", __func__); return 0; } init_completion(&ctxt->read_avail); INIT_LIST_HEAD(&ctxt->page_list); INIT_LIST_HEAD(&ctxt->dfunc_info_list); spin_lock_init(&ctxt->context_lock_lhb1); for (page_cnt = 0; page_cnt < max_num_pages; page_cnt++) { pg = kzalloc(sizeof(struct ipc_log_page), GFP_KERNEL); if (!pg) { pr_err("%s: cannot create ipc_log_page\n", __func__); goto release_ipc_log_context; } pg->hdr.log_id = (uint64_t)(uintptr_t)ctxt; pg->hdr.page_num = LOG_PAGE_FLAG | page_cnt; pg->hdr.ctx_offset = (int64_t)((uint64_t)(uintptr_t)ctxt - (uint64_t)(uintptr_t)&pg->hdr); /* set magic last to signal that page init is complete */ pg->hdr.magic = IPC_LOGGING_MAGIC_NUM; pg->hdr.nmagic = ~(IPC_LOGGING_MAGIC_NUM); spin_lock_irqsave(&ctxt->context_lock_lhb1, flags); list_add_tail(&pg->hdr.list, &ctxt->page_list); spin_unlock_irqrestore(&ctxt->context_lock_lhb1, flags); } ctxt->log_id = (uint64_t)(uintptr_t)ctxt; ctxt->version = IPC_LOG_VERSION; strlcpy(ctxt->name, mod_name, IPC_LOG_MAX_CONTEXT_NAME_LEN); ctxt->user_version = user_version; ctxt->first_page = get_first_page(ctxt); ctxt->last_page = pg; ctxt->write_page = ctxt->first_page; ctxt->read_page = ctxt->first_page; ctxt->nd_read_page = ctxt->first_page; ctxt->write_avail = max_num_pages * LOG_PAGE_DATA_SIZE; ctxt->header_size = sizeof(struct ipc_log_page_header); create_ctx_debugfs(ctxt, mod_name); /* set magic last to signal context init is complete */ ctxt->magic = IPC_LOG_CONTEXT_MAGIC_NUM; ctxt->nmagic = ~(IPC_LOG_CONTEXT_MAGIC_NUM); write_lock_irqsave(&context_list_lock_lha1, flags); list_add_tail(&ctxt->list, &ipc_log_context_list); write_unlock_irqrestore(&context_list_lock_lha1, flags); return (void *)ctxt; release_ipc_log_context: while (page_cnt-- > 0) { pg = get_first_page(ctxt); list_del(&pg->hdr.list); kfree(pg); } kfree(ctxt); return 0; } EXPORT_SYMBOL(ipc_log_context_create); /* * Destroy debug log context * * @ctxt: debug log context created by calling ipc_log_context_create API. */ int ipc_log_context_destroy(void *ctxt) { struct ipc_log_context *ilctxt = (struct ipc_log_context *)ctxt; struct ipc_log_page *pg = NULL; unsigned long flags; if (!ilctxt) return 0; while (!list_empty(&ilctxt->page_list)) { pg = get_first_page(ctxt); list_del(&pg->hdr.list); kfree(pg); } write_lock_irqsave(&context_list_lock_lha1, flags); list_del(&ilctxt->list); write_unlock_irqrestore(&context_list_lock_lha1, flags); kfree(ilctxt); return 0; } EXPORT_SYMBOL(ipc_log_context_destroy); static int __init ipc_logging_init(void) { check_and_create_debugfs(); return 0; } module_init(ipc_logging_init); MODULE_DESCRIPTION("ipc logging"); MODULE_LICENSE("GPL v2");
Skin1980/bass
kernel/trace/ipc_logging.c
C
gpl-2.0
22,470
// license:BSD-3-Clause // copyright-holders:Sergey Svishchev /*************************************************************************** BBN BitGraph -- monochrome, raster graphics (768x1024), serial terminal. Apparently had at least four hardware revisions, A-D, but which ROM revisions support which hardware is unclear. A Versabus slot, and various hardware and software options are mentioned in the docs. Best guesses follow. Onboard hardware (common to all revisions) is - 32K ROM - 128K RAM (includes frame buffer) - 3 serial ports, each driven by 6850 ACIA - some kind of baud rate generator, possibly COM8016 - sync serial port, driven by 6854 but apparently never supported by ROM - 682x PIA - AY-3-891x PSG - ER2055 EAROM - DEC VT100 keyboard interface Rev A has additional 4th serial port for mouse (not supported by ROM 1.25). Rev A has 40 hz realtime clock, the rest use 1040 hz. Rev A-C use AY-3-8912 (with one external PIO port, to connect the EAROM). Rev D uses AY-3-8913 (no external ports; EAROM is wired to TBD). Rev B-D have onboard 8035 to talk to parallel printer and mouse. Rev B-D have more memory (at least up to 512K). ROM 1.25 doesn't support mouse, setup mode, pixel data upload and autowrap. Missing/incorrect emulation: Bidirectional keyboard interface (to drive LEDs and speaker). 8035. EAROM. 1.25 only -- clksync() is dummied out -- causes watchdog resets. Selectable memory size. Video enable/reverse video switch. ****************************************************************************/ #include "emu.h" #include "bus/centronics/ctronics.h" #include "bus/rs232/rs232.h" #include "cpu/m68000/m68000.h" #include "cpu/mcs48/mcs48.h" #include "machine/6821pia.h" #include "machine/6850acia.h" #include "machine/clock.h" #include "machine/com8116.h" #include "machine/er2055.h" #include "machine/i8243.h" #include "machine/mc6854.h" #include "machine/ram.h" #include "sound/ay8910.h" #include "bitgrpha.lh" #include "bitgrphb.lh" #define M68K_TAG "maincpu" #define PPU_TAG "ppu" #define ACIA0_TAG "acia0" #define ACIA1_TAG "acia1" #define ACIA2_TAG "acia2" #define ACIA3_TAG "acia3" #define RS232_H_TAG "rs232host" #define RS232_K_TAG "rs232kbd" #define RS232_D_TAG "rs232debug" #define RS232_M_TAG "rs232mouse" #define COM8116_A_TAG "com8116_a" #define COM8116_B_TAG "com8116_b" #define ADLC_TAG "adlc" #define PIA_TAG "pia" #define PSG_TAG "psg" #define EAROM_TAG "earom" #define VERBOSE_DBG 1 /* general debug messages */ #define DBG_LOG(N,M,A) \ do { \ if(VERBOSE_DBG>=N) \ { \ if( M ) \ logerror("%11.6f at %s: %-24s",machine().time().as_double(),machine().describe_context(),(char*)M ); \ logerror A; \ } \ } while (0) class bitgraph_state : public driver_device { public: bitgraph_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, M68K_TAG) , m_ram(*this, RAM_TAG) , m_acia0(*this, ACIA0_TAG) , m_acia1(*this, ACIA1_TAG) , m_acia2(*this, ACIA2_TAG) , m_acia3(*this, ACIA3_TAG) , m_adlc(*this, ADLC_TAG) , m_dbrga(*this, COM8116_A_TAG) , m_dbrgb(*this, COM8116_B_TAG) , m_pia(*this, PIA_TAG) , m_psg(*this, PSG_TAG) , m_earom(*this, EAROM_TAG) , m_centronics(*this, "centronics") , m_screen(*this, "screen") { } DECLARE_READ8_MEMBER( pia_r ); DECLARE_WRITE8_MEMBER( pia_w ); DECLARE_READ8_MEMBER( pia_pa_r ); DECLARE_READ8_MEMBER( pia_pb_r ); DECLARE_WRITE8_MEMBER( pia_pa_w ); DECLARE_WRITE8_MEMBER( pia_pb_w ); DECLARE_READ_LINE_MEMBER( pia_ca1_r ); DECLARE_WRITE_LINE_MEMBER( pia_cb2_w ); DECLARE_WRITE16_MEMBER( baud_write ); DECLARE_WRITE_LINE_MEMBER( com8116_a_fr_w ); DECLARE_WRITE_LINE_MEMBER( com8116_a_ft_w ); DECLARE_WRITE_LINE_MEMBER( com8116_b_fr_w ); DECLARE_WRITE_LINE_MEMBER( com8116_b_ft_w ); DECLARE_READ8_MEMBER( adlc_r ); DECLARE_WRITE8_MEMBER( adlc_w ); DECLARE_WRITE8_MEMBER( earom_write ); DECLARE_WRITE8_MEMBER( misccr_write ); DECLARE_WRITE_LINE_MEMBER( system_clock_write ); UINT32 screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); DECLARE_READ8_MEMBER( ppu_read ); DECLARE_WRITE8_MEMBER( ppu_write ); DECLARE_WRITE8_MEMBER( ppu_i8243_w ); private: virtual void machine_start() override; virtual void machine_reset() override; required_device<cpu_device> m_maincpu; required_device<ram_device> m_ram; required_device<acia6850_device> m_acia0; required_device<acia6850_device> m_acia1; required_device<acia6850_device> m_acia2; optional_device<acia6850_device> m_acia3; optional_device<mc6854_device> m_adlc; required_device<com8116_device> m_dbrga; required_device<com8116_device> m_dbrgb; required_device<pia6821_device> m_pia; required_device<ay8912_device> m_psg; required_device<er2055_device> m_earom; optional_device<centronics_device> m_centronics; required_device<screen_device> m_screen; UINT8 *m_videoram; UINT8 m_misccr; UINT8 m_pia_a; UINT8 m_pia_b; UINT8 m_ppu[4]; }; static ADDRESS_MAP_START(bitgrapha_mem, AS_PROGRAM, 16, bitgraph_state) ADDRESS_MAP_UNMAP_HIGH AM_RANGE(0x000000, 0x007fff) AM_ROM AM_RANGE(0x010000, 0x010001) AM_DEVREADWRITE8(ACIA0_TAG, acia6850_device, data_r, data_w, 0xff00) // HOST AM_RANGE(0x010002, 0x010003) AM_DEVREADWRITE8(ACIA0_TAG, acia6850_device, status_r, control_w, 0xff00) AM_RANGE(0x010008, 0x010009) AM_DEVREADWRITE8(ACIA1_TAG, acia6850_device, data_r, data_w, 0x00ff) // KEYBOARD AM_RANGE(0x01000a, 0x01000b) AM_DEVREADWRITE8(ACIA1_TAG, acia6850_device, status_r, control_w, 0x00ff) AM_RANGE(0x010010, 0x010011) AM_DEVREADWRITE8(ACIA2_TAG, acia6850_device, data_r, data_w, 0x00ff) // DEBUGGER AM_RANGE(0x010012, 0x010013) AM_DEVREADWRITE8(ACIA2_TAG, acia6850_device, status_r, control_w, 0x00ff) AM_RANGE(0x010018, 0x010019) AM_DEVREADWRITE8(ACIA3_TAG, acia6850_device, data_r, data_w, 0x00ff) // POINTER AM_RANGE(0x01001a, 0x01001b) AM_DEVREADWRITE8(ACIA3_TAG, acia6850_device, status_r, control_w, 0x00ff) AM_RANGE(0x010020, 0x010027) AM_READWRITE8(adlc_r, adlc_w, 0xff00) AM_RANGE(0x010028, 0x01002f) AM_READWRITE8(pia_r, pia_w, 0xff00) // EAROM, PSG AM_RANGE(0x010030, 0x010031) AM_WRITE(baud_write) AM_RANGE(0x3e0000, 0x3fffff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START(bitgraphb_mem, AS_PROGRAM, 16, bitgraph_state) ADDRESS_MAP_UNMAP_HIGH AM_RANGE(0x000000, 0x007fff) AM_ROM AM_RANGE(0x010000, 0x010001) AM_DEVREADWRITE8(ACIA0_TAG, acia6850_device, data_r, data_w, 0xff00) // HOST AM_RANGE(0x010002, 0x010003) AM_DEVREADWRITE8(ACIA0_TAG, acia6850_device, status_r, control_w, 0xff00) AM_RANGE(0x010008, 0x010009) AM_DEVREADWRITE8(ACIA1_TAG, acia6850_device, data_r, data_w, 0x00ff) // KEYBOARD AM_RANGE(0x01000a, 0x01000b) AM_DEVREADWRITE8(ACIA1_TAG, acia6850_device, status_r, control_w, 0x00ff) AM_RANGE(0x010010, 0x010011) AM_DEVREADWRITE8(ACIA2_TAG, acia6850_device, data_r, data_w, 0x00ff) // DEBUGGER AM_RANGE(0x010012, 0x010013) AM_DEVREADWRITE8(ACIA2_TAG, acia6850_device, status_r, control_w, 0x00ff) AM_RANGE(0x01001a, 0x01001b) AM_WRITE8(misccr_write, 0x00ff) AM_RANGE(0x010020, 0x010027) AM_READWRITE8(adlc_r, adlc_w, 0xff00) AM_RANGE(0x010028, 0x01002f) AM_READWRITE8(pia_r, pia_w, 0xff00) // EAROM, PSG AM_RANGE(0x010030, 0x010031) AM_WRITE(baud_write) // AM_RANGE(0x010030, 0x010037) AM_READ8(ppu_read, 0x00ff) // AM_RANGE(0x010038, 0x01003f) AM_WRITE8(ppu_write, 0x00ff) AM_RANGE(0x380000, 0x3fffff) AM_RAM ADDRESS_MAP_END static INPUT_PORTS_START(bitgraph) INPUT_PORTS_END READ8_MEMBER(bitgraph_state::pia_r) { DBG_LOG(3,"PIA", ("R %d\n", offset)); return m_pia->read(space, 3-offset); } WRITE8_MEMBER(bitgraph_state::pia_w) { DBG_LOG(3,"PIA", ("W %d < %02X\n", offset, data)); return m_pia->write(space, 3-offset, data); } READ_LINE_MEMBER(bitgraph_state::pia_ca1_r) { return m_screen->frame_number() & 1; } WRITE_LINE_MEMBER(bitgraph_state::pia_cb2_w) { // XXX shut up verbose log } READ8_MEMBER(bitgraph_state::pia_pa_r) { UINT8 data = BIT(m_pia_b, 3) ? m_earom->data() : m_pia_a; DBG_LOG(2,"PIA", ("A == %02X (%s)\n", data, BIT(m_pia_b, 3) ? "earom" : "pia")); return data; } WRITE8_MEMBER(bitgraph_state::pia_pa_w) { DBG_LOG(2,"PIA", ("A <- %02X\n", data)); m_pia_a = data; } /* B0 O: BC1 to noisemaker. B1 O: BDIR to noisemaker. B2 O: Clock for EAROM. B3 O: CS1 for EAROM. B4 O: Enable HDLC Xmt interrupt. B5 O: Enable HDLC Rcv interrupt. B6 O: Clear Clock interrupt. Must write a 0 [clear interrupt], then a 1. B7 I: EVEN field ?? */ READ8_MEMBER(bitgraph_state::pia_pb_r) { DBG_LOG(2,"PIA", ("B == %02X\n", m_pia_b)); return m_pia_b; } WRITE8_MEMBER(bitgraph_state::pia_pb_w) { DBG_LOG(2,"PIA", ("B <- %02X\n", data)); m_pia_b = data; switch (m_pia_b & 0x03) { case 2: m_psg->data_w(space, 0, m_pia_a); break; case 3: m_psg->address_w(space, 0, m_pia_a); break; } if (BIT(m_pia_b, 3)) { DBG_LOG(2,"EAROM", ("data <- %02X\n", m_pia_a)); m_earom->set_data(m_pia_a); } // CS1, ~CS2, C1, C2, CK m_earom->set_control(BIT(m_pia_b, 3), BIT(m_pia_b, 3), BIT(m_pia_a, 6), BIT(m_pia_a, 7), BIT(m_pia_b, 2)); if (!BIT(m_pia_b, 6)) { m_maincpu->set_input_line(M68K_IRQ_6, CLEAR_LINE); } } WRITE8_MEMBER(bitgraph_state::earom_write) { DBG_LOG(2,"EAROM", ("addr <- %02X (%02X)\n", data & 0x3f, data)); m_earom->set_address(data & 0x3f); } // written once and never changed WRITE8_MEMBER(bitgraph_state::misccr_write) { DBG_LOG(1,"MISCCR", ("<- %02X (DTR %d MAP %d)\n", data, BIT(data, 3), (data & 3))); m_misccr = data; } WRITE_LINE_MEMBER(bitgraph_state::system_clock_write) { if (!BIT(m_pia_b, 6)) { m_maincpu->set_input_line(M68K_IRQ_6, CLEAR_LINE); return; } if (state) { m_maincpu->set_input_line_and_vector(M68K_IRQ_6, ASSERT_LINE, M68K_INT_ACK_AUTOVECTOR); } else { m_maincpu->set_input_line(M68K_IRQ_6, CLEAR_LINE); } } WRITE16_MEMBER(bitgraph_state::baud_write) { DBG_LOG(1,"Baud", ("%04X\n", data)); m_dbrgb->str_w(data & 15); // 2 DBG m_dbrga->stt_w((data >> 4) & 15); // 1 KBD m_dbrgb->stt_w((data >> 8) & 15); // 3 PNT m_dbrga->str_w((data >> 12) & 15); // 0 HOST } WRITE_LINE_MEMBER(bitgraph_state::com8116_a_fr_w) { m_acia0->write_txc(state); m_acia0->write_rxc(state); } WRITE_LINE_MEMBER(bitgraph_state::com8116_a_ft_w) { m_acia1->write_txc(state); m_acia1->write_rxc(state); } WRITE_LINE_MEMBER(bitgraph_state::com8116_b_fr_w) { m_acia2->write_txc(state); m_acia2->write_rxc(state); } WRITE_LINE_MEMBER(bitgraph_state::com8116_b_ft_w) { if (m_acia3) { m_acia3->write_txc(state); m_acia3->write_rxc(state); } } READ8_MEMBER(bitgraph_state::adlc_r) { DBG_LOG(1,"ADLC", ("R %d\n", offset)); return m_adlc ? m_adlc->read(space, 3-offset) : 0xff; } WRITE8_MEMBER(bitgraph_state::adlc_w) { DBG_LOG(1,"ADLC", ("W %d < %02X\n", offset, data)); if (m_adlc) return m_adlc->write(space, 3-offset, data); } UINT32 bitgraph_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { UINT8 gfx=0; int x,y; for (y = 0; y < 768; y++) { UINT16 *p = &bitmap.pix16(y); for (x = 0; x < 1024/8; x+=2) { gfx = m_videoram[ (x+1) | (y<<7)]; *p++ = BIT(gfx, 7); *p++ = BIT(gfx, 6); *p++ = BIT(gfx, 5); *p++ = BIT(gfx, 4); *p++ = BIT(gfx, 3); *p++ = BIT(gfx, 2); *p++ = BIT(gfx, 1); *p++ = BIT(gfx, 0); gfx = m_videoram[ x | (y<<7)]; *p++ = BIT(gfx, 7); *p++ = BIT(gfx, 6); *p++ = BIT(gfx, 5); *p++ = BIT(gfx, 4); *p++ = BIT(gfx, 3); *p++ = BIT(gfx, 2); *p++ = BIT(gfx, 1); *p++ = BIT(gfx, 0); } } return 0; } READ8_MEMBER(bitgraph_state::ppu_read) { UINT8 data = m_ppu[offset]; DBG_LOG(1,"PPU", ("%d == %02X\n", offset, data)); return data; } WRITE8_MEMBER(bitgraph_state::ppu_write) { DBG_LOG(1,"PPU", ("%d <- %02X\n", offset, data)); m_ppu[offset] = data; } #ifdef UNUSED_FUNCTION static ADDRESS_MAP_START(ppu_io, AS_IO, 8, bitgraph_state) // AM_RANGE(0x00, 0x00) AM_READ(ppu_irq) // AM_RANGE(MCS48_PORT_P1, MCS48_PORT_P1) // AM_RANGE(MCS48_PORT_T0, MCS48_PORT_T0) AM_READ(ppu_t0_r) AM_RANGE(MCS48_PORT_PROG, MCS48_PORT_PROG) AM_DEVWRITE("i8243", i8243_device, i8243_prog_w) ADDRESS_MAP_END #endif /* p4 O: Centronics data 3..0 p5 O: Centronics data 7..4 p6 O: Centronics control p7 I: Centronics status */ WRITE8_MEMBER(bitgraph_state::ppu_i8243_w) { DBG_LOG(1,"PPU", ("8243 %d <- %02X\n", offset + 4, data)); switch (offset) { case 0: m_centronics->write_data0(BIT(data, 0)); m_centronics->write_data1(BIT(data, 1)); m_centronics->write_data2(BIT(data, 2)); m_centronics->write_data3(BIT(data, 3)); break; case 1: m_centronics->write_data4(BIT(data, 0)); m_centronics->write_data5(BIT(data, 1)); m_centronics->write_data6(BIT(data, 2)); m_centronics->write_data7(BIT(data, 3)); break; case 2: m_centronics->write_strobe(BIT(data, 0)); // 1: Paper instruction m_centronics->write_init(BIT(data, 2)); break; case 3: m_centronics->write_ack(BIT(data, 0)); m_centronics->write_busy(BIT(data, 1)); m_centronics->write_perror(BIT(data, 2)); m_centronics->write_select(BIT(data, 3)); break; } } void bitgraph_state::machine_start() { m_videoram = (UINT8 *)m_maincpu->space(AS_PROGRAM).get_write_ptr(0x3e0000); } void bitgraph_state::machine_reset() { m_maincpu->reset(); m_misccr = 0; m_pia_a = 0; m_pia_b = 0; memset(m_ppu, 0, sizeof(m_ppu)); } static MACHINE_CONFIG_FRAGMENT( bg_motherboard ) MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(40) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */ MCFG_SCREEN_SIZE(1024, 768) MCFG_SCREEN_VISIBLE_AREA(0, 1024-1, 0, 768-1) MCFG_SCREEN_UPDATE_DRIVER(bitgraph_state, screen_update) MCFG_SCREEN_PALETTE("palette") MCFG_PALETTE_ADD_MONOCHROME("palette") MCFG_DEVICE_ADD(ACIA0_TAG, ACIA6850, 0) MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE(RS232_H_TAG, rs232_port_device, write_txd)) MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE(RS232_H_TAG, rs232_port_device, write_rts)) MCFG_ACIA6850_IRQ_HANDLER(DEVWRITELINE(M68K_TAG, m68000_device, write_irq1)) MCFG_RS232_PORT_ADD(RS232_H_TAG, default_rs232_devices, "null_modem") MCFG_RS232_RXD_HANDLER(DEVWRITELINE(ACIA0_TAG, acia6850_device, write_rxd)) MCFG_RS232_DCD_HANDLER(DEVWRITELINE(ACIA0_TAG, acia6850_device, write_dcd)) MCFG_RS232_CTS_HANDLER(DEVWRITELINE(ACIA0_TAG, acia6850_device, write_cts)) MCFG_DEVICE_ADD(ACIA1_TAG, ACIA6850, 0) MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE(RS232_K_TAG, rs232_port_device, write_txd)) MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE(RS232_K_TAG, rs232_port_device, write_rts)) MCFG_ACIA6850_IRQ_HANDLER(DEVWRITELINE(M68K_TAG, m68000_device, write_irq1)) MCFG_RS232_PORT_ADD(RS232_K_TAG, default_rs232_devices, "keyboard") MCFG_RS232_RXD_HANDLER(DEVWRITELINE(ACIA1_TAG, acia6850_device, write_rxd)) MCFG_RS232_DCD_HANDLER(DEVWRITELINE(ACIA1_TAG, acia6850_device, write_dcd)) MCFG_RS232_CTS_HANDLER(DEVWRITELINE(ACIA1_TAG, acia6850_device, write_cts)) MCFG_DEVICE_ADD(ACIA2_TAG, ACIA6850, 0) MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE(RS232_D_TAG, rs232_port_device, write_txd)) MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE(RS232_D_TAG, rs232_port_device, write_rts)) MCFG_ACIA6850_IRQ_HANDLER(DEVWRITELINE(M68K_TAG, m68000_device, write_irq1)) MCFG_RS232_PORT_ADD(RS232_D_TAG, default_rs232_devices, nullptr) MCFG_RS232_RXD_HANDLER(DEVWRITELINE(ACIA2_TAG, acia6850_device, write_rxd)) MCFG_RS232_DCD_HANDLER(DEVWRITELINE(ACIA2_TAG, acia6850_device, write_dcd)) MCFG_RS232_CTS_HANDLER(DEVWRITELINE(ACIA2_TAG, acia6850_device, write_cts)) // XXX actual part may be something else MCFG_DEVICE_ADD(COM8116_A_TAG, COM8116, XTAL_5_0688MHz) MCFG_COM8116_FR_HANDLER(WRITELINE(bitgraph_state, com8116_a_fr_w)) MCFG_COM8116_FT_HANDLER(WRITELINE(bitgraph_state, com8116_a_ft_w)) MCFG_DEVICE_ADD(COM8116_B_TAG, COM8116, XTAL_5_0688MHz) MCFG_COM8116_FR_HANDLER(WRITELINE(bitgraph_state, com8116_b_fr_w)) MCFG_COM8116_FT_HANDLER(WRITELINE(bitgraph_state, com8116_b_ft_w)) MCFG_DEVICE_ADD(PIA_TAG, PIA6821, 0) MCFG_PIA_READCA1_HANDLER(READLINE(bitgraph_state, pia_ca1_r)) MCFG_PIA_CB2_HANDLER(WRITELINE(bitgraph_state, pia_cb2_w)) MCFG_PIA_READPA_HANDLER(READ8(bitgraph_state, pia_pa_r)) MCFG_PIA_WRITEPA_HANDLER(WRITE8(bitgraph_state, pia_pa_w)) MCFG_PIA_READPB_HANDLER(READ8(bitgraph_state, pia_pb_r)) MCFG_PIA_WRITEPB_HANDLER(WRITE8(bitgraph_state, pia_pb_w)) MCFG_ER2055_ADD(EAROM_TAG) MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_SOUND_ADD(PSG_TAG, AY8912, XTAL_1_2944MHz) MCFG_AY8910_PORT_A_WRITE_CB(WRITE8(bitgraph_state, earom_write)) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00) MACHINE_CONFIG_END #ifdef UNUSED_FUNCTION static MACHINE_CONFIG_FRAGMENT( bg_ppu ) MCFG_CPU_ADD(PPU_TAG, I8035, XTAL_6_9MHz) MCFG_CPU_IO_MAP(ppu_io) MCFG_I8243_ADD("i8243", NOOP, WRITE8(bitgraph_state, ppu_i8243_w)) MCFG_CENTRONICS_ADD("centronics", centronics_devices, "printer") MCFG_CENTRONICS_ACK_HANDLER(DEVWRITELINE("cent_status_in", input_buffer_device, write_bit6)) MCFG_CENTRONICS_BUSY_HANDLER(DEVWRITELINE("cent_status_in", input_buffer_device, write_bit7)) MCFG_CENTRONICS_FAULT_HANDLER(DEVWRITELINE("cent_status_in", input_buffer_device, write_bit4)) MCFG_CENTRONICS_PERROR_HANDLER(DEVWRITELINE("cent_status_in", input_buffer_device, write_bit5)) MCFG_DEVICE_ADD("cent_status_in", INPUT_BUFFER, 0) MCFG_CENTRONICS_OUTPUT_LATCH_ADD("cent_data_out", "centronics") MACHINE_CONFIG_END #endif static MACHINE_CONFIG_START( bitgrpha, bitgraph_state ) MCFG_CPU_ADD(M68K_TAG, M68000, XTAL_6_9MHz) MCFG_CPU_PROGRAM_MAP(bitgrapha_mem) MCFG_FRAGMENT_ADD(bg_motherboard) MCFG_DEVICE_ADD("system_clock", CLOCK, 40) MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(bitgraph_state, system_clock_write)) MCFG_DEVICE_ADD(ACIA3_TAG, ACIA6850, 0) MCFG_ACIA6850_TXD_HANDLER(DEVWRITELINE(RS232_M_TAG, rs232_port_device, write_txd)) MCFG_ACIA6850_RTS_HANDLER(DEVWRITELINE(RS232_M_TAG, rs232_port_device, write_rts)) MCFG_ACIA6850_IRQ_HANDLER(DEVWRITELINE(M68K_TAG, m68000_device, write_irq1)) MCFG_RS232_PORT_ADD(RS232_M_TAG, default_rs232_devices, nullptr) MCFG_RS232_RXD_HANDLER(DEVWRITELINE(ACIA3_TAG, acia6850_device, write_rxd)) MCFG_RS232_DCD_HANDLER(DEVWRITELINE(ACIA3_TAG, acia6850_device, write_dcd)) MCFG_RS232_CTS_HANDLER(DEVWRITELINE(ACIA3_TAG, acia6850_device, write_cts)) MCFG_DEFAULT_LAYOUT(layout_bitgrpha) MCFG_RAM_ADD(RAM_TAG) MCFG_RAM_DEFAULT_SIZE("128K") MACHINE_CONFIG_END static MACHINE_CONFIG_START( bitgrphb, bitgraph_state ) MCFG_CPU_ADD(M68K_TAG, M68000, XTAL_6_9MHz) MCFG_CPU_PROGRAM_MAP(bitgraphb_mem) MCFG_FRAGMENT_ADD(bg_motherboard) // MCFG_FRAGMENT_ADD(bg_ppu) MCFG_DEVICE_ADD("system_clock", CLOCK, 1040) MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(bitgraph_state, system_clock_write)) MCFG_DEFAULT_LAYOUT(layout_bitgrphb) MCFG_RAM_ADD(RAM_TAG) MCFG_RAM_DEFAULT_SIZE("512K") MACHINE_CONFIG_END /* ROM definition */ ROM_START( bitgrpha ) ROM_REGION16_BE( 0x8000, M68K_TAG, 0 ) ROM_LOAD( "bg125.rom", 0x000000, 0x008000, CRC(b86c974e) SHA1(5367db80a856444c2a55de22b69a13f97a62f602)) ROM_FILL( 0x38e4, 1, 0x4e ) // disable clksync() ROM_FILL( 0x38e5, 1, 0x75 ) ROM_END ROM_START( bitgrphb ) ROM_REGION16_BE( 0x8000, M68K_TAG, 0 ) ROM_DEFAULT_BIOS("2.33A") ROM_SYSTEM_BIOS(0, "2.33A", "rev 2.33 Alpha' ROM") ROMX_LOAD( "bg2.32lo_u10.bin", 0x004001, 0x002000, CRC(6a702a96) SHA1(acdf1ba34038b4ccafb5b8069e70ae57a3b8a7e0), ROM_BIOS(1)|ROM_SKIP(1)) ROMX_LOAD( "bg2.32hi_u12.bin", 0x004000, 0x002000, CRC(a282a2c8) SHA1(ea7e4d4e197201c8944acef54479d5c2b26d409f), ROM_BIOS(1)|ROM_SKIP(1)) ROMX_LOAD( "bg2.32lo_u11.bin", 0x000001, 0x002000, CRC(46912afd) SHA1(c1f771adc1ef62b1fb1b904ed1d2a61009e24f55), ROM_BIOS(1)|ROM_SKIP(1)) ROMX_LOAD( "bg2.32hi_u13.bin", 0x000000, 0x002000, CRC(731df44f) SHA1(8c238b5943b8864e539f92891a0ffa6ddd4fc779), ROM_BIOS(1)|ROM_SKIP(1)) ROM_SYSTEM_BIOS(1, "3.0P", "rev 3.0P ROM") ROMX_LOAD( "bg5173_u10.bin", 0x004001, 0x002000, CRC(40014850) SHA1(ef0b7da58a5183391a3a03947882197f25694518), ROM_BIOS(2)|ROM_SKIP(1)) ROMX_LOAD( "bg5175_u12.bin", 0x004000, 0x002000, CRC(c2c4cc6c) SHA1(dbbce7cb58b4cef1557a834cbb07b3ace298cb8b), ROM_BIOS(2)|ROM_SKIP(1)) ROMX_LOAD( "bg5174_u11.bin", 0x000001, 0x002000, CRC(639768b9) SHA1(68f623bcf3bb75390ba2b17efc067cf25f915ec0), ROM_BIOS(2)|ROM_SKIP(1)) ROMX_LOAD( "bg5176_u13.bin", 0x000000, 0x002000, CRC(984e7e8c) SHA1(dd13cbaff96a8b9936ae8cb07205c6abe8b27b6e), ROM_BIOS(2)|ROM_SKIP(1)) ROM_SYSTEM_BIOS(2, "ramtest", "RAM test") ROMX_LOAD( "ramtest.rom", 0x000000, 0x004000, CRC(fabe3b34) SHA1(4d892a2ed2b7ea12d83843609981be9069611d43), ROM_BIOS(3)) ROM_REGION( 0x800, PPU_TAG, 0 ) ROM_LOAD( "bg_mouse_u9.bin", 0x0000, 0x0800, CRC(fd827ff5) SHA1(6d4a8e9b18c7610c5cfde40464826d144d387601)) ROM_END /* Driver */ /* YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS */ COMP( 1981, bitgrpha, 0, 0, bitgrpha, bitgraph, driver_device, 0, "BBN", "BitGraph rev A", MACHINE_IMPERFECT_KEYBOARD) COMP( 1982, bitgrphb, 0, 0, bitgrphb, bitgraph, driver_device, 0, "BBN", "BitGraph rev B", MACHINE_NOT_WORKING|MACHINE_IMPERFECT_KEYBOARD)
RJRetro/mame
src/mame/drivers/bitgraph.cpp
C++
gpl-2.0
21,416
/* Copyright (C) 2007, 2010 - Bit-Blot This file is part of Aquaria. Aquaria is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "Quad.h" OutlineRect::OutlineRect() : RenderObject() { lineSize = 1; renderCenter = false; } void OutlineRect::setWidthHeight(int w, int h) { this->w = w; this->h = h; w2 = w/2; h2 = h/2; } void OutlineRect::setLineSize(int ls) { lineSize = ls; } void OutlineRect::onRender() { #ifdef BBGE_BUILD_OPENGL glLineWidth(lineSize); glBegin(GL_LINES); // l glVertex2f(-w2,-h2); glVertex2f(-w2,h2); // r glVertex2f(w2,-h2); glVertex2f(w2,h2); // u glVertex2f(-w2,-h2); glVertex2f(w2,-h2); // d glVertex2f(-w2,h2); glVertex2f(w2,h2); glEnd(); if (renderCenter) { glColor3f(0.9, 0.9, 1); glBegin(GL_LINES); // lr glVertex2f(-w2,0); glVertex2f(w2,0); // ud glVertex2f(0,-h2); glVertex2f(0,h2); glEnd(); } #endif }
chewi/Aquaria
BBGE/RenderRect.cpp
C++
gpl-2.0
1,528