code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// // ooSocket.c WJ112 // /* * Copyright (c) 2014, Walter de Jong * All rights reserved. * * 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. * * 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. * */ #include "oo/Sock.h" #include "oo/print.h" #include <cerrno> #include <cstring> #include <netdb.h> #include <sys/types.h> namespace oo { int Sock::getprotobyname(const char *name) { if (name == nullptr) { name = "tcp"; } struct protoent *proto = ::getprotobyname(name); if (proto == nullptr) { return -1; } return proto->p_proto; } int Sock::getservbyname(const char *name, const char *proto) { if (name == nullptr) { throw ReferenceError(); } if (proto == nullptr) { proto = "tcp"; } struct servent *serv = ::getservbyname(name, proto); if (!serv) { // maybe it's just a numeric string int port; try { port = convert<int>(name); } catch(ValueError err) { return -1; } if (port <= 0) { // invalid port number return -1; // should we throw ValueError instead? } return port; } return ntohs(serv->s_port); } String Sock::getservbyport(int port, const char *proto) { if (proto == nullptr) { proto = "tcp"; } struct servent *serv = ::getservbyport(htons(port), proto); if (!serv) { return String(""); } return String(serv->s_proto); } bool Sock::listen(const char *serv) { int sock = ::socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { throw IOError("failed to create socket"); } // set option reuse bind address int on = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #ifdef SO_REUSEPORT int on2 = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #endif struct sockaddr_in sa; std::memset(&sa, 0, sizeof(struct sockaddr_in)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; int port = this->getservbyname(serv); if (port == -1) { ::close(sock); throw IOError("failed to listen, service unknown"); } sa.sin_port = htons(port); socklen_t sa_len = sizeof(struct sockaddr_in); if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) { ::close(sock); throw IOError("failed to bind socket"); } if (::listen(sock, SOMAXCONN) == -1) { ::close(sock); throw IOError("failed to listen on socket"); } if (!f_.open(sock, "rw")) { ::close(sock); throw IOError("failed to tie socket to a stream"); } return true; } bool Sock::listen6(const char *serv) { int sock = ::socket(AF_INET6, SOCK_STREAM, 0); if (sock == -1) { throw IOError("failed to create socket"); } // set option reuse bind address int on = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #ifdef SO_REUSEPORT int on2 = 1; if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) { ::close(sock); throw IOError("failed to set socket option"); } #endif struct sockaddr_in6 sa; std::memset(&sa, 0, sizeof(struct sockaddr_in6)); sa.sin6_family = AF_INET6; sa.sin6_addr = in6addr_any; int port = this->getservbyname(serv); if (port == -1) { ::close(sock); throw IOError("failed to listen, service unknown"); } sa.sin6_port = htons(port); socklen_t sa_len = sizeof(struct sockaddr_in6); if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) { ::close(sock); throw IOError("failed to bind socket"); } if (::listen(sock, SOMAXCONN) == -1) { ::close(sock); throw IOError("failed to listen on socket"); } if (!f_.open(sock, "rw")) { ::close(sock); throw IOError("failed to tie socket to a stream"); } return true; } bool Sock::connect(const char *ipaddr, const char *serv) { if (ipaddr == nullptr) { throw ReferenceError(); } if (serv == nullptr) { throw ReferenceError(); } if (!this->isclosed()) { throw IOError("socket is already in use"); } struct addrinfo hints, *res; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; // IPv4, IPv6, or any other protocol hints.ai_socktype = SOCK_STREAM; if (::getaddrinfo(ipaddr, serv, &hints, &res) != 0) { throw IOError("failed to get address info"); } int sock = -1; // try connecting, try out all protocols for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) { if ((sock = ::socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1) { continue; } if (::connect(sock, r->ai_addr, r->ai_addrlen) == -1) { ::close(sock); sock = -1; continue; } break; // successful connect } freeaddrinfo(res); if (sock == -1) { throw IOError("failed to connect to remote host"); } // tie it to a stream if (!f_.open(sock, "w+")) { ::close(sock); sock = -1; throw IOError("failed to open socket as a stream"); } return true; } Sock Sock::accept(void) const { if (this->isclosed()) { throw IOError("accept() called on a non-listening socket"); } Sock sock; struct sockaddr_storage addr; socklen_t addr_len = sizeof(struct sockaddr_storage); int sockfd; for(;;) { sockfd = ::accept(f_.fileno(), (struct sockaddr *)&addr, &addr_len); if (sockfd == -1) { if (errno == EINTR) { continue; } return Sock(); } break; } if (!sock.f_.open(sockfd, "w+")) { return Sock(); } return sock; } String Sock::remoteaddr(void) const { if (this->isclosed()) { throw IOError("can not get remote address of an unconnected socket"); } struct sockaddr_storage addr; socklen_t addr_len = sizeof(struct sockaddr_storage); if (::getpeername(f_.fileno(), (struct sockaddr *)&addr, &addr_len) == -1) { throw IOError("failed to get remote address of socket"); } char host[NI_MAXHOST]; if (::getnameinfo((struct sockaddr *)&addr, addr_len, host, sizeof(host), nullptr, 0, NI_NUMERICHOST|NI_NUMERICSERV) == -1) { throw IOError("failed to get numeric address of remote host"); } return String(host); } Sock listen(const char *serv) { Sock sock; if (!sock.listen(serv)) { return Sock(); } return sock; } Sock listen6(const char *serv) { Sock sock; if (!sock.listen6(serv)) { return Sock(); } return sock; } Sock connect(const char *ipaddr, const char *serv) { Sock sock; if (!sock.connect(ipaddr, serv)) { return Sock(); } return sock; } String resolv(const String& ipaddr) { if (ipaddr.empty()) { throw ValueError(); } struct addrinfo *res; if (::getaddrinfo(ipaddr.c_str(), nullptr, nullptr, &res) != 0) { // probably invalid IP address return ipaddr; } char host[NI_MAXHOST]; for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) { if (::getnameinfo(r->ai_addr, r->ai_addrlen, host, sizeof(host), nullptr, 0, 0) == 0) { freeaddrinfo(res); return String(host); } } // some kind of error // print("TD error: %s", ::gai_strerror(err)); freeaddrinfo(res); return ipaddr; } void fprint(Sock& sock, const char *fmt, ...) { if (fmt == nullptr) { throw ReferenceError(); } if (!*fmt) { return; } std::va_list ap; va_start(ap, fmt); vfprint(sock, fmt, ap); va_end(ap); } void vfprint(Sock& sock, const char *fmt, std::va_list ap) { if (fmt == nullptr) { throw ReferenceError(); } std::stringstream ss; vssprint(ss, fmt, ap); sock.write(ss.str()); } } // namespace // EOB
walterdejong/oolib
src/Sock.cpp
C++
bsd-2-clause
8,549
// Copyright 2013 Yangqing Jia #include <algorithm> #include <cmath> #include <cfloat> #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/io.hpp" #define C_ 1 using std::max; namespace caffe { const float kLOG_THRESHOLD = 1e-20; template <typename Dtype> void MultinomialLogisticLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); } template <typename Dtype> Dtype MultinomialLogisticLossLayer<Dtype>::Backward_cpu( const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* bottom_data = (*bottom)[0]->cpu_data(); const Dtype* bottom_label = (*bottom)[1]->cpu_data(); Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); int num = (*bottom)[0]->num(); int dim = (*bottom)[0]->count() / (*bottom)[0]->num(); memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count()); Dtype loss = 0; for (int i = 0; i < num; ++i) { int label = static_cast<int>(bottom_label[i]); Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD)); loss -= log(prob); bottom_diff[i * dim + label] = - 1. / prob / num; } return loss / num; } // TODO: implement the GPU version for multinomial loss template <typename Dtype> void InfogainLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); BlobProto blob_proto; ReadProtoFromBinaryFile(this->layer_param_.source(), &blob_proto); infogain_.FromProto(blob_proto); CHECK_EQ(infogain_.num(), 1); CHECK_EQ(infogain_.channels(), 1); CHECK_EQ(infogain_.height(), infogain_.width()); } template <typename Dtype> Dtype InfogainLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* bottom_data = (*bottom)[0]->cpu_data(); const Dtype* bottom_label = (*bottom)[1]->cpu_data(); const Dtype* infogain_mat = infogain_.cpu_data(); Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); int num = (*bottom)[0]->num(); int dim = (*bottom)[0]->count() / (*bottom)[0]->num(); CHECK_EQ(infogain_.height(), dim); Dtype loss = 0; for (int i = 0; i < num; ++i) { int label = static_cast<int>(bottom_label[i]); for (int j = 0; j < dim; ++j) { Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD)); loss -= infogain_mat[label * dim + j] * log(prob); bottom_diff[i * dim + j] = - infogain_mat[label * dim + j] / prob / num; } } return loss / num; } template <typename Dtype> void EuclideanLossLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[0]->channels(), bottom[1]->channels()); CHECK_EQ(bottom[0]->height(), bottom[1]->height()); CHECK_EQ(bottom[0]->width(), bottom[1]->width()); difference_.Reshape(bottom[0]->num(), bottom[0]->channels(), bottom[0]->height(), bottom[0]->width()); } template <typename Dtype> Dtype EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { int count = (*bottom)[0]->count(); int num = (*bottom)[0]->num(); caffe_sub(count, (*bottom)[0]->cpu_data(), (*bottom)[1]->cpu_data(), difference_.mutable_cpu_data()); Dtype loss = caffe_cpu_dot( count, difference_.cpu_data(), difference_.cpu_data()) / num / Dtype(2); // Compute the gradient caffe_axpby(count, Dtype(1) / num, difference_.cpu_data(), Dtype(0), (*bottom)[0]->mutable_cpu_diff()); return loss; } template <typename Dtype> void AccuracyLayer<Dtype>::SetUp( const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Accuracy Layer takes two blobs as input."; CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output."; CHECK_EQ(bottom[0]->num(), bottom[1]->num()) << "The data and label should have the same number."; CHECK_EQ(bottom[1]->channels(), 1); CHECK_EQ(bottom[1]->height(), 1); CHECK_EQ(bottom[1]->width(), 1); (*top)[0]->Reshape(1, 2, 1, 1); } template <typename Dtype> void AccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Dtype accuracy = 0; Dtype logprob = 0; const Dtype* bottom_data = bottom[0]->cpu_data(); const Dtype* bottom_label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int dim = bottom[0]->count() / bottom[0]->num(); for (int i = 0; i < num; ++i) { // Accuracy Dtype maxval = -FLT_MAX; int max_id = 0; for (int j = 0; j < dim; ++j) { if (bottom_data[i * dim + j] > maxval) { maxval = bottom_data[i * dim + j]; max_id = j; } } //LOG(INFO) << " max_id: " << max_id << " label: " << static_cast<int>(bottom_label[i]); if (max_id == static_cast<int>(bottom_label[i])) { ++accuracy; } Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])], Dtype(kLOG_THRESHOLD)); logprob -= log(prob); } // LOG(INFO) << "classes: " << num; (*top)[0]->mutable_cpu_data()[0] = accuracy / num; (*top)[0]->mutable_cpu_data()[1] = logprob / num; } template <typename Dtype> void HingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Hinge Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Hinge Loss Layer takes no output."; } template <typename Dtype> void HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int count = bottom[0]->count(); int dim = count / num; caffe_copy(count, bottom_data, bottom_diff); if(0) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) LOG(INFO) << bottom_data[i * dim + j]; LOG(INFO) << "*************ONE PASS*****************"; } for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; //LOG(INFO) << bottom_diff[i * dim + static_cast<int>(label[i])]; } for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { //LOG(INFO) << bottom_diff[i * dim + j]; bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]); //if(bottom_diff[i*dim+j] != 1) //LOG(INFO) << bottom_diff[i*dim+j]; } } } template <typename Dtype> Dtype HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); const Dtype* label = (*bottom)[1]->cpu_data(); int num = (*bottom)[0]->num(); int count = (*bottom)[0]->count(); int dim = count / num; Dtype loss = caffe_cpu_asum(count, bottom_diff) / num; caffe_cpu_sign(count, bottom_diff, bottom_diff); for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } caffe_scal(count, Dtype(1. / num), bottom_diff); //LOG(INFO) << "loss" << loss; return loss; } //**********************SquaredHingeLoss********************** template <typename Dtype> void SquaredHingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 2) << "Squared Hinge Loss Layer takes two blobs as input."; CHECK_EQ(top->size(), 0) << "Squared Hinge Loss Layer takes no output."; } template <typename Dtype> void SquaredHingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const Dtype* label = bottom[1]->cpu_data(); int num = bottom[0]->num(); int count = bottom[0]->count(); int dim = count / num; caffe_copy(count, bottom_data, bottom_diff); //Debug if(0) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { LOG(INFO) << bottom_data[i * dim + j]; } LOG(INFO) << "*************ONE PASS*****************"; } for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; //LOG(INFO) << static_cast<int>(label[i]); } for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { //LOG(INFO) << bottom_diff[i * dim + j]; bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]); //if(bottom_diff[i*dim+j] != 1) //LOG(INFO) << bottom_diff[i*dim+j]; } } } template <typename Dtype> Dtype SquaredHingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); const Dtype* label = (*bottom)[1]->cpu_data(); int num = (*bottom)[0]->num(); int count = (*bottom)[0]->count(); int dim = count / num; Dtype loss = caffe_cpu_dot(count, bottom_diff, bottom_diff) / num; for (int i = 0; i < num; ++i) { bottom_diff[i * dim + static_cast<int>(label[i])] *= -1; } caffe_scal(count, Dtype(2.* C_ / num), bottom_diff); //LOG(INFO) << "loss" << loss; return loss; } INSTANTIATE_CLASS(MultinomialLogisticLossLayer); INSTANTIATE_CLASS(InfogainLossLayer); INSTANTIATE_CLASS(EuclideanLossLayer); INSTANTIATE_CLASS(AccuracyLayer); INSTANTIATE_CLASS(HingeLossLayer); INSTANTIATE_CLASS(SquaredHingeLossLayer); } // namespace caffe
PeterPan1990/DSN
src/caffe/layers/loss_layer.cpp
C++
bsd-2-clause
10,973
#ifndef _CONVOUTPUT_SPH_H_ #define _CONVOUTPUT_SPH_H_ /* ################################################################################### # # CDMlib - Cartesian Data Management library # # Copyright (c) 2013-2017 Advanced Institute for Computational Science (AICS), RIKEN. # All rights reserved. # # Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University. # All rights reserved. # ################################################################################### */ /** * @file convOutput_SPH.h * @brief convOutput_SPH Class Header * @author aics * @date 2013/11/7 */ #include "convOutput.h" class convOutput_SPH : public convOutput { public: /** コンストラクタ */ convOutput_SPH(); /** デストラクタ */ ~convOutput_SPH(); public: /** * @brief 出力ファイルをオープンする * @param [in] prefix ファイル接頭文字 * @param [in] step ステップ数 * @param [in] id ランク番号 * @param [in] mio 出力時の分割指定  true = local / false = gather(default) */ cdm_FILE* OutputFile_Open( const std::string prefix, const unsigned step, const int id, const bool mio); /** * @brief sphファイルのheaderの書き込み * @param[in] step ステップ数 * @param[in] dim 変数の個数 * @param[in] d_type データ型タイプ * @param[in] imax x方向ボクセルサイズ * @param[in] jmax y方向ボクセルサイズ * @param[in] kmax z方向ボクセルサイズ * @param[in] time 時間 * @param[in] org 原点座標 * @param[in] pit ピッチ * @param[in] prefix ファイル接頭文字 * @param[in] pFile 出力ファイルポインタ */ bool WriteHeaderRecord(int step, int dim, CDM::E_CDM_DTYPE d_type, int imax, int jmax, int kmax, double time, double* org, double* pit, const std::string prefix, cdm_FILE *pFile); /** * @brief マーカーの書き込み * @param[in] dmy マーカー * @param[in] pFile 出力ファイルポインタ * @param[in] out plot3d用 */ bool WriteDataMarker(int dmy, cdm_FILE* pFile, bool out); protected: }; #endif // _CONVOUTPUT_SPH_H_
avr-aics-riken/CDMlib
tools/fconv/include/convOutput_SPH.h
C
bsd-2-clause
2,523
#ifndef CRYPTOPP_CONFIG_H #define CRYPTOPP_CONFIG_H #ifdef __GNUC__ #define VC_INLINE static inline __attribute__((always_inline)) #elif defined (_MSC_VER) #define VC_INLINE __forceinline #else #define VC_INLINE static inline #endif #ifdef __GNUC__ #define CRYPTOPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif // Apple and LLVM's Clang. Apple Clang version 7.0 roughly equals LLVM Clang version 3.7 #if defined(__clang__ ) && !defined(__apple_build_version__) #define CRYPTOPP_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) #elif defined(__clang__ ) && defined(__apple_build_version__) #define CRYPTOPP_APPLE_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) #endif // Clang due to "Inline assembly operands don't work with .intel_syntax", http://llvm.org/bugs/show_bug.cgi?id=24232 // TODO: supply the upper version when LLVM fixes it. We set it to 20.0 for compilation purposes. #if (defined(CRYPTOPP_CLANG_VERSION) && CRYPTOPP_CLANG_VERSION <= 200000) || (defined(CRYPTOPP_APPLE_CLANG_VERSION) && CRYPTOPP_APPLE_CLANG_VERSION <= 200000) #define CRYPTOPP_DISABLE_INTEL_ASM 1 #endif #ifndef CRYPTOPP_L1_CACHE_LINE_SIZE // This should be a lower bound on the L1 cache line size. It's used for defense against timing attacks. // Also see http://stackoverflow.com/questions/794632/programmatically-get-the-cache-line-size. #if defined(_M_X64) || defined(__x86_64__) || (__ILP32__ >= 1) #define CRYPTOPP_L1_CACHE_LINE_SIZE 64 #else // L1 cache line size is 32 on Pentium III and earlier #define CRYPTOPP_L1_CACHE_LINE_SIZE 32 #endif #endif #if defined(_MSC_VER) && (_MSC_VER > 1200) #define CRYPTOPP_MSVC6PP_OR_LATER #endif #ifndef CRYPTOPP_ALIGN_DATA #if defined(_MSC_VER) #define CRYPTOPP_ALIGN_DATA(x) __declspec(align(x)) #elif defined(__GNUC__) #define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x))) #else #define CRYPTOPP_ALIGN_DATA(x) #endif #endif #ifndef CRYPTOPP_SECTION_ALIGN16 #if defined(__GNUC__) && !defined(__APPLE__) // the alignment attribute doesn't seem to work without this section attribute when -fdata-sections is turned on #define CRYPTOPP_SECTION_ALIGN16 __attribute__((section ("CryptoPP_Align16"))) #else #define CRYPTOPP_SECTION_ALIGN16 #endif #endif #if defined(_MSC_VER) || defined(__fastcall) #define CRYPTOPP_FASTCALL __fastcall #else #define CRYPTOPP_FASTCALL #endif #ifdef CRYPTOPP_DISABLE_X86ASM // for backwards compatibility: this macro had both meanings #define CRYPTOPP_DISABLE_ASM #define CRYPTOPP_DISABLE_SSE2 #endif // Apple's Clang prior to 5.0 cannot handle SSE2 (and Apple does not use LLVM Clang numbering...) #if defined(CRYPTOPP_APPLE_CLANG_VERSION) && (CRYPTOPP_APPLE_CLANG_VERSION < 50000) # define CRYPTOPP_DISABLE_ASM #endif #if !defined(CRYPTOPP_DISABLE_ASM) && ((defined(_MSC_VER) && defined(_M_IX86)) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))) // C++Builder 2010 does not allow "call label" where label is defined within inline assembly #define CRYPTOPP_X86_ASM_AVAILABLE #if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__)) #define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1 #else #define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 0 #endif // SSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed. // GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version. Also see the output of // `gcc -dM -E -march=native - < /dev/null | grep -i SSE` for preprocessor defines available. #if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1400 || CRYPTOPP_GCC_VERSION >= 40102 || defined(__SSSE3__) || defined(__SSE3__)) #define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 1 #else #define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 0 #endif #endif #if !defined(CRYPTOPP_DISABLE_ASM) && defined(_MSC_VER) && defined(_M_X64) #define CRYPTOPP_X64_MASM_AVAILABLE #endif #if !defined(CRYPTOPP_DISABLE_ASM) && defined(__GNUC__) && defined(__x86_64__) #define CRYPTOPP_X64_ASM_AVAILABLE #endif #if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || defined(__SSE2__)) && !defined(_M_ARM) #define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 1 #else #define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 0 #endif #if !defined(CRYPTOPP_DISABLE_SSSE3) && !defined(CRYPTOPP_DISABLE_AESNI) && CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE && (CRYPTOPP_GCC_VERSION >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110 || defined(__AES__)) #define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 1 #else #define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 0 #endif #if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE) #define CRYPTOPP_BOOL_ALIGN16 1 #else #define CRYPTOPP_BOOL_ALIGN16 0 #endif #if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE && (defined(__SSE4_1__) || defined(__INTEL_COMPILER) || defined(_MSC_VER)) #define CRYPTOPP_BOOL_SSE41_INTRINSICS_AVAILABLE 1 #else #define CRYPTOPP_BOOL_SSE41_INTRINSICS_AVAILABLE 0 #endif // how to allocate 16-byte aligned memory (for SSE2) #if defined(_MSC_VER) #define CRYPTOPP_MM_MALLOC_AVAILABLE #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) #define CRYPTOPP_MALLOC_ALIGNMENT_IS_16 #elif defined(__linux__) || defined(__sun__) || defined(__CYGWIN__) #define CRYPTOPP_MEMALIGN_AVAILABLE #else #define CRYPTOPP_NO_ALIGNED_ALLOC #endif // how to declare class constants #if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__INTEL_COMPILER) # define CRYPTOPP_CONSTANT(x) enum {x}; #else # define CRYPTOPP_CONSTANT(x) static const int x; #endif // Linux provides X32, which is 32-bit integers, longs and pointers on x86_64 using the full x86_64 register set. // Detect via __ILP32__ (http://wiki.debian.org/X32Port). However, __ILP32__ shows up in more places than // the System V ABI specs calls out, like on just about any 32-bit system with Clang. #if ((__ILP32__ >= 1) || (_ILP32 >= 1)) && defined(__x86_64__) #define CRYPTOPP_BOOL_X32 1 #else #define CRYPTOPP_BOOL_X32 0 #endif // see http://predef.sourceforge.net/prearch.html #if (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)) && !CRYPTOPP_BOOL_X32 #define CRYPTOPP_BOOL_X86 1 #else #define CRYPTOPP_BOOL_X86 0 #endif #if (defined(_M_X64) || defined(__x86_64__)) && !CRYPTOPP_BOOL_X32 #define CRYPTOPP_BOOL_X64 1 #else #define CRYPTOPP_BOOL_X64 0 #endif // Undo the ASM and Intrinsic related defines due to X32. #if CRYPTOPP_BOOL_X32 # undef CRYPTOPP_BOOL_X64 # undef CRYPTOPP_X64_ASM_AVAILABLE # undef CRYPTOPP_X64_MASM_AVAILABLE #endif #if !defined(CRYPTOPP_NO_UNALIGNED_DATA_ACCESS) && !defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS) #if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || defined(__powerpc__) || (__ARM_FEATURE_UNALIGNED >= 1)) #define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS #endif #endif // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack #define GETBYTE(x, y) (unsigned int)((unsigned char)((x)>>(8*(y)))) // these may be faster on other CPUs/compilers // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255) // #define GETBYTE(x, y) (((byte *)&(x))[y]) #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) ((byte)((x)>>(8*(y)))) #endif
adouble42/nemesis-current
Crypto/config.h
C
bsd-2-clause
7,649
#################################################################################### #.Synopsis # Creates and deletes sinkhole domains in Windows DNS servers. # #.Description # Script takes fully-qualified domain names (FQDNs) and/or simple domain # names, then uses them to create primary zones (not Active Directory # integrated) in a Windows DNS server, setting all zones to resolve to a # single chosen IP address. The IP address might be "0.0.0.0" or the IP # of an internal server configured for logging. The intention is to # prevent clients from resolving the correct IP address of unwanted FQDNs # and domain names, such as for malware and phishing sites. Such names # are said to be "sinkholed" or "blackholed" since they often resolve # to 0.0.0.0, which is an inaccessible IP address. # #.Parameter InputFile # Path to a file which contains the FQDNs and domain names to sinkhole. # File can have blank lines, comment lines (# or ;), multiple FQDNs or # domains per line (space- or comma-delimited), and can be a hosts file # with IP addresses too (addresses and localhost entires will be ignored). # You can also include wildcards to input multiple files, e.g., # "*bad*.txt", or pass in an array of file objects instead of a string. # #.Parameter Domain # One or more FQDNs or domains to sinkhole, separated by spaces or commas. # #.Parameter SinkHoleIP # The IP address to which all sinkholed names will resolve. The # default is "0.0.0.0", but perhaps is better set to an internal server. # Remember, there is only one IP for ALL the sinkholed domains. # #.Parameter DnsServerName # FQDN of the Windows DNS server. Defaults to localhost. If specified, # please always use a fully-qualified domain name (FQDN), especially if # the DNS server is a stand-alone or in a different domain. # #.Parameter IncludeWildCard # Will add a wildcard host record (*) to every sinkhole domain, which # will match all possible hostnames within that domain. Keep in mind # that sinkholing "www.sans.org" will treat the "www" as a domain # name, so a wildcard is not needed to match it; but sinkholing just # "sans.org" will not match "www.sans.org" or "ftp.sans.org" without # the wildcard. If you only want to sinkhole the exact FQDN or domain # name supplied to the script, then don't include a wildcard record. # If you are certain that you do not want to resolve anything whatsoever # under the sinkholed domains, then include the wildcard DNS record. # #.Parameter ReloadSinkHoleDomains # Will cause every sinkholed domain in your DNS server to re-read the # one shared zone file they all use. This is the zone file for the # 000-sinkholed-domain.local domain. Keep in mind that the DNS # graphical management tool shows you what is cached in memory, not # what is in the zone file. Reload the sinkhole domains if you, # for example, change the sinkhole IP address. Using this switch # causes any other parameters to be ignored. # #.Parameter DeleteSinkHoleDomains # Will delete all sinkhole domains, but will not delete any regular # non-sinkhole domains. Strictly speaking, this deletes any domain # which uses a zone file named "000-sinkholed-domain.local.dns". # The zone file itself is not deleted, but it only 1KB in size. # Using this switch causes any other parameters to be ignored. # #.Parameter RemoveLeadingWWW # Some lists of sinkhole names are simple domain names, while other # lists might prepend "www." to the beginning of many of the names. # Use this switch to remove the "www." from the beginning of any # name to be sinkholed, then consider using -IncludeWildCard too. # Note that "www.", "www1.", "www2." ... "www9." will be cut too, # but only for a single digit after the "www" part (1-9 only). # #.Parameter Credential # An "authority\username" string to explicitly authenticate to the # DNS server instead of using single sign-on with the current # identity. The authority is either a server name or a domain name. # You will be prompted for the passphrase. You can also pass in # a variable with a credential object from Get-Credential. # #.Example # .\Sinkhole-DNS.ps1 -Domain "www.sans.org" # # This will create a primary DNS domain named "www.sans.org" # which will resolve to "0.0.0.0". DNS server is local. # #.Example # .\Sinkhole-DNS.ps1 -Domain "www.sans.org" -SinkHoleIP "10.1.1.1" # # This will create a primary DNS domain named "www.sans.org" # which will resolve to "10.1.1.1". DNS server is local. # #.Example # .\Sinkhole-DNS.ps1 -InputFile file.txt -IncludeWildCard # # This will create DNS domains out of all the FQDNs and domain # names listed in file.txt, plus add a wildcard (*) record. # #.Example # .\Sinkhole-DNS.ps1 -ReloadSinkHoleDomains # # Perhaps after changing the sinkhole IP address, this will cause # all sinkholed domains to re-read their shared zone file. # #.Example # .\Sinkhole-DNS.ps1 -DeleteSinkHoleDomains # # This will delete all sinkholed domains, but will not delete # any other domains. This does not delete the sinkhole zone file. # #.Example # .\Sinkhole-DNS.ps1 -InputFile file.txt -DnsServerName ` # "server7.sans.org" -Credential "server7\administrator" # # This will create sinkholed domains from file.txt on a remote # DNS server named "server7.sans.org" with explicit credentials. # You will be prompted for the passphrase. # #.Example # $Cred = Get-Credential -Credential "server7\administrator" # # .\Sinkhole-DNS.ps1 -InputFile *evil*.txt ` # -DnsServerName "server7.sans.org" -Credential $Cred # # This will create sinkholed domains from *evil*.txt on a remote # DNS server named "server7.sans.org" with explicit credentials # supplied in a credential object ($Cred) which can be reused again. # Multiple input files may match "*evil*.txt". # # #################################################################################### Param ($InputFile, [String] $Domain, [String] $SinkHoleIP = "0.0.0.0", [String] $DnsServerName = ".", [Switch] $IncludeWildCard, [Switch] $ReloadSinkHoleDomains, [Switch] $DeleteSinkHoleDomains, [Switch] $RemoveLeadingWWW, $Credential) # Check for common help switches. if (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String") -and ($InputFile -match "/\?|-help|--h|--help")) { If ($Host.Version.Major -ge 2) { get-help -full .\sinkhole-dns.ps1 } Else {"`nPlease read this script's header in Notepad for the help information."} Exit } # Confirm PowerShell 2.0 or later. If ($Host.Version.Major -lt 2) { "This script requires PowerShell 2.0 or later.`nDownload the latest version from http://www.microsoft.com/powershell`n" ; Exit } # If necessary, prompt user for domain\username and a passphrase. If ($Credential) { $Cred = Get-Credential -Credential $Credential } Function Main { # Test access to WMI at target server ($ZoneClass is used later too). $ZoneClass = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_Zone'" If (-not $? -or $ZoneClass.Name -ne "MicrosoftDNS_Zone") { Throw("Failed to connect to WMI service or the WMI DNS_Zone namespace!") ; Exit } ##### Parse input domains, but exclude the following: localhost, any IP addresses, blank lines. #Process any -Domain args. [Object[]] $Domains = @($Domain -Split "[\s\;\,]") #Process any -InputFile arguments and expand any wildcards. If (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String")) { $InputFile = dir $InputFile } If ($InputFile -ne $Null) { $InputFile | ForEach { $Domains += Get-Content $_ | Where { $_ -notmatch "^[\#\;\<]" } | ForEach { $_ -Split "[\s\;\,]" } } } #If -RemoveLeadingWWW was used, edit out those "www." strings. If ($RemoveLeadingWWW) { 0..$([Int] $Domains.Count - 1) | ForEach { $Domains[$_] = $Domains[$_] -Replace "^www[1-9]{0,1}\.","" } } #Convert to lowercase, remove redundants, exclude blank lines, exclude IPs, exclude anything with a colon in it, e.g., IPv6. $Domains = $Domains | ForEach { $_.Trim().ToLower() } | Sort -Unique | Where { $_.Length -ne 0 -and $_ -notmatch "^localhost$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\:" } If ($Domains.Count -le 0) { "No domains specified!" ; exit } Else { "`n" + [String] $Domains.Count + " domain(s) to sinkhole to $SinkHoleIP." } ##### ##### Get or create the master sinkhole zone: 000-sinkholed-domain.local. $WmiPath = "Root\MicrosoftDNS:MicrosoftDNS_Zone.ContainerName='000-sinkholed-domain.local',DnsServerName='" + $DnsServerName + "',Name='000-sinkholed-domain.local'" If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName GetDistinguishedName) #Zone exists. { "`nThe 000-sinkholed-domain.local zone already exists, deleting its existing DNS records." $ExistingRecords = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_AType WHERE ContainerName = '000-sinkholed-domain.local'") If (-not $?) { Throw("Failed to query the A records of the 000-sinkholed-domain.local domain!") ; exit } If ($ExistingRecords.Count -gt 0) { $ExistingRecords | ForEach { $_.Delete() } } } Else #Zone does not exist. { "`nCreating the 000-sinkholed-domain.local zone and its zone file." $RR = $ZoneClass.CreateZone("000-sinkholed-domain.local",0,$false,$null,$null,"only-edit.000-sinkholed-domain.local.") If (-not $? -or $RR.__CLASS -ne "__PARAMETERS") { If ($Credential -And ($DnsServerName.Length -ne 0) -And ($DnsServerName -NotLike "*.*")) { "Did you forget to use a FQDN for the DNS server name?" } Throw("Failed to create the 000-sinkholed-domain.local domain!") Exit } } ##### ##### Create DNS records in master sinkhole zone. # Create the default A record with the sinkhole IP address. $RecordClass = $Null # Defaults to "IN" class of record. $TTL = 120 # Seconds. Defaults to zone default if you set this to $null. $ATypeRecords = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_AType'" If (-not $? -or $ATypeRecords.Name -ne "MicrosoftDNS_AType") { "`nFailed to query A type records, but continuing..." } $ARecord = $ATypeRecords.CreateInstanceFromPropertyData($DnsServerName,"000-sinkholed-domain.local","000-sinkholed-domain.local",$RecordClass,$TTL,$SinkHoleIP) If ($?) { "Created default DNS record for the 000-sinkholed-domain.local zone ($SinkHoleIP)." } Else { "Failed to create default A record for the 000-sinkholed-domain.local zone, but continuing..." } # Create the wildcard A record if the -IncludeWildCard switch was used. If ($IncludeWildCard) { $ARecord = $ATypeRecords.CreateInstanceFromPropertyData($DnsServerName,"000-sinkholed-domain.local","*.000-sinkholed-domain.local",$RecordClass,$TTL,$SinkHoleIP) If ($?) { "Created the wildcard (*) record for the 000-sinkholed-domain.local zone ($SinkHoleIP)." } Else { "Failed to create the wildcard (*) record for the 000-sinkholed-domain.local zone, but continuing..." } } # Update zone data file on disk after adding the A record(s). If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone) { "Updated the zone file for 000-sinkholed-domain.local." } Else { Start-Sleep -Seconds 2 #Just seems to help... $ItWorked = InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone If ($ItWorked) { "Updated the zone file for 000-sinkholed-domain.local." } Else {"`nFailed to update the server data file for the 000-sinkholed-domain.local zone, but continuing..." } } ##### ##### Create the sinkholed domains using the 000-sinkholed-domain.local.dns zone file. $Created = $NotCreated = 0 $CurrentErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $Domains | ForEach ` { $ZoneClass.CreateZone($_,0,$false,"000-sinkholed-domain.local.dns",$null,"only-edit.000-sinkholed-domain.local.") | Out-Null If ($?) { $Created++ } Else { $NotCreated++ } } $ErrorActionPreference = $CurrentErrorActionPreference "`nSinkhole domains created at the DNS server: $Created" "`nDomains NOT created (maybe already existed): $NotCreated`n" } #End of Main Function GetWMI ([String] $Query) { # This is a helper function for the sake of -Credential. If ($Credential) { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName -Credential $Cred } Else { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName } } Function InvokeWmiMethod ([String] $ObjectPath, [String] $MethodName) { # This is a helper function for the sake of -Credential. $ErrorActionPreference = "SilentlyContinue" If ($Credential) { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName -Credential $Cred } Else { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName } $? #Returns } Function Reload-SinkHoledDomains { # Function causes sinkholed domains to be reloaded from the shared master zone file, perhaps after a -SinkHoleIP change. # You may get errors if zone is temporarily locked for updates, but the DNS server's default lock is only two minutes. "`nReloading sinkholed domains from the 000-sinkholed-domain.local.dns zone file, `nwhich may take a few minutes if you have 10K+ domains..." $BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '000-sinkholed-domain.local.dns'") If (-not $?) { Throw("Failed to connect to WMI service!") ; exit } "`nSinkholed domains to be reloaded from the zone file: " + [String] $BHDomains.Count $Locked = @() #Index numbers of zones which are temporarily locked and cannot be reloaded yet. $i = 0 $ErrorActionPreference = "SilentlyContinue" If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.ReloadZone() ; If (-not $?) { $Locked += $i } ; $i++ } } If ($Locked.Count -gt 0) { "`n" + [String] $Locked.Count + " zone(s) are still temporarily locked, will try those again in two minutes.`nPlease wait two minutes or hit Ctrl-C to cancel..." Start-Sleep -Seconds 60 "Just one more minute... Thank you for holding, your function call is appreciated." Start-Sleep -Seconds 30 "Just 30 more seconds... Your patience is admirable, and you're good looking too!" Start-Sleep -Seconds 35 $Locked | ForEach { $BHDomains[$_].ReloadZone() ; if (-not $?) { "`n" + [String] $BHDomains[$_].ContainerName + " is still locked and has not reloaded yet." } } } "`nThe other sinkholed domains were successfully reloaded.`n" } #End Function Delete-SinkHoledDomains { # Delete all sinkholed zones, including 000-sinkholed-domain.local, but # note that this does not delete the (tiny) zone file on the drive. "`nDeleting all sinkholed domains, which may take a few minutes if you have 10K+ domains..." $BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '000-sinkholed-domain.local.dns'") If (-not $?) { Throw("Failed to connect to WMI service!") ; exit } "`nSinkhole domains to be deleted: " + [String] $BHDomains.Count $i = 0 If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.Delete() ; If ($?){$i++} } } "Sinkhole domains deleted count: $i`n" } #End ######################## # MAIN # ######################## If ($ReloadSinkHoleDomains) { Reload-SinkHoledDomains ; Exit } If ($DeleteSinkHoleDomains) { Delete-SinkHoledDomains ; Exit } Main
allenj0321/Powershell
Sinkhole-DNS.ps1
PowerShell
bsd-2-clause
15,857
var searchData= [ ['lettersonly',['lettersOnly',['../class_able_polecat___data___primitive___scalar___string.html#ab2a7acaf93e00fbbd75ea51e56bbf47e',1,'AblePolecat_Data_Primitive_Scalar_String']]], ['list_5fdelimiter',['LIST_DELIMITER',['../interface_able_polecat___query_language___statement_interface.html#a7a10020800f80146451f24fbd57744f1',1,'AblePolecat_QueryLanguage_StatementInterface']]], ['load',['load',['../interface_able_polecat___service___dtx_interface.html#a4dcaa8f72c8423d4de25a9e87fa6f3e4',1,'AblePolecat_Service_DtxInterface']]], ['loadclass',['loadClass',['../class_able_polecat___registry___class.html#af58c5b3a44f9688f9e90dd35abbdefa2',1,'AblePolecat_Registry_Class']]], ['loadmore',['loadMore',['../interface_able_polecat___service___dtx_interface.html#ab5a46d6d7f1795a26153dc59a28b9881',1,'AblePolecat_Service_DtxInterface']]], ['loadtemplatefragment',['loadTemplateFragment',['../class_able_polecat___dom.html#af8f857ffafb0c1e59d752b7b430a95a0',1,'AblePolecat_Dom']]], ['loadtoken',['loadToken',['../interface_able_polecat___access_control___role___user___authenticated___o_auth2_interface.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Interface\loadToken()'],['../class_able_polecat___access_control___role___user___authenticated___o_auth2_abstract.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Abstract\loadToken()']]], ['log_2ephp',['Log.php',['../_command_2_log_8php.html',1,'']]], ['log_5fname_5fbootseq',['LOG_NAME_BOOTSEQ',['../class_able_polecat___log___boot.html#a645cd359836227fd9f770339a3147e7b',1,'AblePolecat_Log_Boot']]], ['logbootmessage',['logBootMessage',['../class_able_polecat___mode___server.html#a049626e8b9364098553ee05897b55111',1,'AblePolecat_Mode_Server']]], ['logerrorinfo',['logErrorInfo',['../class_able_polecat___database___pdo.html#a3fdddf6c2c95a4b45cf1a8468f07477d',1,'AblePolecat_Database_Pdo']]], ['logerrormessage',['logErrorMessage',['../class_able_polecat___log_abstract.html#aab8bf90eb60199535dca4c1a6a7742c6',1,'AblePolecat_LogAbstract']]], ['logstatusmessage',['logStatusMessage',['../class_able_polecat___log_abstract.html#af7ba4439ae852b1deed142b4c80f4453',1,'AblePolecat_LogAbstract']]], ['logwarningmessage',['logWarningMessage',['../class_able_polecat___log_abstract.html#a56bda277fc4e215249cfb9ed967204cc',1,'AblePolecat_LogAbstract']]], ['lookupconstraint',['lookupConstraint',['../class_able_polecat___resource___restricted_abstract.html#a46d5b25cc8f9b1ad658b5c6617536824',1,'AblePolecat_Resource_RestrictedAbstract']]], ['lvalue',['lvalue',['../interface_able_polecat___query_language___expression___binary_interface.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryInterface\lvalue()'],['../class_able_polecat___query_language___expression___binary_abstract.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryAbstract\lvalue()']]] ];
kkuhrman/AblePolecat
usr/share/documentation/html/search/all_c.js
JavaScript
bsd-2-clause
3,016
// 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. #ifndef UI_GFX_IMAGE_IMAGE_UTIL_H_ #define UI_GFX_IMAGE_IMAGE_UTIL_H_ #include <vector> #include "base/basictypes.h" #include "ui/gfx/gfx_export.h" namespace gfx { class Image; } namespace gfx { // Creates an image from the given JPEG-encoded input. If there was an error // creating the image, returns an IsEmpty() Image. UI_EXPORT Image ImageFrom1xJPEGEncodedData(const unsigned char* input, size_t input_size); // Fills the |dst| vector with JPEG-encoded bytes of the 1x representation of // the given image. // Returns true if the image has a 1x representation and the 1x representation // was encoded successfully. // |quality| determines the compression level, 0 == lowest, 100 == highest. // Returns true if the Image was encoded successfully. UI_EXPORT bool JPEG1xEncodedDataFromImage(const Image& image, int quality, std::vector<unsigned char>* dst); } // namespace gfx #endif // UI_GFX_IMAGE_IMAGE_UTIL_H_
mogoweb/chromium-crosswalk
ui/gfx/image/image_util.h
C
bsd-3-clause
1,223
// Copyright (c) 2011 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 "chrome/browser/profiles/profile.h" #include <string> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/browser/background_contents_service_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/host_content_settings_map.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/extensions/extension_pref_store.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_special_storage_policy.h" #include "chrome/browser/net/pref_proxy_config_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/off_the_record_profile_io_data.h" #include "chrome/browser/profiles/profile_dependency_manager.h" #include "chrome/browser/ssl/ssl_host_state.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/transport_security_persister.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/find_bar/find_bar_state.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/extension_icon_source.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/json_pref_store.h" #include "chrome/common/pref_names.h" #include "chrome/common/render_messages.h" #include "content/browser/appcache/chrome_appcache_service.h" #include "content/browser/browser_thread.h" #include "content/browser/chrome_blob_storage_context.h" #include "content/browser/file_system/browser_file_system_helper.h" #include "content/browser/host_zoom_map.h" #include "content/browser/in_process_webkit/webkit_context.h" #include "content/common/notification_service.h" #include "grit/locale_settings.h" #include "net/base/transport_security_state.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/database/database_tracker.h" #include "webkit/quota/quota_manager.h" #if defined(TOOLKIT_USES_GTK) #include "chrome/browser/ui/gtk/gtk_theme_service.h" #endif #if defined(OS_WIN) #include "chrome/browser/password_manager/password_store_win.h" #elif defined(OS_MACOSX) #include "chrome/browser/keychain_mac.h" #include "chrome/browser/password_manager/password_store_mac.h" #elif defined(OS_POSIX) && !defined(OS_CHROMEOS) #include "chrome/browser/password_manager/native_backend_gnome_x.h" #include "chrome/browser/password_manager/native_backend_kwallet_x.h" #include "chrome/browser/password_manager/password_store_x.h" #elif defined(OS_CHROMEOS) #include "chrome/browser/chromeos/preferences.h" #endif using base::Time; using base::TimeDelta; // A pointer to the request context for the default profile. See comments on // Profile::GetDefaultRequestContext. net::URLRequestContextGetter* Profile::default_request_context_; namespace { } // namespace Profile::Profile() : restored_last_session_(false), accessibility_pause_level_(0) { } // static const char* Profile::kProfileKey = "__PROFILE__"; // static const ProfileId Profile::kInvalidProfileId = static_cast<ProfileId>(0); // static void Profile::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kSearchSuggestEnabled, true); prefs->RegisterBooleanPref(prefs::kSessionExitedCleanly, true); prefs->RegisterBooleanPref(prefs::kSafeBrowsingEnabled, true); prefs->RegisterBooleanPref(prefs::kSafeBrowsingReportingEnabled, false); // TODO(estade): IDS_SPELLCHECK_DICTIONARY should be an ASCII string. prefs->RegisterLocalizedStringPref(prefs::kSpellCheckDictionary, IDS_SPELLCHECK_DICTIONARY); prefs->RegisterBooleanPref(prefs::kEnableSpellCheck, true); prefs->RegisterBooleanPref(prefs::kEnableAutoSpellCorrect, true); #if defined(TOOLKIT_USES_GTK) prefs->RegisterBooleanPref(prefs::kUsesSystemTheme, GtkThemeService::DefaultUsesSystemTheme()); #endif prefs->RegisterFilePathPref(prefs::kCurrentThemePackFilename, FilePath()); prefs->RegisterStringPref(prefs::kCurrentThemeID, ThemeService::kDefaultThemeID); prefs->RegisterDictionaryPref(prefs::kCurrentThemeImages); prefs->RegisterDictionaryPref(prefs::kCurrentThemeColors); prefs->RegisterDictionaryPref(prefs::kCurrentThemeTints); prefs->RegisterDictionaryPref(prefs::kCurrentThemeDisplayProperties); prefs->RegisterBooleanPref(prefs::kDisableExtensions, false); prefs->RegisterStringPref(prefs::kSelectFileLastDirectory, ""); #if defined(OS_CHROMEOS) // TODO(dilmah): For OS_CHROMEOS we maintain kApplicationLocale in both // local state and user's profile. For other platforms we maintain // kApplicationLocale only in local state. // In the future we may want to maintain kApplicationLocale // in user's profile for other platforms as well. prefs->RegisterStringPref(prefs::kApplicationLocale, ""); prefs->RegisterStringPref(prefs::kApplicationLocaleBackup, ""); prefs->RegisterStringPref(prefs::kApplicationLocaleAccepted, ""); #endif } // static net::URLRequestContextGetter* Profile::GetDefaultRequestContext() { return default_request_context_; } bool Profile::IsGuestSession() { #if defined(OS_CHROMEOS) static bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession); return is_guest_session; #else return false; #endif } bool Profile::IsSyncAccessible() { ProfileSyncService* syncService = GetProfileSyncService(); return syncService && !syncService->IsManaged(); } //////////////////////////////////////////////////////////////////////////////// // // OffTheRecordProfileImpl is a profile subclass that wraps an existing profile // to make it suitable for the incognito mode. // //////////////////////////////////////////////////////////////////////////////// class OffTheRecordProfileImpl : public Profile, public BrowserList::Observer { public: explicit OffTheRecordProfileImpl(Profile* real_profile) : profile_(real_profile), prefs_(real_profile->GetOffTheRecordPrefs()), ALLOW_THIS_IN_INITIALIZER_LIST(io_data_(this)), start_time_(Time::Now()) { extension_process_manager_.reset(ExtensionProcessManager::Create(this)); BrowserList::AddObserver(this); BackgroundContentsServiceFactory::GetForProfile(this); DCHECK(real_profile->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled)); // TODO(oshima): Remove the need to eagerly initialize the request context // getter. chromeos::OnlineAttempt is illegally trying to access this // Profile member from a thread other than the UI thread, so we need to // prevent a race. #if defined(OS_CHROMEOS) GetRequestContext(); #endif // defined(OS_CHROMEOS) // Make the chrome//extension-icon/ resource available. ExtensionIconSource* icon_source = new ExtensionIconSource(real_profile); GetChromeURLDataManager()->AddDataSource(icon_source); } virtual ~OffTheRecordProfileImpl() { NotificationService::current()->Notify(NotificationType::PROFILE_DESTROYED, Source<Profile>(this), NotificationService::NoDetails()); ProfileDependencyManager::GetInstance()->DestroyProfileServices(this); // Clean up all DB files/directories if (db_tracker_) BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod( db_tracker_.get(), &webkit_database::DatabaseTracker::DeleteIncognitoDBDirectory)); BrowserList::RemoveObserver(this); if (pref_proxy_config_tracker_) pref_proxy_config_tracker_->DetachFromPrefService(); } virtual ProfileId GetRuntimeId() { return reinterpret_cast<ProfileId>(this); } virtual std::string GetProfileName() { // Incognito profile should not return the profile name. return std::string(); } virtual FilePath GetPath() { return profile_->GetPath(); } virtual bool IsOffTheRecord() { return true; } virtual Profile* GetOffTheRecordProfile() { return this; } virtual void DestroyOffTheRecordProfile() { // Suicide is bad! NOTREACHED(); } virtual bool HasOffTheRecordProfile() { return true; } virtual Profile* GetOriginalProfile() { return profile_; } virtual ChromeAppCacheService* GetAppCacheService() { if (!appcache_service_) { appcache_service_ = new ChromeAppCacheService; BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( appcache_service_.get(), &ChromeAppCacheService::InitializeOnIOThread, IsOffTheRecord() ? FilePath() : GetPath().Append(chrome::kAppCacheDirname), make_scoped_refptr(GetHostContentSettingsMap()), make_scoped_refptr(GetExtensionSpecialStoragePolicy()), false)); } return appcache_service_; } virtual webkit_database::DatabaseTracker* GetDatabaseTracker() { if (!db_tracker_.get()) { db_tracker_ = new webkit_database::DatabaseTracker( GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy()); } return db_tracker_; } virtual VisitedLinkMaster* GetVisitedLinkMaster() { // We don't provide access to the VisitedLinkMaster when we're OffTheRecord // because we don't want to leak the sites that the user has visited before. return NULL; } virtual ExtensionService* GetExtensionService() { return GetOriginalProfile()->GetExtensionService(); } virtual StatusTray* GetStatusTray() { return GetOriginalProfile()->GetStatusTray(); } virtual UserScriptMaster* GetUserScriptMaster() { return GetOriginalProfile()->GetUserScriptMaster(); } virtual ExtensionDevToolsManager* GetExtensionDevToolsManager() { // TODO(mpcomplete): figure out whether we should return the original // profile's version. return NULL; } virtual ExtensionProcessManager* GetExtensionProcessManager() { return extension_process_manager_.get(); } virtual ExtensionMessageService* GetExtensionMessageService() { return GetOriginalProfile()->GetExtensionMessageService(); } virtual ExtensionEventRouter* GetExtensionEventRouter() { return GetOriginalProfile()->GetExtensionEventRouter(); } virtual ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() { return GetOriginalProfile()->GetExtensionSpecialStoragePolicy(); } virtual SSLHostState* GetSSLHostState() { if (!ssl_host_state_.get()) ssl_host_state_.reset(new SSLHostState()); DCHECK(ssl_host_state_->CalledOnValidThread()); return ssl_host_state_.get(); } virtual net::TransportSecurityState* GetTransportSecurityState() { if (!transport_security_state_.get()) { transport_security_state_ = new net::TransportSecurityState( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kHstsHosts)); transport_security_loader_ = new TransportSecurityPersister(true /* readonly */); transport_security_loader_->Initialize(transport_security_state_.get(), GetOriginalProfile()->GetPath()); } return transport_security_state_.get(); } virtual HistoryService* GetHistoryService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetHistoryService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual HistoryService* GetHistoryServiceWithoutCreating() { return profile_->GetHistoryServiceWithoutCreating(); } virtual FaviconService* GetFaviconService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetFaviconService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual AutocompleteClassifier* GetAutocompleteClassifier() { return profile_->GetAutocompleteClassifier(); } virtual WebDataService* GetWebDataService(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetWebDataService(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual WebDataService* GetWebDataServiceWithoutCreating() { return profile_->GetWebDataServiceWithoutCreating(); } virtual PasswordStore* GetPasswordStore(ServiceAccessType sat) { if (sat == EXPLICIT_ACCESS) return profile_->GetPasswordStore(sat); NOTREACHED() << "This profile is OffTheRecord"; return NULL; } virtual PrefService* GetPrefs() { return prefs_; } virtual PrefService* GetOffTheRecordPrefs() { return prefs_; } virtual TemplateURLModel* GetTemplateURLModel() { return profile_->GetTemplateURLModel(); } virtual TemplateURLFetcher* GetTemplateURLFetcher() { return profile_->GetTemplateURLFetcher(); } virtual DownloadManager* GetDownloadManager() { if (!download_manager_.get()) { scoped_refptr<DownloadManager> dlm( new DownloadManager(g_browser_process->download_status_updater())); dlm->Init(this); download_manager_.swap(dlm); } return download_manager_.get(); } virtual bool HasCreatedDownloadManager() const { return (download_manager_.get() != NULL); } virtual PersonalDataManager* GetPersonalDataManager() { return NULL; } virtual fileapi::FileSystemContext* GetFileSystemContext() { if (!file_system_context_) file_system_context_ = CreateFileSystemContext( GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy()); DCHECK(file_system_context_.get()); return file_system_context_.get(); } virtual net::URLRequestContextGetter* GetRequestContext() { return io_data_.GetMainRequestContextGetter(); } virtual quota::QuotaManager* GetQuotaManager() { if (!quota_manager_.get()) { quota_manager_ = new quota::QuotaManager( IsOffTheRecord(), GetPath(), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB)); } return quota_manager_.get(); } virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess( int renderer_child_id) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalAppManifests)) { const Extension* installed_app = GetExtensionService()-> GetInstalledAppForRenderer(renderer_child_id); if (installed_app != NULL && installed_app->is_storage_isolated()) return GetRequestContextForIsolatedApp(installed_app->id()); } return GetRequestContext(); } virtual net::URLRequestContextGetter* GetRequestContextForMedia() { // In OTR mode, media request context is the same as the original one. return io_data_.GetMainRequestContextGetter(); } virtual net::URLRequestContextGetter* GetRequestContextForExtensions() { return io_data_.GetExtensionsRequestContextGetter(); } virtual net::URLRequestContextGetter* GetRequestContextForIsolatedApp( const std::string& app_id) { return io_data_.GetIsolatedAppRequestContextGetter(app_id); } virtual const content::ResourceContext& GetResourceContext() { return io_data_.GetResourceContext(); } virtual net::SSLConfigService* GetSSLConfigService() { return profile_->GetSSLConfigService(); } virtual HostContentSettingsMap* GetHostContentSettingsMap() { // Retrieve the host content settings map of the parent profile in order to // ensure the preferences have been migrated. profile_->GetHostContentSettingsMap(); if (!host_content_settings_map_.get()) host_content_settings_map_ = new HostContentSettingsMap(this); return host_content_settings_map_.get(); } virtual HostZoomMap* GetHostZoomMap() { if (!host_zoom_map_) host_zoom_map_ = new HostZoomMap(this); return host_zoom_map_.get(); } virtual GeolocationContentSettingsMap* GetGeolocationContentSettingsMap() { return profile_->GetGeolocationContentSettingsMap(); } virtual GeolocationPermissionContext* GetGeolocationPermissionContext() { return profile_->GetGeolocationPermissionContext(); } virtual UserStyleSheetWatcher* GetUserStyleSheetWatcher() { return profile_->GetUserStyleSheetWatcher(); } virtual FindBarState* GetFindBarState() { if (!find_bar_state_.get()) find_bar_state_.reset(new FindBarState()); return find_bar_state_.get(); } virtual bool HasProfileSyncService() const { // We never have a profile sync service. return false; } virtual bool DidLastSessionExitCleanly() { return profile_->DidLastSessionExitCleanly(); } virtual BookmarkModel* GetBookmarkModel() { return profile_->GetBookmarkModel(); } virtual ProtocolHandlerRegistry* GetProtocolHandlerRegistry() { return profile_->GetProtocolHandlerRegistry(); } virtual TokenService* GetTokenService() { return NULL; } virtual ProfileSyncService* GetProfileSyncService() { return NULL; } virtual ProfileSyncService* GetProfileSyncService( const std::string& cros_user) { return NULL; } virtual BrowserSignin* GetBrowserSignin() { return profile_->GetBrowserSignin(); } virtual CloudPrintProxyService* GetCloudPrintProxyService() { return NULL; } virtual bool IsSameProfile(Profile* profile) { return (profile == this) || (profile == profile_); } virtual Time GetStartTime() const { return start_time_; } virtual SpellCheckHost* GetSpellCheckHost() { return profile_->GetSpellCheckHost(); } virtual void ReinitializeSpellCheckHost(bool force) { profile_->ReinitializeSpellCheckHost(force); } virtual WebKitContext* GetWebKitContext() { if (!webkit_context_.get()) { webkit_context_ = new WebKitContext( IsOffTheRecord(), GetPath(), GetExtensionSpecialStoragePolicy(), false); } return webkit_context_.get(); } virtual history::TopSites* GetTopSitesWithoutCreating() { return NULL; } virtual history::TopSites* GetTopSites() { return NULL; } virtual void MarkAsCleanShutdown() { } virtual void InitExtensions(bool extensions_enabled) { NOTREACHED(); } virtual void InitPromoResources() { NOTREACHED(); } virtual void InitRegisteredProtocolHandlers() { NOTREACHED(); } virtual NTPResourceCache* GetNTPResourceCache() { // Just return the real profile resource cache. return profile_->GetNTPResourceCache(); } virtual FilePath last_selected_directory() { const FilePath& directory = last_selected_directory_; if (directory.empty()) { return profile_->last_selected_directory(); } return directory; } virtual void set_last_selected_directory(const FilePath& path) { last_selected_directory_ = path; } #if defined(OS_CHROMEOS) virtual void SetupChromeOSEnterpriseExtensionObserver() { profile_->SetupChromeOSEnterpriseExtensionObserver(); } virtual void InitChromeOSPreferences() { // The incognito profile shouldn't have Chrome OS's preferences. // The preferences are associated with the regular user profile. } #endif // defined(OS_CHROMEOS) virtual void ExitedOffTheRecordMode() { // DownloadManager is lazily created, so check before accessing it. if (download_manager_.get()) { // Drop our download manager so we forget about all the downloads made // in incognito mode. download_manager_->Shutdown(); download_manager_ = NULL; } } virtual void OnBrowserAdded(const Browser* browser) { } virtual void OnBrowserRemoved(const Browser* browser) { if (BrowserList::GetBrowserCount(this) == 0) ExitedOffTheRecordMode(); } virtual ChromeBlobStorageContext* GetBlobStorageContext() { if (!blob_storage_context_) { blob_storage_context_ = new ChromeBlobStorageContext(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( blob_storage_context_.get(), &ChromeBlobStorageContext::InitializeOnIOThread)); } return blob_storage_context_; } virtual ExtensionInfoMap* GetExtensionInfoMap() { return profile_->GetExtensionInfoMap(); } virtual ChromeURLDataManager* GetChromeURLDataManager() { if (!chrome_url_data_manager_.get()) chrome_url_data_manager_.reset(new ChromeURLDataManager(this)); return chrome_url_data_manager_.get(); } virtual PromoCounter* GetInstantPromoCounter() { return NULL; } #if defined(OS_CHROMEOS) virtual void ChangeAppLocale(const std::string& locale, AppLocaleChangedVia) { } virtual void OnLogin() { } #endif // defined(OS_CHROMEOS) virtual PrefProxyConfigTracker* GetProxyConfigTracker() { if (!pref_proxy_config_tracker_) pref_proxy_config_tracker_ = new PrefProxyConfigTracker(GetPrefs()); return pref_proxy_config_tracker_; } virtual prerender::PrerenderManager* GetPrerenderManager() { // We do not allow prerendering in OTR profiles at this point. // TODO(tburkard): Figure out if we want to support this, and how, at some // point in the future. return NULL; } private: NotificationRegistrar registrar_; // The real underlying profile. Profile* profile_; // Weak pointer owned by |profile_|. PrefService* prefs_; scoped_ptr<ExtensionProcessManager> extension_process_manager_; OffTheRecordProfileIOData::Handle io_data_; // The download manager that only stores downloaded items in memory. scoped_refptr<DownloadManager> download_manager_; // We use a non-writable content settings map for OTR. scoped_refptr<HostContentSettingsMap> host_content_settings_map_; // Use a separate zoom map for OTR. scoped_refptr<HostZoomMap> host_zoom_map_; // Use a special WebKit context for OTR browsing. scoped_refptr<WebKitContext> webkit_context_; // We don't want SSLHostState from the OTR profile to leak back to the main // profile because then the main profile would learn some of the host names // the user visited while OTR. scoped_ptr<SSLHostState> ssl_host_state_; // Use a separate FindBarState so search terms do not leak back to the main // profile. scoped_ptr<FindBarState> find_bar_state_; // The TransportSecurityState that only stores enabled sites in memory. scoped_refptr<net::TransportSecurityState> transport_security_state_; // Time we were started. Time start_time_; scoped_refptr<ChromeAppCacheService> appcache_service_; // The main database tracker for this profile. // Should be used only on the file thread. scoped_refptr<webkit_database::DatabaseTracker> db_tracker_; FilePath last_selected_directory_; scoped_refptr<ChromeBlobStorageContext> blob_storage_context_; // The file_system context for this profile. scoped_refptr<fileapi::FileSystemContext> file_system_context_; scoped_refptr<PrefProxyConfigTracker> pref_proxy_config_tracker_; scoped_ptr<ChromeURLDataManager> chrome_url_data_manager_; scoped_refptr<quota::QuotaManager> quota_manager_; // Used read-only. scoped_refptr<TransportSecurityPersister> transport_security_loader_; DISALLOW_COPY_AND_ASSIGN(OffTheRecordProfileImpl); }; #if defined(OS_CHROMEOS) // Special case of the OffTheRecordProfileImpl which is used while Guest // session in CrOS. class GuestSessionProfile : public OffTheRecordProfileImpl { public: explicit GuestSessionProfile(Profile* real_profile) : OffTheRecordProfileImpl(real_profile) { } virtual PersonalDataManager* GetPersonalDataManager() { return GetOriginalProfile()->GetPersonalDataManager(); } virtual void InitChromeOSPreferences() { chromeos_preferences_.reset(new chromeos::Preferences()); chromeos_preferences_->Init(GetPrefs()); } private: // The guest user should be able to customize Chrome OS preferences. scoped_ptr<chromeos::Preferences> chromeos_preferences_; }; #endif Profile* Profile::CreateOffTheRecordProfile() { #if defined(OS_CHROMEOS) if (Profile::IsGuestSession()) return new GuestSessionProfile(this); #endif return new OffTheRecordProfileImpl(this); }
Crystalnix/house-of-life-chromium
chrome/browser/profiles/profile.cc
C++
bsd-3-clause
24,938
/* * Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * wrapper pow(x,y) return x**y */ #include "fdlibm.h" #ifdef __STDC__ double pow(double x, double y) /* wrapper pow */ #else double pow(x,y) /* wrapper pow */ double x,y; #endif { #ifdef _IEEE_LIBM return __ieee754_pow(x,y); #else double z; z=__ieee754_pow(x,y); if(_LIB_VERSION == _IEEE_|| isnan(y)) return z; if(isnan(x)) { if(y==0.0) return __kernel_standard(x,y,42); /* pow(NaN,0.0) */ else return z; } if(x==0.0){ if(y==0.0) return __kernel_standard(x,y,20); /* pow(0.0,0.0) */ if(finite(y)&&y<0.0) return __kernel_standard(x,y,23); /* pow(0.0,negative) */ return z; } if(!finite(z)) { if(finite(x)&&finite(y)) { if(isnan(z)) return __kernel_standard(x,y,24); /* pow neg**non-int */ else return __kernel_standard(x,y,21); /* pow overflow */ } } if(z==0.0&&finite(x)&&finite(y)) return __kernel_standard(x,y,22); /* pow underflow */ return z; #endif }
SnakeDoc/GuestVM
guestvm~guestvm/com.oracle.max.ve.native/fdlibm/w_pow.c
C
bsd-3-clause
1,152
{% from 'macros/misc.html' import render_tag %} {% macro render_flag_hidden(hidden_by) -%} {{ render_tag(_('hidden'), class='user-comment-hidden', icon='hidden', title='%s (%s %s)'|format(_('hidden'), _('by'), hidden_by.screen_name)) }} {%- endmacro %} {% macro render_flag_new() -%} {{ render_tag(_('new')) }} {%- endmacro %}
homeworkprod/byceps
byceps/blueprints/site/board/templates/macros/board.html
HTML
bsd-3-clause
335
// Copyright (c) 2009 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 NET_HTTP_HTTP_STREAM_PARSER_H_ #define NET_HTTP_HTTP_STREAM_PARSER_H_ #include <string> #include "base/basictypes.h" #include "net/base/io_buffer.h" #include "net/base/load_log.h" #include "net/base/upload_data_stream.h" #include "net/http/http_chunked_decoder.h" #include "net/http/http_response_info.h" #include "net/socket/client_socket_handle.h" namespace net { class ClientSocketHandle; class HttpRequestInfo; class HttpStreamParser { public: // Any data in |read_buffer| will be used before reading from the socket // and any data left over after parsing the stream will be put into // |read_buffer|. The left over data will start at offset 0 and the // buffer's offset will be set to the first free byte. |read_buffer| may // have its capacity changed. HttpStreamParser(ClientSocketHandle* connection, GrowableIOBuffer* read_buffer, LoadLog* load_log); ~HttpStreamParser() {} // These functions implement the interface described in HttpStream with // some additional functionality int SendRequest(const HttpRequestInfo* request, const std::string& headers, UploadDataStream* request_body, HttpResponseInfo* response, CompletionCallback* callback); int ReadResponseHeaders(CompletionCallback* callback); int ReadResponseBody(IOBuffer* buf, int buf_len, CompletionCallback* callback); uint64 GetUploadProgress() const; HttpResponseInfo* GetResponseInfo(); bool IsResponseBodyComplete() const; bool CanFindEndOfResponse() const; bool IsMoreDataBuffered() const; private: // FOO_COMPLETE states implement the second half of potentially asynchronous // operations and don't necessarily mean that FOO is complete. enum State { STATE_NONE, STATE_SENDING_HEADERS, STATE_SENDING_BODY, STATE_REQUEST_SENT, STATE_READ_HEADERS, STATE_READ_HEADERS_COMPLETE, STATE_BODY_PENDING, STATE_READ_BODY, STATE_READ_BODY_COMPLETE, STATE_DONE }; // The number of bytes by which the header buffer is grown when it reaches // capacity. enum { kHeaderBufInitialSize = 4096 }; // |kMaxHeaderBufSize| is the number of bytes that the response headers can // grow to. If the body start is not found within this range of the // response, the transaction will fail with ERR_RESPONSE_HEADERS_TOO_BIG. // Note: |kMaxHeaderBufSize| should be a multiple of |kHeaderBufInitialSize|. enum { kMaxHeaderBufSize = 256 * 1024 }; // 256 kilobytes. // The maximum sane buffer size. enum { kMaxBufSize = 2 * 1024 * 1024 }; // 2 megabytes. // Handle callbacks. void OnIOComplete(int result); // Try to make progress sending/receiving the request/response. int DoLoop(int result); // The implementations of each state of the state machine. int DoSendHeaders(int result); int DoSendBody(int result); int DoReadHeaders(); int DoReadHeadersComplete(int result); int DoReadBody(); int DoReadBodyComplete(int result); // Examines |read_buf_| to find the start and end of the headers. Return // the offset for the end of the headers, or -1 if the complete headers // were not found. If they are are found, parse them with // DoParseResponseHeaders(). int ParseResponseHeaders(); // Parse the headers into response_. void DoParseResponseHeaders(int end_of_header_offset); // Examine the parsed headers to try to determine the response body size. void CalculateResponseBodySize(); // Current state of the request. State io_state_; // The request to send. const HttpRequestInfo* request_; // The request header data. scoped_refptr<DrainableIOBuffer> request_headers_; // The request body data. scoped_ptr<UploadDataStream> request_body_; // Temporary buffer for reading. scoped_refptr<GrowableIOBuffer> read_buf_; // Offset of the first unused byte in |read_buf_|. May be nonzero due to // a 1xx header, or body data in the same packet as header data. int read_buf_unused_offset_; // The amount beyond |read_buf_unused_offset_| where the status line starts; // -1 if not found yet. int response_header_start_offset_; // The parsed response headers. Owned by the caller. HttpResponseInfo* response_; // Indicates the content length. If this value is less than zero // (and chunked_decoder_ is null), then we must read until the server // closes the connection. int64 response_body_length_; // Keep track of the number of response body bytes read so far. int64 response_body_read_; // Helper if the data is chunked. scoped_ptr<HttpChunkedDecoder> chunked_decoder_; // Where the caller wants the body data. scoped_refptr<IOBuffer> user_read_buf_; int user_read_buf_len_; // The callback to notify a user that their request or response is // complete or there was an error CompletionCallback* user_callback_; // In the client callback, the client can do anything, including // destroying this class, so any pending callback must be issued // after everything else is done. When it is time to issue the client // callback, move it from |user_callback_| to |scheduled_callback_|. CompletionCallback* scheduled_callback_; // The underlying socket. ClientSocketHandle* const connection_; scoped_refptr<LoadLog> load_log_; // Callback to be used when doing IO. CompletionCallbackImpl<HttpStreamParser> io_callback_; DISALLOW_COPY_AND_ASSIGN(HttpStreamParser); }; } // namespace net #endif // NET_HTTP_HTTP_STREAM_PARSER_H_
rwatson/chromium-capsicum
net/http/http_stream_parser.h
C
bsd-3-clause
5,721
# Goga &ndash; examples ## Summary 0. Simple functions 1. Constrained one-objective problems 2. Unconstrained two-objective problems 3. Constrained two-objective problems 4. Constrained and unconstrained three-objective problems 5. Unconstrained many-objectives problems 6. Truss shape and topology optimisation 7. Economic emission load dispatch # 0 Simple functions Goga can use two types of objective functions: (A) the higher-level one: MinProb\_t which takes the vector of random variables x and returns the objectives values in f. It may also return the inequality constraints in g and the equality constraints in h. It also accepts integer random variables in y (B) the lower-level one: ObjFunc\_t which takes the pointer to a candidate solution object (Solution) and fills the Ova array in this object with the objective values. In this method the vector of random variables x is stored as Flt Both functions take the cpu number as input if that's necessary (rarely) The functions definitions of each case are shown below ObjFunc\_t defines the objective fuction `type ObjFunc_t func(sol *Solution, cpu int)` MinProb\_t defines objective functon for specialised minimisation problem `type MinProb_t func(f, g, h, x []float64, y []int, cpu int)` ## Curve 1 ```go // case A: finding the minimum of 2.0 + (1+x)² func fcnA(f, g, h, x []float64, y []int, cpu int) { f[0] = 2.0 + (1.0+x[0])*(1.0+x[0]) } // case B: finding the minimum of func fcnB(sol *goga.Solution, cpu int) { x := sol.Flt sol.Ova[0] = 2.0 + (1.0+x[0])*(1.0+x[0]) } // main function func main() { // problem definition nf := 1 // number of objective functions ng := 0 // number of inequality constraints nh := 0 // number of equality constraints // the solver (optimiser) var opt goga.Optimiser opt.Default() // must call this to set default constants opt.FltMin = []float64{-2} // must set minimum opt.FltMax = []float64{2} // must set maximum // initialise the solver useMethodA := false if useMethodA { opt.Init(goga.GenTrialSolutions, nil, fcnA, nf, ng, nh) } else { opt.Init(goga.GenTrialSolutions, fcnB, nil, nf, ng, nh) } // solve problem opt.Solve() // print results xBest := opt.Solutions[0].Flt[0] fBest := 2.0 + (1.0+xBest)*(1.0+xBest) io.Pf("xBest = %v\n", xBest) io.Pf("f(xBest) = %v\n", fBest) // plotting fvec := []float64{0} // temporary vector to use with fcnA xvec := []float64{0} // temporary vector to use with fcnA X := utl.LinSpace(-2, 2, 101) F := utl.GetMapped(X, func(x float64) float64 { xvec[0] = x fcnA(fvec, nil, nil, xvec, nil, 0) return fvec[0] }) plt.Reset(true, nil) plt.PlotOne(xBest, fBest, &plt.A{C: "r", M: "o", Ms: 20, NoClip: true}) plt.Plot(X, F, nil) plt.Gll("$x$", "$f$", nil) plt.Save("/tmp/goga", "simple01") } ``` Source code: <a href="simple/simple01.go">simple/simple01.go</a> <div id="container"> <p><img src="simple/figs/simple01.png" width="450"></p> Output of simple01.go </div> ## Curve 2 ```go // objective function func fcn(f, g, h, x []float64, y []int, cpu int) { f[0] = Cos(8*x[0]*Pi) * Exp(Cos(x[0]*Pi)-1) } // main function func main() { // problem definition nf := 1 // number of objective functions ng := 0 // number of inequality constraints nh := 0 // number of equality constraints // the solver (optimiser) var opt goga.Optimiser opt.Default() // must call this to set default constants opt.FltMin = []float64{0} // must set minimum opt.FltMax = []float64{2} // must set maximum // initialise the solver opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh) // solve problem opt.Solve() // auxiliary fvec := []float64{0} // temporary vector to use with fcn xvec := []float64{0} // temporary vector to use with fcn // print results xBest := opt.Solutions[0].Flt[0] xvec[0] = xBest fcn(fvec, nil, nil, xvec, nil, 0) fBest := fvec[0] io.Pf("xBest = %v\n", xBest) io.Pf("f(xBest) = %v\n", fBest) // generate f(x) curve X := utl.LinSpace(opt.FltMin[0], opt.FltMax[0], 1001) F := utl.GetMapped(X, func(x float64) float64 { xvec[0] = x fcn(fvec, nil, nil, xvec, nil, 0) return fvec[0] }) // plotting plt.Reset(true, nil) plt.PlotOne(xBest, fBest, &plt.A{L: "best", C: "#bf2e64", M: ".", Ms: 15, NoClip: true}) opt.PlotAddFltOva(0, 0, opt.Solutions, 1, &plt.A{L: "all", C: "g", Ls: "none", M: ".", NoClip: true}) plt.Plot(X, F, &plt.A{L: "f(x)", C: "#0077d2"}) plt.Gll("$x$", "$f$", nil) plt.Save("/tmp/goga", "simple02") } ``` Source code: <a href="simple/simple02.go">simple/simple02.go</a> <div id="container"> <p><img src="simple/figs/simple02.png" width="450"></p> Output of simple02.go </div> ## Cross-in-tray function See [cross-in-tray function on wikipedia](https://en.wikipedia.org/wiki/Test_functions_for_optimization) ```go // objective function func fcn(f, g, h, x []float64, y []int, cpu int) { f[0] = -0.0001 * Pow(Abs(Sin(x[0])*Sin(x[1])*Exp(Abs(100-Sqrt(Pow(x[0], 2)+Pow(x[1], 2))/Pi)))+1, 0.1) } // main function func main() { // problem definition nf := 1 // number of objective functions ng := 0 // number of inequality constraints nh := 0 // number of equality constraints // the solver (optimiser) var opt goga.Optimiser opt.Default() // must call this to set default constants opt.FltMin = []float64{-10, -10} // must set minimum opt.FltMax = []float64{+10, +10} // must set maximum opt.Nsol = 80 // initialise the solver opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh) // solve problem tstart := time.Now() opt.Solve() cputime := time.Now().Sub(tstart) // print results fvec := []float64{0} // temporary vector to use with fcn xbest := opt.Solutions[0].Flt fcn(fvec, nil, nil, xbest, nil, 0) io.Pf("xBest = %v\n", xbest) io.Pf("f(xBest) = %v\n", fvec) // plotting pp := goga.NewPlotParams(false) pp.Npts = 101 pp.ArgsF.NoLines = true pp.ArgsF.CmapIdx = 4 plt.Reset(true, nil) plt.Title(io.Sf("Nsol(pop.size)=%d Tmax(generations)=%d CpuTime=%v", opt.Nsol, opt.Tmax, io.RoundDuration(cputime, 1e3)), &plt.A{Fsz: 8}) opt.PlotContour(0, 1, 0, pp) plt.PlotOne(xbest[0], xbest[1], &plt.A{C: "r", Mec: "r", M: "*"}) plt.Gll("$x_0$", "$x_1$", nil) plt.Save("/tmp/goga", "cross-in-tray") } ``` Source code: <a href="simple/cross-in-tray.go">simple/cross-in-tray.go</a> <div id="container"> <p><img src="simple/figs/cross-in-tray.png" width="450"></p> Output of cross-in-tray.go </div> To check the **repeatability** of the code, the optimisation loop can be called several times. This can be done with the `RunMany` function. For example, replace `opt.Solve()` with ```go // solve problem opt.RunMany("", "", false) // stat opt.PrintStatF(0) ``` Which will produce something similar to: ``` fmin = -2.0626118708227428 fave = -2.062611870822731 fmax = -2.0626118708217605 fdev = 9.817431965542015e-14 [-2.11,-2.10) | 0 [-2.10,-2.08) | 0 [-2.08,-2.07) | 0 [-2.07,-2.06) | 100 ##################### [-2.06,-2.04) | 0 [-2.04,-2.03) | 0 [-2.03,-2.01) | 0 count = 100 ``` Source code: <a href="simple/cross-in-tray-stat.go">simple/cross-in-tray-stat.go</a> # 1 Constrained one-objective problems Source code: <a href="01-one-obj/one-obj.go">one-obj.go</a> # 2 Unconstrained two-objective problems Source code: <a href="02-two-obj/two-obj.go">two-obj.go</a> # 3 Constrained two-objective problems Source code: <a href="03-two-obj-ct/two-obj-ct.go">two-obj-ct.go</a> # 4 Constrained and unconstrained three-objective problems Source code: <a href="04-three-obj/three-obj.go">three-obj.go</a> # 5 Unconstrained many-objectives problems Source code: <a href="05-many-obj/many-obj.go">many-obj.go</a> # 6 Truss shape and topology optimisation Source code: <a href="06-truss/topology.go">topology.go</a> and <a href="06-truss/femsim.go">femsim.go</a> # 7 Economic emission load dispatch Source code: <a href="07-eed/ecoemission.go">ecoemission.go</a> and <a href="07-eed/generators.go">generators.go</a>
cpmech/goga
examples/README.md
Markdown
bsd-3-clause
8,060
/** * Layout Select UI * * @package zork * @subpackage form * @author Kristof Matos <[email protected]> */ ( function ( global, $, js ) { "use strict"; if ( typeof js.layoutSelect !== "undefined" ) { return; } js.require( "jQuery.fn.vslider"); /** * Generates layout select user interface from radio inputs * * @memberOf Zork.Form.Element */ global.Zork.prototype.layoutSelect = function ( element ) { js.style('/styles/scripts/layoutselect.css'); element = $( element ); var defaultKey = element.data( "jsLayoutselectDefaultkey") || "paragraph.form.content.layout.default", descriptionKeyPattern = element.data( "jsLayoutselectDescriptionkey") || "paragraph.form.content.layout.default-description", imageSrcPattern = element.data( "jsLayoutselectImagesrc") || "", selectType = element.data( "jsLayoutselectType") || "locale", itemsPerRow = parseInt(element.data("jsLayoutselectItemsperrow"))>0 ? parseInt(element.data("jsLayoutselectItemsperrow")) : ( selectType == "local" ? 6 : 3 ); element.addClass( "layout-select "+selectType); element.find( "label" ).each( function(idx,eleRadioItem) { var input = $(eleRadioItem).find( ":radio" ), inner = $('<div class="inner"/>').append(input), title = $('<div class="title"/>').html( $(eleRadioItem).html() || js.core.translate(defaultKey) ), overlay = $('<div class="overlay"/>'), innerButtons = $('<div class="buttons"/>').appendTo(inner), innerDescription = $('<p class="description"/>').appendTo(inner), innerButtonsSelect = $('<span class="select"/>') .html( js.core.translate("default.select" ,js.core.userLocale) ) .appendTo(innerButtons), dateCreated = input.data("created") || '-', dateModified = input.data("lastModified") || '-'; $(eleRadioItem).html('') .append(inner) .append(title) .append(overlay); if( selectType == 'import' ) { innerDescription.html( js.core.translate( descriptionKeyPattern.replace("[value]", input.attr( "value")) ,js.core.userLocale)); var imageSrc = imageSrcPattern .replace("[value]",input.attr( "value")); inner.prepend( $( "<img alt='icon' />" ).attr( "src", imageSrc )); } else//selectType == 'locale' { if( input.attr( "value") ) { innerDescription .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.lastmodified", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateModified) ) ) .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.created", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateCreated) ) ); js.core.translate("default.created",js.core.userLocale) innerButtons.prepend( $('<a class="preview"/>') .html( js.core.translate("default.preview" ,js.core.userLocale) ) .attr('href','/app/'+js.core.userLocale +'/paragraph/render/'+input.attr( "value")) .attr('target','_blank') ); } } innerButtonsSelect.on( "click", function(evt) { element.find( "label" ).removeClass("selected"); $(evt.target.parentNode.parentNode.parentNode).addClass("selected"); } ); } ); var eleRow, eleRowsContainer = $('<div/>').appendTo(element); element.find( "label" ).each( function(idxItem,eleItem) { if( idxItem%itemsPerRow==0 ) { eleRow = $('<div />').appendTo(eleRowsContainer); } eleRow.append(eleItem); } ); $(eleRowsContainer).vslider({"items":"div", "itemheight":( selectType == 'local' ? 300 : 255 )}); { setTimeout( function(){ $('.ui-vslider').vslider('refresh') },100 ); } }; global.Zork.prototype.layoutSelect.isElementConstructor = true; } ( window, jQuery, zork ) );
webriq/core
module/Paragraph/public/scripts/zork/layoutselect.js
JavaScript
bsd-3-clause
5,515
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Bill */ public class BackRightAutonomous extends CommandBase { public BackRightAutonomous() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
TeamSprocket/2013Robot
BackRightAutonomous.java
Java
bsd-3-clause
952
/** * Dialog to add a new visualization from any of your * existing tables. * */ cdb.admin.NewVisualizationDialogTableItem = cdb.core.View.extend({ events: { "click .remove" : "_onRemove" }, tagName: "li", className: "table", initialize: function() { _.bindAll(this, "_onRemove"); this.template = this.getTemplate('dashboard/views/new_visualization_dialog_table_item'); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this.$el; }, show: function() { this.$el.show(); }, _onRemove: function(e) { this.killEvent(e); this.clear(); this.trigger("remove", this); }, clear: function() { this.$el.hide(); } }); cdb.admin.NewVisualizationDialog = cdb.admin.BaseDialog.extend({ _MAX_LAYERS: 3, _TEXTS: { title: _t('Create visualization'), loading_data: _t('Loading data…'), description: _t('Select the layers you will use on this visualization (you will be able to add more later)'), new_vis_title: _t("Give a name to your visualization"), no_tables: _t("Looks like you don’t have any imported data in your account. To create your first \ visualization you will need to import at least a dataset.") }, events: cdb.core.View.extendEvents({ // do not remove "click .add" : "_onAddTableItem", }), initialize: function() { if (!this.options.user) { new Throw("No user specified when it is needed") } this.user = this.options.user; // Dialog options _.extend(this.options, { title: this._TEXTS.title, template_name: 'common/views/dialog_base', clean_on_hide: true, ok_button_classes: "button green hidden", ok_title: this._TEXTS.title, modal_type: "creation", modal_class: 'new_visualization_dialog', width: this.user.isInsideOrg() ? 502 : 464 }); // Set max layers if user has this parameter var max_user_layers = this.options.user.get('max_layers'); if (!isNaN(max_user_layers) && this._MAX_LAYERS != max_user_layers) { this._MAX_LAYERS = max_user_layers; } this.ok = this.options.ok; this.model = new cdb.core.Model(); this.model.bind("change:disabled", this._onToggleDisabled, this); // Collection to manage the tables this.table_items = new Backbone.Collection(); this.table_items.bind("add", this._addTableItem, this); this.table_items.bind("remove", this._onRemove, this); this.constructor.__super__.initialize.apply(this); this.setWizard(this.options.wizard_option); this.visualizations = new cdb.admin.Visualizations({ type: "derived" }); }, render_content: function() { this.$content = $("<div>"); var temp_content = this.getTemplate('dashboard/views/new_visualization_dialog'); this.$content.append(temp_content({ description: this._TEXTS.loading })); // Tables combo this.tableCombo = new cdb.ui.common.VisualizationsSelector({ model: this.visualizations, user: this.options.user }); this.$content.find('.tableListCombo').append(this.tableCombo.render().el); this.addView(this.tableCombo); this.disableOkButton(); this._loadTables(); return this.$content; }, _onToggleDisabled: function() { this.tableCombo[ this.model.get("disabled") ? "disable" : "enable" ]() this.$(".combo_wrapper")[( this.model.get("disabled") ? "addClass" : "removeClass" )]('disabled'); }, _loadTables: function() { this.visualizations.bind('reset', this._onReset, this); this.visualizations.options.set({ type: "table", per_page: 100000 }); var order = { data: { o: { updated_at: "desc" }, exclude_raster: true }}; this.visualizations.fetch(order); }, _onReset: function() { this.visualizations.unbind(null, null, this); // do this one time and one time only if (this.visualizations.size() == 0) { this.emptyState = true; this._showEmpyState(); } else { this.emptyState = false; this._showControls(); } }, _showEmpyState: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.no_tables); self.$el.find(".ok.button").removeClass("green").addClass("grey"); self.$el.find(".ok.button").html("Ok, let's import some data"); self.$el.find(".ok.button").fadeIn(250, function() { self.enableOkButton(); }); }); }, _showControls: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.description); self.$el.find(".combo_wrapper").addClass('active'); self.$el.find(".ok.button").fadeIn(250, function() { $(this).removeClass("hidden"); }); self.$el.find(".cancel").fadeIn(250); }); this._setupScroll(); }, _setupScroll: function() { this.$scrollPane = this.$el.find(".scrollpane"); this.$scrollPane.jScrollPane({ showArrows: true, animateScroll: true, animateDuration: 150 }); this.api = this.$scrollPane.data('jsp'); }, _cleanString: function(s, n) { if (s) { s = s.replace(/<(?:.|\n)*?>/gm, ''); // strip HTML tags s = s.substr(0, n-1) + (s.length > n ? '&hellip;' : ''); // truncate string } return s; }, _onAddTableItem: function(e) { this.killEvent(e); if (this.model.get("disabled")) return; var table = this.tableCombo.getSelected(); if (table) { var model = new cdb.core.Model(table); this.table_items.add(model); } }, _afterAddItem: function() { if (this.table_items.length >= this._MAX_LAYERS) { this.model.set("disabled", true); } }, _afterRemoveItem: function() { if (this.table_items.length < this._MAX_LAYERS) { this.model.set("disabled", false); } }, _addTableItem: function(model) { this.enableOkButton(); this._afterAddItem(); var view = new cdb.admin.NewVisualizationDialogTableItem({ model: model }); this.$(".tables").append(view.render()); view.bind("remove", this._onRemoveItem, this); view.show(); this._refreshScrollPane(); }, _onRemoveItem: function(item) { this.table_items.remove(item.model); this._refreshScrollPane(); this._afterRemoveItem(); }, _onRemove: function() { if (this.table_items.length == 0) this.disableOkButton(); }, _refreshScrollPane: function() { var self = this; this.$(".scrollpane").animate({ height: this.$(".tables").height() + 5 }, { duration: 150, complete: function() { self.api && self.api.reinitialise(); }}); }, _ok: function(ev) { this.killEvent(ev); if (this.emptyState) { this.hide(); this.trigger("navigate_tables", this); } else { if (this.table_items.length === 0) return; this.hide(); this._openNameVisualizationDialog(); } }, _openNameVisualizationDialog: function() { var selected_tables = this.table_items.pluck("vis_id"); var tables = _.compact( this.visualizations.map(function(m) { if (_.contains(selected_tables, m.get('id'))) { return m.get('table').name } return false; }) ); var dlg = new cdb.admin.NameVisualization({ msg: this._TEXTS.new_vis_title, onResponse: function(name) { var vis = new cdb.admin.Visualization(); vis.save({ name: name, tables: tables }).success(function() { window.location.href = vis.viewUrl(); }); } }); dlg.bind("will_open", function() { $("body").css({ overflow: "hidden" }); }, this); dlg.bind("was_removed", function() { $("body").css({ overflow: "auto" }); }, this); dlg.appendToBody().open(); }, clean: function() { $(".select2-drop.select2-drop-active").hide(); cdb.admin.BaseDialog.prototype.clean.call(this); } });
comilla/map
lib/assets/javascripts/cartodb/dashboard/visualizations/new_visualization_dialog.js
JavaScript
bsd-3-clause
8,143
/****************************************************************************** This source file is part of the Avogadro project. Copyright 2013 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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. ******************************************************************************/ #include <utilities/vtktesting/imageregressiontest.h> #include <avogadro/qtopengl/glwidget.h> #include <avogadro/rendering/geometrynode.h> #include <avogadro/rendering/spheregeometry.h> #include <avogadro/rendering/textlabel2d.h> #include <avogadro/rendering/textlabel3d.h> #include <avogadro/rendering/textproperties.h> #include <avogadro/core/vector.h> #include <QtOpenGL/QGLFormat> #include <QtWidgets/QApplication> #include <QtGui/QImage> #include <QtCore/QTimer> #include <iostream> using Avogadro::Vector2f; using Avogadro::Vector3f; using Avogadro::Vector2i; using Avogadro::Vector3ub; using Avogadro::Rendering::GeometryNode; using Avogadro::Rendering::TextLabel2D; using Avogadro::Rendering::TextLabel3D; using Avogadro::Rendering::TextProperties; using Avogadro::Rendering::SphereGeometry; using Avogadro::QtOpenGL::GLWidget; using Avogadro::VtkTesting::ImageRegressionTest; int qttextlabeltest(int argc, char *argv[]) { // Set up the default format for our GL contexts. QGLFormat defaultFormat = QGLFormat::defaultFormat(); defaultFormat.setSampleBuffers(true); QGLFormat::setDefaultFormat(defaultFormat); // Create and show widget QApplication app(argc, argv); GLWidget widget; widget.setGeometry(10, 10, 500, 500); widget.show(); // Create scene GeometryNode *geometry = new GeometryNode; widget.renderer().scene().rootNode().addChild(geometry); // Add a small sphere at the origin for reference: SphereGeometry *spheres = new SphereGeometry; spheres->addSphere(Vector3f::Zero(), Vector3ub(128, 128, 128), 0.1f); geometry->addDrawable(spheres); // Default text property: TextProperties tprop; // Test alignment: TextLabel3D *l3 = NULL; TextLabel2D *l2 = NULL; // 3D: tprop.setColorRgb(255, 0, 0); tprop.setAlign(TextProperties::HLeft, TextProperties::VTop); l3 = new TextLabel3D; l3->setText("Upper Left Anchor"); l3->setAnchor(Vector3f::Zero()); l3->setTextProperties(tprop); geometry->addDrawable(l3); tprop.setColorRgb(0, 255, 0); tprop.setAlign(TextProperties::HLeft, TextProperties::VBottom); l3 = new TextLabel3D; l3->setText("Bottom Left Anchor"); l3->setAnchor(Vector3f::Zero()); l3->setTextProperties(tprop); geometry->addDrawable(l3); tprop.setColorRgb(0, 0, 255); tprop.setAlign(TextProperties::HRight, TextProperties::VTop); l3 = new TextLabel3D; l3->setText("Upper Right Anchor"); l3->setAnchor(Vector3f::Zero()); l3->setTextProperties(tprop); geometry->addDrawable(l3); tprop.setColorRgb(255, 255, 0); tprop.setAlign(TextProperties::HRight, TextProperties::VBottom); l3 = new TextLabel3D; l3->setText("Bottom Right Anchor"); l3->setAnchor(Vector3f::Zero()); l3->setTextProperties(tprop); geometry->addDrawable(l3); tprop.setColorRgba(255, 255, 255, 220); tprop.setRotationDegreesCW(90.f); tprop.setAlign(TextProperties::HCenter, TextProperties::VCenter); l3 = new TextLabel3D; l3->setText("Centered Anchor (3D)"); l3->setAnchor(Vector3f::Zero()); l3->setTextProperties(tprop); l3->setRenderPass(Avogadro::Rendering::TranslucentPass); geometry->addDrawable(l3); tprop.setRotationDegreesCW(0.f); tprop.setAlpha(255); // 2D: tprop.setColorRgb(255, 0, 0); tprop.setAlign(TextProperties::HLeft, TextProperties::VTop); l2 = new TextLabel2D; l2->setText("Upper Left Corner"); l2->setAnchor(Vector2i(0, widget.height())); l2->setTextProperties(tprop); geometry->addDrawable(l2); tprop.setColorRgb(0, 255, 0); tprop.setAlign(TextProperties::HLeft, TextProperties::VBottom); l2 = new TextLabel2D; l2->setText("Bottom Left Corner"); l2->setAnchor(Vector2i(0, 0)); l2->setTextProperties(tprop); geometry->addDrawable(l2); tprop.setColorRgb(0, 0, 255); tprop.setAlign(TextProperties::HRight, TextProperties::VTop); l2 = new TextLabel2D; l2->setText("Upper Right Corner"); l2->setAnchor(Vector2i(widget.width(), widget.height())); l2->setTextProperties(tprop); geometry->addDrawable(l2); tprop.setColorRgb(255, 255, 0); tprop.setAlign(TextProperties::HRight, TextProperties::VBottom); l2 = new TextLabel2D; l2->setText("Bottom Right Corner"); l2->setAnchor(Vector2i(widget.width(), 0)); l2->setTextProperties(tprop); geometry->addDrawable(l2); tprop.setColorRgba(255, 255, 255, 220); tprop.setAlign(TextProperties::HCenter, TextProperties::VCenter); l2 = new TextLabel2D; l2->setText("Centered Anchor (2D)"); l2->setAnchor(Vector2i(widget.width() / 2, widget.height() / 2)); l2->setTextProperties(tprop); geometry->addDrawable(l2); // Test the TextLabel3D's radius feature: spheres->addSphere(Vector3f(0.f, 6.f, 0.f), Vector3ub(255, 255, 255), 1.f); tprop.setColorRgba(255, 128, 64, 255); tprop.setRotationDegreesCW(90.f); l3 = new TextLabel3D; l3->setText("Clipped"); l3->setAnchor(Vector3f(0.f, 6.f, 0.f)); l3->setTextProperties(tprop); geometry->addDrawable(l3); tprop.setColorRgba(64, 128, 255, 255); tprop.setRotationDegreesCW(45.f); l3 = new TextLabel3D; l3->setText("Projected"); l3->setAnchor(Vector3f(0.f, 6.f, 0.f)); l3->setTextProperties(tprop); l3->setRadius(1.f); geometry->addDrawable(l3); // Make sure the widget renders the scene, and store it in a QImage. widget.raise(); widget.repaint(); // Run the application for a while, and then quit so we can save an image. QTimer timer; timer.setSingleShot(true); app.connect(&timer, SIGNAL(timeout()), SLOT(quit())); timer.start(200); app.exec(); // Grab the frame buffer of the GLWidget and save it to a QImage. QImage image = widget.grabFrameBuffer(false); // Set up the image regression test. ImageRegressionTest test(argc, argv); // Do the image threshold test, printing output to the std::cout for ctest. return test.imageThresholdTest(image, std::cout); }
wadejong/avogadrolibs
tests/qtopengl/qttextlabeltest.cpp
C++
bsd-3-clause
6,465
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0) on Wed May 09 10:30:52 EDT 2007 --> <TITLE> B-Index </TITLE> <META NAME="date" CONTENT="2007-05-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="B-Index"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-1.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR> <A NAME="_B_"><!-- --></A><H2> <B>B</B></H2> <DL> <DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class)"><B>buildTestSuite(Class&lt;?&gt;)</B></A> - Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A> <DD>Scan through a given class <code>c</code> to find any inner classes that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>. <DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class, java.lang.String)"><B>buildTestSuite(Class&lt;?&gt;, String)</B></A> - Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A> <DD>Scan through a given class <code>c</code> to find any inner classes that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>. </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-1.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR> </BODY> </HTML>
MSch/multithreadedtc-junit4
web/docs/index-files/index-2.html
HTML
bsd-3-clause
7,566
# Copyright 2020 The Cobalt Authors. 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 # # 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. # NOTE: # libdav1d's build process will generate this file and populate it with defines # that configure the project appropriately and set compilation flags. These # flags are migrated into Cobalt's gyp and ninja build process which makes this # file superfluous. However, we keep |config.asm| since the file is referenced # in the includes for several source files and to keep the overall code changes # low for ease of rebasing upstream changes from libdav1d.
youtube/cobalt
third_party/libdav1d/include/config.asm
Assembly
bsd-3-clause
1,067
/**************************************************************************** ** ** BSD 3-Clause License ** ** Copyright (c) 2017, bitdewy ** All rights reserved. ** ****************************************************************************/ #pragma once #include <QtCore/QMap> #include <QtGui/QIcon> class Property; class BoolPropertyManager; class BoolPropertyManagerPrivate { BoolPropertyManager* boolPropertyManagerPtr_; friend class BoolPropertyManager; public: BoolPropertyManagerPrivate(); BoolPropertyManagerPrivate(const BoolPropertyManagerPrivate&) = delete; BoolPropertyManagerPrivate& operator=(const BoolPropertyManagerPrivate&) = delete; QMap<const Property*, bool> values_; const QIcon checkedIcon_; const QIcon uncheckedIcon_; };
bitdewy/Ya
src/propertybrowser/propertymanager/private/boolpropertymanager_p.h
C
bsd-3-clause
813
# The purpose of these tests are to ensure that calling ufuncs with quantities # returns quantities with the right units, or raises exceptions. import warnings import pytest import numpy as np from numpy.testing.utils import assert_allclose from ... import units as u from ...tests.helper import raises from ...extern.six.moves import zip from ...utils.compat import NUMPY_LT_1_13 class TestUfuncCoverage(object): """Test that we cover all ufunc's""" def test_coverage(self): all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values() if type(ufunc) == np.ufunc]) from .. import quantity_helper as qh all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS | set(qh.UFUNC_HELPERS.keys())) assert all_np_ufuncs - all_q_ufuncs == set([]) assert all_q_ufuncs - all_np_ufuncs == set([]) class TestQuantityTrigonometricFuncs(object): """ Test trigonometric functions """ def test_sin_scalar(self): q = np.sin(30. * u.degree) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, 0.5) def test_sin_array(self): q = np.sin(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([0., 1. / np.sqrt(2.), 1.]), atol=1.e-15) def test_arcsin_scalar(self): q1 = 30. * u.degree q2 = np.arcsin(np.sin(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_arcsin_array(self): q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian q2 = np.arcsin(np.sin(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_sin_invalid_units(self): with pytest.raises(TypeError) as exc: np.sin(3. * u.m) assert exc.value.args[0] == ("Can only apply 'sin' function " "to quantities with angle units") def test_arcsin_invalid_units(self): with pytest.raises(TypeError) as exc: np.arcsin(3. * u.m) assert exc.value.args[0] == ("Can only apply 'arcsin' function to " "dimensionless quantities") def test_arcsin_no_warning_on_unscaled_quantity(self): a = 15 * u.kpc b = 27 * u.pc with warnings.catch_warnings(): warnings.filterwarnings('error') np.arcsin(b/a) def test_cos_scalar(self): q = np.cos(np.pi / 3. * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, 0.5) def test_cos_array(self): q = np.cos(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([1., 1. / np.sqrt(2.), 0.]), atol=1.e-15) def test_arccos_scalar(self): q1 = np.pi / 3. * u.radian q2 = np.arccos(np.cos(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_arccos_array(self): q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian q2 = np.arccos(np.cos(q1)).to(q1.unit) assert_allclose(q1.value, q2.value) def test_cos_invalid_units(self): with pytest.raises(TypeError) as exc: np.cos(3. * u.s) assert exc.value.args[0] == ("Can only apply 'cos' function " "to quantities with angle units") def test_arccos_invalid_units(self): with pytest.raises(TypeError) as exc: np.arccos(3. * u.s) assert exc.value.args[0] == ("Can only apply 'arccos' function to " "dimensionless quantities") def test_tan_scalar(self): q = np.tan(np.pi / 3. * u.radian) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.sqrt(3.)) def test_tan_array(self): q = np.tan(np.array([0., 45., 135., 180.]) * u.degree) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, np.array([0., 1., -1., 0.]), atol=1.e-15) def test_arctan_scalar(self): q = np.pi / 3. * u.radian assert np.arctan(np.tan(q)) def test_arctan_array(self): q = np.array([10., 30., 70., 80.]) * u.degree assert_allclose(np.arctan(np.tan(q)).to_value(q.unit), q.value) def test_tan_invalid_units(self): with pytest.raises(TypeError) as exc: np.tan(np.array([1, 2, 3]) * u.N) assert exc.value.args[0] == ("Can only apply 'tan' function " "to quantities with angle units") def test_arctan_invalid_units(self): with pytest.raises(TypeError) as exc: np.arctan(np.array([1, 2, 3]) * u.N) assert exc.value.args[0] == ("Can only apply 'arctan' function to " "dimensionless quantities") def test_arctan2_valid(self): q1 = np.array([10., 30., 70., 80.]) * u.m q2 = 2.0 * u.km assert np.arctan2(q1, q2).unit == u.radian assert_allclose(np.arctan2(q1, q2).value, np.arctan2(q1.value, q2.to_value(q1.unit))) q3 = q1 / q2 q4 = 1. at2 = np.arctan2(q3, q4) assert_allclose(at2.value, np.arctan2(q3.to_value(1), q4)) def test_arctan2_invalid(self): with pytest.raises(u.UnitsError) as exc: np.arctan2(np.array([1, 2, 3]) * u.N, 1. * u.s) assert "compatible dimensions" in exc.value.args[0] with pytest.raises(u.UnitsError) as exc: np.arctan2(np.array([1, 2, 3]) * u.N, 1.) assert "dimensionless quantities when other arg" in exc.value.args[0] def test_radians(self): q1 = np.deg2rad(180. * u.degree) assert_allclose(q1.value, np.pi) assert q1.unit == u.radian q2 = np.radians(180. * u.degree) assert_allclose(q2.value, np.pi) assert q2.unit == u.radian # the following doesn't make much sense in terms of the name of the # routine, but we check it gives the correct result. q3 = np.deg2rad(3. * u.radian) assert_allclose(q3.value, 3.) assert q3.unit == u.radian q4 = np.radians(3. * u.radian) assert_allclose(q4.value, 3.) assert q4.unit == u.radian with pytest.raises(TypeError): np.deg2rad(3. * u.m) with pytest.raises(TypeError): np.radians(3. * u.m) def test_degrees(self): # the following doesn't make much sense in terms of the name of the # routine, but we check it gives the correct result. q1 = np.rad2deg(60. * u.degree) assert_allclose(q1.value, 60.) assert q1.unit == u.degree q2 = np.degrees(60. * u.degree) assert_allclose(q2.value, 60.) assert q2.unit == u.degree q3 = np.rad2deg(np.pi * u.radian) assert_allclose(q3.value, 180.) assert q3.unit == u.degree q4 = np.degrees(np.pi * u.radian) assert_allclose(q4.value, 180.) assert q4.unit == u.degree with pytest.raises(TypeError): np.rad2deg(3. * u.m) with pytest.raises(TypeError): np.degrees(3. * u.m) class TestQuantityMathFuncs(object): """ Test other mathematical functions """ def test_multiply_scalar(self): assert np.multiply(4. * u.m, 2. / u.s) == 8. * u.m / u.s assert np.multiply(4. * u.m, 2.) == 8. * u.m assert np.multiply(4., 2. / u.s) == 8. / u.s def test_multiply_array(self): assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) == np.arange(0, 6., 2.) * u.m / u.s) @pytest.mark.parametrize('function', (np.divide, np.true_divide)) def test_divide_scalar(self, function): assert function(4. * u.m, 2. * u.s) == function(4., 2.) * u.m / u.s assert function(4. * u.m, 2.) == function(4., 2.) * u.m assert function(4., 2. * u.s) == function(4., 2.) / u.s @pytest.mark.parametrize('function', (np.divide, np.true_divide)) def test_divide_array(self, function): assert np.all(function(np.arange(3.) * u.m, 2. * u.s) == function(np.arange(3.), 2.) * u.m / u.s) def test_floor_divide_remainder_and_divmod(self): inch = u.Unit(0.0254 * u.m) dividend = np.array([1., 2., 3.]) * u.m divisor = np.array([3., 4., 5.]) * inch quotient = dividend // divisor remainder = dividend % divisor assert_allclose(quotient.value, [13., 19., 23.]) assert quotient.unit == u.dimensionless_unscaled assert_allclose(remainder.value, [0.0094, 0.0696, 0.079]) assert remainder.unit == dividend.unit quotient2 = np.floor_divide(dividend, divisor) remainder2 = np.remainder(dividend, divisor) assert np.all(quotient2 == quotient) assert np.all(remainder2 == remainder) quotient3, remainder3 = divmod(dividend, divisor) assert np.all(quotient3 == quotient) assert np.all(remainder3 == remainder) with pytest.raises(TypeError): divmod(dividend, u.km) with pytest.raises(TypeError): dividend // u.km with pytest.raises(TypeError): dividend % u.km if hasattr(np, 'divmod'): # not NUMPY_LT_1_13 quotient4, remainder4 = np.divmod(dividend, divisor) assert np.all(quotient4 == quotient) assert np.all(remainder4 == remainder) with pytest.raises(TypeError): np.divmod(dividend, u.km) def test_sqrt_scalar(self): assert np.sqrt(4. * u.m) == 2. * u.m ** 0.5 def test_sqrt_array(self): assert np.all(np.sqrt(np.array([1., 4., 9.]) * u.m) == np.array([1., 2., 3.]) * u.m ** 0.5) def test_square_scalar(self): assert np.square(4. * u.m) == 16. * u.m ** 2 def test_square_array(self): assert np.all(np.square(np.array([1., 2., 3.]) * u.m) == np.array([1., 4., 9.]) * u.m ** 2) def test_reciprocal_scalar(self): assert np.reciprocal(4. * u.m) == 0.25 / u.m def test_reciprocal_array(self): assert np.all(np.reciprocal(np.array([1., 2., 4.]) * u.m) == np.array([1., 0.5, 0.25]) / u.m) # cbrt only introduced in numpy 1.10 # heaviside only introduced in numpy 1.13 @pytest.mark.skipif("not hasattr(np, 'heaviside')") def test_heaviside_scalar(self): assert np.heaviside(0. * u.m, 0.5) == 0.5 * u.dimensionless_unscaled assert np.heaviside(0. * u.s, 25 * u.percent) == 0.25 * u.dimensionless_unscaled assert np.heaviside(2. * u.J, 0.25) == 1. * u.dimensionless_unscaled @pytest.mark.skipif("not hasattr(np, 'heaviside')") def test_heaviside_array(self): values = np.array([-1., 0., 0., +1.]) halfway = np.array([0.75, 0.25, 0.75, 0.25]) * u.dimensionless_unscaled assert np.all(np.heaviside(values * u.m, halfway * u.dimensionless_unscaled) == [0, 0.25, 0.75, +1.] * u.dimensionless_unscaled) @pytest.mark.skipif("not hasattr(np, 'cbrt')") def test_cbrt_scalar(self): assert np.cbrt(8. * u.m**3) == 2. * u.m @pytest.mark.skipif("not hasattr(np, 'cbrt')") def test_cbrt_array(self): # Calculate cbrt on both sides since on Windows the cube root of 64 # does not exactly equal 4. See 4388. values = np.array([1., 8., 64.]) assert np.all(np.cbrt(values * u.m**3) == np.cbrt(values) * u.m) def test_power_scalar(self): assert np.power(4. * u.m, 2.) == 16. * u.m ** 2 assert np.power(4., 200. * u.cm / u.m) == \ u.Quantity(16., u.dimensionless_unscaled) # regression check on #1696 assert np.power(4. * u.m, 0.) == 1. * u.dimensionless_unscaled def test_power_array(self): assert np.all(np.power(np.array([1., 2., 3.]) * u.m, 3.) == np.array([1., 8., 27.]) * u.m ** 3) # regression check on #1696 assert np.all(np.power(np.arange(4.) * u.m, 0.) == 1. * u.dimensionless_unscaled) # float_power only introduced in numpy 1.12 @pytest.mark.skipif("not hasattr(np, 'float_power')") def test_float_power_array(self): assert np.all(np.float_power(np.array([1., 2., 3.]) * u.m, 3.) == np.array([1., 8., 27.]) * u.m ** 3) # regression check on #1696 assert np.all(np.float_power(np.arange(4.) * u.m, 0.) == 1. * u.dimensionless_unscaled) @raises(ValueError) def test_power_array_array(self): np.power(4. * u.m, [2., 4.]) @raises(ValueError) def test_power_array_array2(self): np.power([2., 4.] * u.m, [2., 4.]) def test_power_array_array3(self): # Identical unit fractions are converted automatically to dimensionless # and should be allowed as base for np.power: #4764 q = [2., 4.] * u.m / u.m powers = [2., 4.] res = np.power(q, powers) assert np.all(res.value == q.value ** powers) assert res.unit == u.dimensionless_unscaled # The same holds for unit fractions that are scaled dimensionless. q2 = [2., 4.] * u.m / u.cm # Test also against different types of exponent for cls in (list, tuple, np.array, np.ma.array, u.Quantity): res2 = np.power(q2, cls(powers)) assert np.all(res2.value == q2.to_value(1) ** powers) assert res2.unit == u.dimensionless_unscaled # Though for single powers, we keep the composite unit. res3 = q2 ** 2 assert np.all(res3.value == q2.value ** 2) assert res3.unit == q2.unit ** 2 assert np.all(res3 == q2 ** [2, 2]) def test_power_invalid(self): with pytest.raises(TypeError) as exc: np.power(3., 4. * u.m) assert "raise something to a dimensionless" in exc.value.args[0] def test_copysign_scalar(self): assert np.copysign(3 * u.m, 1.) == 3. * u.m assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m assert np.copysign(3 * u.m, -1.) == -3. * u.m assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m def test_copysign_array(self): assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) == -np.array([1., 2., 3.]) * u.s) assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) == -np.array([1., 2., 3.]) * u.s) assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, np.array([-2., 2., -4.]) * u.m) == np.array([-1., 2., -3.]) * u.s) q = np.copysign(np.array([1., 2., 3.]), -3 * u.m) assert np.all(q == np.array([-1., -2., -3.])) assert not isinstance(q, u.Quantity) def test_ldexp_scalar(self): assert np.ldexp(4. * u.m, 2) == 16. * u.m def test_ldexp_array(self): assert np.all(np.ldexp(np.array([1., 2., 3.]) * u.m, [3, 2, 1]) == np.array([8., 8., 6.]) * u.m) def test_ldexp_invalid(self): with pytest.raises(TypeError): np.ldexp(3. * u.m, 4.) with pytest.raises(TypeError): np.ldexp(3., u.Quantity(4, u.m, dtype=int)) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_scalar(self, function): q = function(3. * u.m / (6. * u.m)) assert q.unit == u.dimensionless_unscaled assert q.value == function(0.5) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_array(self, function): q = function(np.array([2., 3., 6.]) * u.m / (6. * u.m)) assert q.unit == u.dimensionless_unscaled assert np.all(q.value == function(np.array([1. / 3., 1. / 2., 1.]))) # should also work on quantities that can be made dimensionless q2 = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm)) assert q2.unit == u.dimensionless_unscaled assert_allclose(q2.value, function(np.array([100. / 3., 100. / 2., 100.]))) @pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)) def test_exp_invalid_units(self, function): # Can't use exp() with non-dimensionless quantities with pytest.raises(TypeError) as exc: function(3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply '{0}' function to " "dimensionless quantities" .format(function.__name__)) def test_modf_scalar(self): q = np.modf(9. * u.m / (600. * u.cm)) assert q == (0.5 * u.dimensionless_unscaled, 1. * u.dimensionless_unscaled) def test_modf_array(self): v = np.arange(10.) * u.m / (500. * u.cm) q = np.modf(v) n = np.modf(v.to_value(u.dimensionless_unscaled)) assert q[0].unit == u.dimensionless_unscaled assert q[1].unit == u.dimensionless_unscaled assert all(q[0].value == n[0]) assert all(q[1].value == n[1]) def test_frexp_scalar(self): q = np.frexp(3. * u.m / (6. * u.m)) assert q == (np.array(0.5), np.array(0.0)) def test_frexp_array(self): q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m)) assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d in zip(q[0], q[1], [1. / 3., 1. / 2., 1.])) def test_frexp_invalid_units(self): # Can't use prod() with non-dimensionless quantities with pytest.raises(TypeError) as exc: np.frexp(3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities") # also does not work on quantities that can be made dimensionless with pytest.raises(TypeError) as exc: np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.cm)) assert exc.value.args[0] == ("Can only apply 'frexp' function to " "unscaled dimensionless quantities") @pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2)) def test_dimensionless_twoarg_array(self, function): q = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm), 1.) assert q.unit == u.dimensionless_unscaled assert_allclose(q.value, function(np.array([100. / 3., 100. / 2., 100.]), 1.)) @pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2)) def test_dimensionless_twoarg_invalid_units(self, function): with pytest.raises(TypeError) as exc: function(1. * u.km / u.s, 3. * u.m / u.s) assert exc.value.args[0] == ("Can only apply '{0}' function to " "dimensionless quantities" .format(function.__name__)) class TestInvariantUfuncs(object): # np.positive was only added in numpy 1.13. @pytest.mark.parametrize(('ufunc'), [np.absolute, np.fabs, np.conj, np.conjugate, np.negative, np.spacing, np.rint, np.floor, np.ceil] + [np.positive] if hasattr(np, 'positive') else []) def test_invariant_scalar(self, ufunc): q_i = 4.7 * u.m q_o = ufunc(q_i) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i.unit assert q_o.value == ufunc(q_i.value) @pytest.mark.parametrize(('ufunc'), [np.absolute, np.conjugate, np.negative, np.rint, np.floor, np.ceil]) def test_invariant_array(self, ufunc): q_i = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_o = ufunc(q_i) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i.unit assert np.all(q_o.value == ufunc(q_i.value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_scalar(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.km q_o = ufunc(q_i1, q_i2) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit))) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_array(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_i2 = np.array([10., -5., 1.e6]) * u.g / u.us q_o = ufunc(q_i1, q_i2) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit))) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_one_arbitrary(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s arbitrary_unit_value = np.array([0.]) q_o = ufunc(q_i1, arbitrary_unit_value) assert isinstance(q_o, u.Quantity) assert q_o.unit == q_i1.unit assert_allclose(q_o.value, ufunc(q_i1.value, arbitrary_unit_value)) @pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot, np.maximum, np.minimum, np.nextafter, np.remainder, np.mod, np.fmod]) def test_invariant_twoarg_invalid_units(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.s with pytest.raises(u.UnitsError) as exc: ufunc(q_i1, q_i2) assert "compatible dimensions" in exc.value.args[0] class TestComparisonUfuncs(object): @pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal]) def test_comparison_valid_units(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_i2 = np.array([10., -5., 1.e6]) * u.g / u.Ms q_o = ufunc(q_i1, q_i2) assert not isinstance(q_o, u.Quantity) assert q_o.dtype == np.bool assert np.all(q_o == ufunc(q_i1.value, q_i2.to_value(q_i1.unit))) q_o2 = ufunc(q_i1 / q_i2, 2.) assert not isinstance(q_o2, u.Quantity) assert q_o2.dtype == np.bool assert np.all(q_o2 == ufunc((q_i1 / q_i2) .to_value(u.dimensionless_unscaled), 2.)) # comparison with 0., inf, nan is OK even for dimensional quantities for arbitrary_unit_value in (0., np.inf, np.nan): ufunc(q_i1, arbitrary_unit_value) ufunc(q_i1, arbitrary_unit_value*np.ones(len(q_i1))) # and just for completeness ufunc(q_i1, np.array([0., np.inf, np.nan])) @pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal]) def test_comparison_invalid_units(self, ufunc): q_i1 = 4.7 * u.m q_i2 = 9.4 * u.s with pytest.raises(u.UnitsError) as exc: ufunc(q_i1, q_i2) assert "compatible dimensions" in exc.value.args[0] class TestInplaceUfuncs(object): @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_ufunc_inplace(self, value): # without scaling s = value * u.rad check = s np.sin(s, out=s) assert check is s assert check.unit == u.dimensionless_unscaled # with scaling s2 = (value * u.rad).to(u.deg) check2 = s2 np.sin(s2, out=s2) assert check2 is s2 assert check2.unit == u.dimensionless_unscaled assert_allclose(s.value, s2.value) @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_ufunc_inplace_2(self, value): """Check inplace works with non-quantity input and quantity output""" s = value * u.m check = s np.absolute(value, out=s) assert check is s assert np.all(check.value == np.absolute(value)) assert check.unit is u.dimensionless_unscaled np.sqrt(value, out=s) assert check is s assert np.all(check.value == np.sqrt(value)) assert check.unit is u.dimensionless_unscaled np.exp(value, out=s) assert check is s assert np.all(check.value == np.exp(value)) assert check.unit is u.dimensionless_unscaled np.arcsin(value/10., out=s) assert check is s assert np.all(check.value == np.arcsin(value/10.)) assert check.unit is u.radian @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_one_argument_two_output_ufunc_inplace(self, value): v = 100. * value * u.cm / u.m v_copy = v.copy() tmp = v.copy() check = v np.modf(v, tmp, v) # cannot use out1,out2 keywords with numpy 1.7 assert check is v assert check.unit == u.dimensionless_unscaled v2 = v_copy.to(u.dimensionless_unscaled) check2 = v2 np.modf(v2, tmp, v2) assert check2 is v2 assert check2.unit == u.dimensionless_unscaled # can also replace in last position if no scaling is needed v3 = v_copy.to(u.dimensionless_unscaled) check3 = v3 np.modf(v3, v3, tmp) assert check3 is v3 assert check3.unit == u.dimensionless_unscaled # in np<1.13, without __array_ufunc__, one cannot replace input with # first output when scaling v4 = v_copy.copy() if NUMPY_LT_1_13: with pytest.raises(TypeError): np.modf(v4, v4, tmp) else: check4 = v4 np.modf(v4, v4, tmp) assert check4 is v4 assert check4.unit == u.dimensionless_unscaled @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_two_argument_ufunc_inplace_1(self, value): s = value * u.cycle check = s s /= 2. assert check is s assert np.all(check.value == value / 2.) s /= u.s assert check is s assert check.unit == u.cycle / u.s s *= 2. * u.s assert check is s assert np.all(check == value * u.cycle) @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_two_argument_ufunc_inplace_2(self, value): s = value * u.cycle check = s np.arctan2(s, s, out=s) assert check is s assert check.unit == u.radian with pytest.raises(u.UnitsError): s += 1. * u.m assert check is s assert check.unit == u.radian np.arctan2(1. * u.deg, s, out=s) assert check is s assert check.unit == u.radian np.add(1. * u.deg, s, out=s) assert check is s assert check.unit == u.deg np.multiply(2. / u.s, s, out=s) assert check is s assert check.unit == u.deg / u.s def test_two_argument_ufunc_inplace_3(self): s = np.array([1., 2., 3.]) * u.dimensionless_unscaled np.add(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s) assert np.all(s.value == np.array([3., 6., 9.])) assert s.unit is u.dimensionless_unscaled np.arctan2(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s) assert_allclose(s.value, np.arctan2(1., 2.)) assert s.unit is u.radian @pytest.mark.skipif(NUMPY_LT_1_13, reason="numpy >=1.13 required.") @pytest.mark.parametrize(('value'), [1., np.arange(10.)]) def test_two_argument_two_output_ufunc_inplace(self, value): v = value * u.m divisor = 70.*u.cm v1 = v.copy() tmp = v.copy() check = np.divmod(v1, divisor, out=(tmp, v1)) assert check[0] is tmp and check[1] is v1 assert tmp.unit == u.dimensionless_unscaled assert v1.unit == v.unit v2 = v.copy() check2 = np.divmod(v2, divisor, out=(v2, tmp)) assert check2[0] is v2 and check2[1] is tmp assert v2.unit == u.dimensionless_unscaled assert tmp.unit == v.unit v3a = v.copy() v3b = v.copy() check3 = np.divmod(v3a, divisor, out=(v3a, v3b)) assert check3[0] is v3a and check3[1] is v3b assert v3a.unit == u.dimensionless_unscaled assert v3b.unit == v.unit def test_ufunc_inplace_non_contiguous_data(self): # ensure inplace works also for non-contiguous data (closes #1834) s = np.arange(10.) * u.m s_copy = s.copy() s2 = s[::2] s2 += 1. * u.cm assert np.all(s[::2] > s_copy[::2]) assert np.all(s[1::2] == s_copy[1::2]) def test_ufunc_inplace_non_standard_dtype(self): """Check that inplace operations check properly for casting. First two tests that check that float32 is kept close #3976. """ a1 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32) a1 *= np.float32(10) assert a1.unit is u.m assert a1.dtype == np.float32 a2 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32) a2 += (20.*u.km) assert a2.unit is u.m assert a2.dtype == np.float32 # For integer, in-place only works if no conversion is done. a3 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32) a3 += u.Quantity(10, u.m, dtype=np.int64) assert a3.unit is u.m assert a3.dtype == np.int32 a4 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32) with pytest.raises(TypeError): a4 += u.Quantity(10, u.mm, dtype=np.int64) @pytest.mark.xfail("NUMPY_LT_1_13") class TestUfuncAt(object): """Test that 'at' method for ufuncs (calculates in-place at given indices) For Quantities, since calculations are in-place, it makes sense only if the result is still a quantity, and if the unit does not have to change """ def test_one_argument_ufunc_at(self): q = np.arange(10.) * u.m i = np.array([1, 2]) qv = q.value.copy() np.negative.at(q, i) np.negative.at(qv, i) assert np.all(q.value == qv) assert q.unit is u.m # cannot change from quantity to bool array with pytest.raises(TypeError): np.isfinite.at(q, i) # for selective in-place, cannot change the unit with pytest.raises(u.UnitsError): np.square.at(q, i) # except if the unit does not change (i.e., dimensionless) d = np.arange(10.) * u.dimensionless_unscaled dv = d.value.copy() np.square.at(d, i) np.square.at(dv, i) assert np.all(d.value == dv) assert d.unit is u.dimensionless_unscaled d = np.arange(10.) * u.dimensionless_unscaled dv = d.value.copy() np.log.at(d, i) np.log.at(dv, i) assert np.all(d.value == dv) assert d.unit is u.dimensionless_unscaled # also for sine it doesn't work, even if given an angle a = np.arange(10.) * u.radian with pytest.raises(u.UnitsError): np.sin.at(a, i) # except, for consistency, if we have made radian equivalent to # dimensionless (though hopefully it will never be needed) av = a.value.copy() with u.add_enabled_equivalencies(u.dimensionless_angles()): np.sin.at(a, i) np.sin.at(av, i) assert_allclose(a.value, av) # but we won't do double conversion ad = np.arange(10.) * u.degree with pytest.raises(u.UnitsError): np.sin.at(ad, i) def test_two_argument_ufunc_at(self): s = np.arange(10.) * u.m i = np.array([1, 2]) check = s.value.copy() np.add.at(s, i, 1.*u.km) np.add.at(check, i, 1000.) assert np.all(s.value == check) assert s.unit is u.m with pytest.raises(u.UnitsError): np.add.at(s, i, 1.*u.s) # also raise UnitsError if unit would have to be changed with pytest.raises(u.UnitsError): np.multiply.at(s, i, 1*u.s) # but be fine if it does not s = np.arange(10.) * u.m check = s.value.copy() np.multiply.at(s, i, 2.*u.dimensionless_unscaled) np.multiply.at(check, i, 2) assert np.all(s.value == check) s = np.arange(10.) * u.m np.multiply.at(s, i, 2.) assert np.all(s.value == check) # of course cannot change class of data either with pytest.raises(TypeError): np.greater.at(s, i, 1.*u.km) @pytest.mark.xfail("NUMPY_LT_1_13") class TestUfuncReduceReduceatAccumulate(object): """Test 'reduce', 'reduceat' and 'accumulate' methods for ufuncs For Quantities, it makes sense only if the unit does not have to change """ def test_one_argument_ufunc_reduce_accumulate(self): # one argument cannot be used s = np.arange(10.) * u.radian i = np.array([0, 5, 1, 6]) with pytest.raises(ValueError): np.sin.reduce(s) with pytest.raises(ValueError): np.sin.accumulate(s) with pytest.raises(ValueError): np.sin.reduceat(s, i) def test_two_argument_ufunc_reduce_accumulate(self): s = np.arange(10.) * u.m i = np.array([0, 5, 1, 6]) check = s.value.copy() s_add_reduce = np.add.reduce(s) check_add_reduce = np.add.reduce(check) assert s_add_reduce.value == check_add_reduce assert s_add_reduce.unit is u.m s_add_accumulate = np.add.accumulate(s) check_add_accumulate = np.add.accumulate(check) assert np.all(s_add_accumulate.value == check_add_accumulate) assert s_add_accumulate.unit is u.m s_add_reduceat = np.add.reduceat(s, i) check_add_reduceat = np.add.reduceat(check, i) assert np.all(s_add_reduceat.value == check_add_reduceat) assert s_add_reduceat.unit is u.m # reduce(at) or accumulate on comparisons makes no sense, # as intermediate result is not even a Quantity with pytest.raises(TypeError): np.greater.reduce(s) with pytest.raises(TypeError): np.greater.accumulate(s) with pytest.raises(TypeError): np.greater.reduceat(s, i) # raise UnitsError if unit would have to be changed with pytest.raises(u.UnitsError): np.multiply.reduce(s) with pytest.raises(u.UnitsError): np.multiply.accumulate(s) with pytest.raises(u.UnitsError): np.multiply.reduceat(s, i) # but be fine if it does not s = np.arange(10.) * u.dimensionless_unscaled check = s.value.copy() s_multiply_reduce = np.multiply.reduce(s) check_multiply_reduce = np.multiply.reduce(check) assert s_multiply_reduce.value == check_multiply_reduce assert s_multiply_reduce.unit is u.dimensionless_unscaled s_multiply_accumulate = np.multiply.accumulate(s) check_multiply_accumulate = np.multiply.accumulate(check) assert np.all(s_multiply_accumulate.value == check_multiply_accumulate) assert s_multiply_accumulate.unit is u.dimensionless_unscaled s_multiply_reduceat = np.multiply.reduceat(s, i) check_multiply_reduceat = np.multiply.reduceat(check, i) assert np.all(s_multiply_reduceat.value == check_multiply_reduceat) assert s_multiply_reduceat.unit is u.dimensionless_unscaled @pytest.mark.xfail("NUMPY_LT_1_13") class TestUfuncOuter(object): """Test 'outer' methods for ufuncs Just a few spot checks, since it uses the same code as the regular ufunc call """ def test_one_argument_ufunc_outer(self): # one argument cannot be used s = np.arange(10.) * u.radian with pytest.raises(ValueError): np.sin.outer(s) def test_two_argument_ufunc_outer(self): s1 = np.arange(10.) * u.m s2 = np.arange(2.) * u.s check1 = s1.value check2 = s2.value s12_multiply_outer = np.multiply.outer(s1, s2) check12_multiply_outer = np.multiply.outer(check1, check2) assert np.all(s12_multiply_outer.value == check12_multiply_outer) assert s12_multiply_outer.unit == s1.unit * s2.unit # raise UnitsError if appropriate with pytest.raises(u.UnitsError): np.add.outer(s1, s2) # but be fine if it does not s3 = np.arange(2.) * s1.unit check3 = s3.value s13_add_outer = np.add.outer(s1, s3) check13_add_outer = np.add.outer(check1, check3) assert np.all(s13_add_outer.value == check13_add_outer) assert s13_add_outer.unit is s1.unit s13_greater_outer = np.greater.outer(s1, s3) check13_greater_outer = np.greater.outer(check1, check3) assert type(s13_greater_outer) is np.ndarray assert np.all(s13_greater_outer == check13_greater_outer)
AustereCuriosity/astropy
astropy/units/tests/test_quantity_ufuncs.py
Python
bsd-3-clause
38,162
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>messageStream property - TorrentClientManager class - hetimatorrent library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the messageStream property from the TorrentClientManager class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li> <li><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></li> <li class="self-crumb">messageStream</li> </ol> <div class="self-name">messageStream</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">hetimatorrent</a></li> <li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li> <li><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></li> <li class="self-crumb">messageStream</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">property</div> messageStream </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">hetimatorrent</a></h5> <h5><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></h5> <h5><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></h5> <ol> <li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#instance-properties">Properties</a></li> <li><a href="hetimatorrent/TorrentClientManager/globalIp.html">globalIp</a> </li> <li><a href="hetimatorrent/TorrentClientManager/globalPort.html">globalPort</a> </li> <li><a href="hetimatorrent/TorrentClientManager/isStart.html">isStart</a> </li> <li><a href="hetimatorrent/TorrentClientManager/localIp.html">localIp</a> </li> <li><a href="hetimatorrent/TorrentClientManager/localPort.html">localPort</a> </li> <li><a href="hetimatorrent/TorrentClientManager/messageStream.html">messageStream</a> </li> <li><a href="hetimatorrent/TorrentClientManager/onReceiveEvent.html">onReceiveEvent</a> </li> <li><a href="hetimatorrent/TorrentClientManager/onReceiveSignal.html">onReceiveSignal</a> </li> <li><a href="hetimatorrent/TorrentClientManager/rawclients.html">rawclients</a> </li> <li><a href="hetimatorrent/TorrentClientManager/verbose.html">verbose</a> </li> <li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#constructors">Constructors</a></li> <li><a href="hetimatorrent/TorrentClientManager/TorrentClientManager.html">TorrentClientManager</a></li> <li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#methods">Methods</a></li> <li><a href="hetimatorrent/TorrentClientManager/addTorrentClientWithDelegationToAccept.html">addTorrentClientWithDelegationToAccept</a> </li> <li><a href="hetimatorrent/TorrentClientManager/getTorrentClientFromInfoHash.html">getTorrentClientFromInfoHash</a> </li> <li><a href="hetimatorrent/TorrentClientManager/log.html">log</a> </li> <li><a href="hetimatorrent/TorrentClientManager/start.html">start</a> </li> <li><a href="hetimatorrent/TorrentClientManager/stop.html">stop</a> </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">StreamController&lt;<a href="hetimatorrent.torrent.client.message/TorrentClientMessage-class.html">TorrentClientMessage</a>&gt;</span> <span class="name ">messageStream</span> <div class="readable-writable"> read / write </div> </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> hetimatorrent 0.0.1 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
kyorohiro/dart_hetimatorrent
doc/api/hetimatorrent/TorrentClientManager/messageStream.html
HTML
bsd-3-clause
6,287
// Copyright 2019 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 "third_party/blink/public/common/page/content_to_visible_time_reporter.h" #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/strings/strcat.h" #include "base/trace_event/trace_event.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom.h" #include "ui/gfx/presentation_feedback.h" namespace blink { namespace { // Used to generate unique "TabSwitching::Latency" event ids. Note: The address // of ContentToVisibleTimeReporter can't be used as an id because a single // ContentToVisibleTimeReporter can generate multiple overlapping events. int g_num_trace_events_in_process = 0; const char* GetHistogramSuffix( bool has_saved_frames, const mojom::RecordContentToVisibleTimeRequest& start_state) { if (has_saved_frames) return "WithSavedFrames"; if (start_state.destination_is_loaded) { return "NoSavedFrames_Loaded"; } else { return "NoSavedFrames_NotLoaded"; } } void ReportUnOccludedMetric(const base::TimeTicks requested_time, const gfx::PresentationFeedback& feedback) { const base::TimeDelta delta = feedback.timestamp - requested_time; UMA_HISTOGRAM_TIMES("Aura.WebContentsWindowUnOccludedTime", delta); } void RecordBackForwardCacheRestoreMetric( const base::TimeTicks requested_time, const gfx::PresentationFeedback& feedback) { const base::TimeDelta delta = feedback.timestamp - requested_time; // Histogram to record the content to visible duration after restoring a page // from back-forward cache. Here min, max bucket size are same as the // "PageLoad.PaintTiming.NavigationToFirstContentfulPaint" metric. base::UmaHistogramCustomTimes( "BackForwardCache.Restore.NavigationToFirstPaint", delta, base::Milliseconds(10), base::Minutes(10), 100); } } // namespace void UpdateRecordContentToVisibleTimeRequest( mojom::RecordContentToVisibleTimeRequest const& from, mojom::RecordContentToVisibleTimeRequest& to) { to.event_start_time = std::min(to.event_start_time, from.event_start_time); to.destination_is_loaded |= from.destination_is_loaded; to.show_reason_tab_switching |= from.show_reason_tab_switching; to.show_reason_unoccluded |= from.show_reason_unoccluded; to.show_reason_bfcache_restore |= from.show_reason_bfcache_restore; } ContentToVisibleTimeReporter::ContentToVisibleTimeReporter() : is_tab_switch_metric2_feature_enabled_( base::FeatureList::IsEnabled(blink::features::kTabSwitchMetrics2)) {} ContentToVisibleTimeReporter::~ContentToVisibleTimeReporter() = default; base::OnceCallback<void(const gfx::PresentationFeedback&)> ContentToVisibleTimeReporter::TabWasShown( bool has_saved_frames, mojom::RecordContentToVisibleTimeRequestPtr start_state, base::TimeTicks widget_visibility_request_timestamp) { DCHECK(!start_state->event_start_time.is_null()); DCHECK(!widget_visibility_request_timestamp.is_null()); DCHECK(!tab_switch_start_state_); DCHECK(widget_visibility_request_timestamp_.is_null()); // Invalidate previously issued callbacks, to avoid accessing a null // |tab_switch_start_state_|. // // TODO(https://crbug.com/1121339): Make sure that TabWasShown() is never // called twice without a call to TabWasHidden() in-between, and remove this // mitigation. weak_ptr_factory_.InvalidateWeakPtrs(); has_saved_frames_ = has_saved_frames; tab_switch_start_state_ = std::move(start_state); widget_visibility_request_timestamp_ = widget_visibility_request_timestamp; // |tab_switch_start_state_| is only reset by RecordHistogramsAndTraceEvents // once the metrics have been emitted. return base::BindOnce( &ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents, weak_ptr_factory_.GetWeakPtr(), false /* is_incomplete */, tab_switch_start_state_->show_reason_tab_switching, tab_switch_start_state_->show_reason_unoccluded, tab_switch_start_state_->show_reason_bfcache_restore); } base::OnceCallback<void(const gfx::PresentationFeedback&)> ContentToVisibleTimeReporter::TabWasShown( bool has_saved_frames, base::TimeTicks event_start_time, bool destination_is_loaded, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore, base::TimeTicks widget_visibility_request_timestamp) { return TabWasShown( has_saved_frames, mojom::RecordContentToVisibleTimeRequest::New( event_start_time, destination_is_loaded, show_reason_tab_switching, show_reason_unoccluded, show_reason_bfcache_restore), widget_visibility_request_timestamp); } void ContentToVisibleTimeReporter::TabWasHidden() { if (tab_switch_start_state_) { RecordHistogramsAndTraceEvents(true /* is_incomplete */, true /* show_reason_tab_switching */, false /* show_reason_unoccluded */, false /* show_reason_bfcache_restore */, gfx::PresentationFeedback::Failure()); weak_ptr_factory_.InvalidateWeakPtrs(); } } void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents( bool is_incomplete, bool show_reason_tab_switching, bool show_reason_unoccluded, bool show_reason_bfcache_restore, const gfx::PresentationFeedback& feedback) { DCHECK(tab_switch_start_state_); DCHECK(!widget_visibility_request_timestamp_.is_null()); // If the DCHECK fail, make sure RenderWidgetHostImpl::WasShown was triggered // for recording the event. DCHECK(show_reason_bfcache_restore || show_reason_unoccluded || show_reason_tab_switching); if (show_reason_bfcache_restore) { RecordBackForwardCacheRestoreMetric( tab_switch_start_state_->event_start_time, feedback); } if (show_reason_unoccluded) { ReportUnOccludedMetric(tab_switch_start_state_->event_start_time, feedback); } if (!show_reason_tab_switching) return; // Tab switching has occurred. auto tab_switch_result = TabSwitchResult::kSuccess; if (is_incomplete) tab_switch_result = TabSwitchResult::kIncomplete; else if (feedback.flags & gfx::PresentationFeedback::kFailure) tab_switch_result = TabSwitchResult::kPresentationFailure; const auto tab_switch_duration = feedback.timestamp - tab_switch_start_state_->event_start_time; // Record trace events. TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( "latency", "TabSwitching::Latency", TRACE_ID_LOCAL(g_num_trace_events_in_process), tab_switch_start_state_->event_start_time); TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP2( "latency", "TabSwitching::Latency", TRACE_ID_LOCAL(g_num_trace_events_in_process), feedback.timestamp, "result", tab_switch_result, "latency", tab_switch_duration.InMillisecondsF()); ++g_num_trace_events_in_process; const char* suffix = GetHistogramSuffix(has_saved_frames_, *tab_switch_start_state_); // Record result histogram. if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramEnumeration( base::StrCat({"Browser.Tabs.TabSwitchResult2.", suffix}), tab_switch_result); } else { base::UmaHistogramEnumeration( base::StrCat({"Browser.Tabs.TabSwitchResult.", suffix}), tab_switch_result); } // Record latency histogram. switch (tab_switch_result) { case TabSwitchResult::kSuccess: { if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramTimes( base::StrCat({"Browser.Tabs.TotalSwitchDuration2.", suffix}), tab_switch_duration); } else { base::UmaHistogramTimes( base::StrCat({"Browser.Tabs.TotalSwitchDuration.", suffix}), tab_switch_duration); } break; } case TabSwitchResult::kIncomplete: { if (is_tab_switch_metric2_feature_enabled_) { base::UmaHistogramTimes( base::StrCat( {"Browser.Tabs.TotalIncompleteSwitchDuration2.", suffix}), tab_switch_duration); } else { base::UmaHistogramTimes( base::StrCat( {"Browser.Tabs.TotalIncompleteSwitchDuration.", suffix}), tab_switch_duration); } break; } case TabSwitchResult::kPresentationFailure: { break; } } // Record legacy latency histogram. UMA_HISTOGRAM_TIMES( "MPArch.RWH_TabSwitchPaintDuration", feedback.timestamp - widget_visibility_request_timestamp_); // Reset tab switch information. has_saved_frames_ = false; tab_switch_start_state_.reset(); widget_visibility_request_timestamp_ = base::TimeTicks(); } } // namespace blink
nwjs/chromium.src
third_party/blink/common/page/content_to_visible_time_reporter.cc
C++
bsd-3-clause
9,156
#!/usr/bin/env python """ # Software License Agreement (BSD License) # # Copyright (c) 2012, University of California, Berkeley # All rights reserved. # Authors: Cameron Lee ([email protected]) and Dmitry Berenson ( [email protected]) # # 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 University of California, Berkeley 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 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. """ """ This node advertises an action which is used by the main lightning node (see run_lightning.py) to run the Retrieve and Repair portion of LightningROS. This node relies on a planner_stoppable type node to repair the paths, the PathTools library to retrieve paths from the library (this is not a separate node; just a python library that it calls), and the PathTools python library which calls the collision_checker service and advertises a topic for displaying stuff in RViz. """ import roslib import rospy import actionlib import threading from tools.PathTools import PlanTrajectoryWrapper, InvalidSectionWrapper, DrawPointsWrapper from pathlib.PathLibrary import * from lightning.msg import Float64Array, RRAction, RRResult from lightning.msg import StopPlanning, RRStats from lightning.srv import ManagePathLibrary, ManagePathLibraryResponse import sys import pickle import time # Name of this node. RR_NODE_NAME = "rr_node" # Name to use for stopping the repair planner. Published from this node. STOP_PLANNER_NAME = "stop_rr_planning" # Topic to subscribe to for stopping the whole node in the middle of processing. STOP_RR_NAME = "stop_all_rr" # Name of library managing service run from this node. MANAGE_LIBRARY = "manage_path_library" STATE_RETRIEVE, STATE_REPAIR, STATE_RETURN_PATH, STATE_FINISHED, STATE_FINISHED = (0, 1, 2, 3, 4) class RRNode: def __init__(self): # Retrieve ROS parameters and configuration and cosntruct various objects. self.robot_name = rospy.get_param("robot_name") self.planner_config_name = rospy.get_param("planner_config_name") self.current_joint_names = [] self.current_group_name = "" self.plan_trajectory_wrapper = PlanTrajectoryWrapper("rr", int(rospy.get_param("~num_rr_planners"))) self.invalid_section_wrapper = InvalidSectionWrapper() self.path_library = PathLibrary(rospy.get_param("~path_library_dir"), rospy.get_param("step_size"), node_size=int(rospy.get_param("~path_library_path_node_size")), sg_node_size=int(rospy.get_param("~path_library_sg_node_size")), dtw_dist=float(rospy.get_param("~dtw_distance"))) self.num_paths_checked = int(rospy.get_param("~num_paths_to_collision_check")) self.stop_lock = threading.Lock() self.stop = True self.rr_server = actionlib.SimpleActionServer(RR_NODE_NAME, RRAction, execute_cb=self._retrieve_repair, auto_start=False) self.rr_server.start() self.stop_rr_subscriber = rospy.Subscriber(STOP_RR_NAME, StopPlanning, self._stop_rr_planner) self.stop_rr_planner_publisher = rospy.Publisher(STOP_PLANNER_NAME, StopPlanning, queue_size=10) self.manage_library_service = rospy.Service(MANAGE_LIBRARY, ManagePathLibrary, self._do_manage_action) self.stats_pub = rospy.Publisher("rr_stats", RRStats, queue_size=10) self.repaired_sections_lock = threading.Lock() self.repaired_sections = [] self.working_lock = threading.Lock() #to ensure that node is not doing RR and doing a library management action at the same time #if draw_points is True, then display points in rviz self.draw_points = rospy.get_param("draw_points") if self.draw_points: self.draw_points_wrapper = DrawPointsWrapper() def _set_repaired_section(self, index, section): """ After you have done the path planning to repair a section, store the repaired path section. Args: index (int): the index corresponding to the section being repaired. section (path, list of list of float): A path to store. """ self.repaired_sections_lock.acquire() self.repaired_sections[index] = section self.repaired_sections_lock.release() def _call_planner(self, start, goal, planning_time): """ Calls a standard planner to plan between two points with an allowed planning time. Args: start (list of float): A joint configuration corresponding to the start position of the path. goal (list of float): The jount configuration corresponding to the goal position for the path. Returns: path: A list of joint configurations corresponding to the planned path. """ ret = None planner_number = self.plan_trajectory_wrapper.acquire_planner() if not self._need_to_stop(): ret = self.plan_trajectory_wrapper.plan_trajectory(start, goal, planner_number, self.current_joint_names, self.current_group_name, planning_time, self.planner_config_name) self.plan_trajectory_wrapper.release_planner(planner_number) return ret def _repair_thread(self, index, start, goal, start_index, goal_index, planning_time): """ Handles repairing a portion of the path. All that this function really does is to plan from scratch between the start and goal configurations and then store the planned path in the appropriate places and draws either the repaired path or, if the repair fails, the start and goal. Args: index (int): The index to pass to _set_repaired_section(), corresponding to which of the invalid sections of the path we are repairing. start (list of float): The start joint configuration to use. goal (list of float): The goal joint configuration to use. start_index (int): The index in the overall path corresponding to start. Only used for debugging info. goal_index (int): The index in the overall path corresponding to goal. Only used for debugging info. planning_time (float): Maximum allowed time to spend planning, in seconds. """ repaired_path = self._call_planner(start, goal, planning_time) if self.draw_points: if repaired_path is not None and len(repaired_path) > 0: rospy.loginfo("RR action server: got repaired section with start = %s, goal = %s" % (repaired_path[0], repaired_path[-1])) self.draw_points_wrapper.draw_points(repaired_path, self.current_group_name, "repaired"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0, 0.01) else: if self.draw_points: rospy.loginfo("RR action server: path repair for section (%i, %i) failed, start = %s, goal = %s" % (start_index, goal_index, start, goal)) self.draw_points_wrapper.draw_points([start, goal], self.current_group_name, "failed_repair"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0) if self._need_to_stop(): self._set_repaired_section(index, None) else: self._set_repaired_section(index, repaired_path) def _need_to_stop(self): self.stop_lock.acquire(); ret = self.stop; self.stop_lock.release(); return ret; def _set_stop_value(self, val): self.stop_lock.acquire(); self.stop = val; self.stop_lock.release(); def do_retrieved_path_drawing(self, projected, retrieved, invalid): """ Draws the points from the various paths involved in the planning in different colors in different namespaces. All of the arguments are lists of joint configurations, where each joint configuration is a list of joint angles. The only distinction between the different arguments being passed in are which color the points in question are being drawn in. Uses the DrawPointsWrapper to draw the points. Args: projected (list of list of float): List of points to draw as projected between the library path and the actual start/goal position. Will be drawn in blue. retrieved (list of list of float): The path retrieved straight from the path library. Will be drawn in white. invalid (list of list of float): List of points which were invalid. Will be drawn in red. """ if len(projected) > 0: if self.draw_points: self.draw_points_wrapper.draw_points(retrieved, self.current_group_name, "retrieved", DrawPointsWrapper.ANGLES, DrawPointsWrapper.WHITE, 0.1) projectionDisplay = projected[:projected.index(retrieved[0])]+projected[projected.index(retrieved[-1])+1:] self.draw_points_wrapper.draw_points(projectionDisplay, self.current_group_name, "projection", DrawPointsWrapper.ANGLES, DrawPointsWrapper.BLUE, 0.2) invalidDisplay = [] for invSec in invalid: invalidDisplay += projected[invSec[0]+1:invSec[-1]] self.draw_points_wrapper.draw_points(invalidDisplay, self.current_group_name, "invalid", DrawPointsWrapper.ANGLES, DrawPointsWrapper.RED, 0.2) def _retrieve_repair(self, action_goal): """ Callback which performs the full Retrieve and Repair for the path. """ self.working_lock.acquire() self.start_time = time.time() self.stats_msg = RRStats() self._set_stop_value(False) if self.draw_points: self.draw_points_wrapper.clear_points() rospy.loginfo("RR action server: RR got an action goal") s, g = action_goal.start, action_goal.goal res = RRResult() res.status.status = res.status.FAILURE self.current_joint_names = action_goal.joint_names self.current_group_name = action_goal.group_name projected, retrieved, invalid = [], [], [] repair_state = STATE_RETRIEVE self.stats_msg.init_time = time.time() - self.start_time # Go through the retrieve, repair, and return stages of the planning. # The while loop should only ever go through 3 iterations, one for each # stage. while not self._need_to_stop() and repair_state != STATE_FINISHED: if repair_state == STATE_RETRIEVE: start_retrieve = time.time() projected, retrieved, invalid = self.path_library.retrieve_path(s, g, self.num_paths_checked, self.robot_name, self.current_group_name, self.current_joint_names) self.stats_msg.retrieve_time.append(time.time() - start_retrieve) if len(projected) == 0: rospy.loginfo("RR action server: got an empty path for retrieve state") repair_state = STATE_FINISHED else: start_draw = time.time() if self.draw_points: self.do_retrieved_path_drawing(projected, retrieved, invalid) self.stats_msg.draw_time.append(time.time() - start_draw) repair_state = STATE_REPAIR elif repair_state == STATE_REPAIR: start_repair = time.time() repaired = self._path_repair(projected, action_goal.allowed_planning_time.to_sec(), invalid_sections=invalid) self.stats_msg.repair_time.append(time.time() - start_repair) if repaired is None: rospy.loginfo("RR action server: path repair didn't finish") repair_state = STATE_FINISHED else: repair_state = STATE_RETURN_PATH elif repair_state == STATE_RETURN_PATH: start_return = time.time() res.status.status = res.status.SUCCESS res.retrieved_path = [Float64Array(p) for p in retrieved] res.repaired_path = [Float64Array(p) for p in repaired] rospy.loginfo("RR action server: returning a path") repair_state = STATE_FINISHED self.stats_msg.return_time = time.time() - start_return if repair_state == STATE_RETRIEVE: rospy.loginfo("RR action server: stopped before it retrieved a path") elif repair_state == STATE_REPAIR: rospy.loginfo("RR action server: stopped before it could repair a retrieved path") elif repair_state == STATE_RETURN_PATH: rospy.loginfo("RR action server: stopped before it could return a repaired path") self.rr_server.set_succeeded(res) self.stats_msg.total_time = time.time() - self.start_time self.stats_pub.publish(self.stats_msg) self.working_lock.release() def _path_repair(self, original_path, planning_time, invalid_sections=None, use_parallel_repairing=True): """ Goes through each invalid section in a path and calls a planner to repair it, with the potential for multi-threading. Returns the repaired path. Args: original_path (path): The original path which needs repairing. planning_time (float): The maximum allowed planning time for each repair, in seconds. invalid_sections (list of pairs of indicies): The pairs of indicies describing the invalid sections. If None, then the invalid sections will be computed by this function. use_parallel_repairing (bool): Whether or not to use multi-threading. Returns: path: The repaired path. """ zeros_tuple = tuple([0 for i in xrange(len(self.current_joint_names))]) rospy.loginfo("RR action server: got path with %d points" % len(original_path)) if invalid_sections is None: invalid_sections = self.invalid_section_wrapper.getInvalidSectionsForPath(original_path, self.current_group_name) rospy.loginfo("RR action server: invalid sections: %s" % (str(invalid_sections))) if len(invalid_sections) > 0: if invalid_sections[0][0] == -1: rospy.loginfo("RR action server: Start is not a valid state...nothing can be done") return None if invalid_sections[-1][1] == len(original_path): rospy.loginfo("RR action server: Goal is not a valid state...nothing can be done") return None if use_parallel_repairing: #multi-threaded repairing self.repaired_sections = [None for i in xrange(len(invalid_sections))] #each thread replans an invalid section threadList = [] for i, sec in enumerate(invalid_sections): th = threading.Thread(target=self._repair_thread, args=(i, original_path[sec[0]], original_path[sec[-1]], sec[0], sec[-1], planning_time)) threadList.append(th) th.start() for th in threadList: th.join() #once all threads return, then the repaired sections can be combined for item in self.repaired_sections: if item is None: rospy.loginfo("RR action server: RR node was stopped during repair or repair failed") return None #replace invalid sections with replanned sections new_path = original_path[0:invalid_sections[0][0]] for i in xrange(len(invalid_sections)): new_path += self.repaired_sections[i] if i+1 < len(invalid_sections): new_path += original_path[invalid_sections[i][1]+1:invalid_sections[i+1][0]] new_path += original_path[invalid_sections[-1][1]+1:] self.repaired_sections = [] #reset repaired_sections else: #single-threaded repairing rospy.loginfo("RR action server: Got invalid sections: %s" % str(invalid_sections)) new_path = original_path[0:invalid_sections[0][0]] for i in xrange(len(invalid_sections)): if not self._need_to_stop(): #start_invalid and end_invalid must correspond to valid states when passed to the planner start_invalid, end_invalid = invalid_sections[i] rospy.loginfo("RR action server: Requesting path to replace from %d to %d" % (start_invalid, end_invalid)) repairedSection = self._call_planner(original_path[start_invalid], original_path[end_invalid]) if repairedSection is None: rospy.loginfo("RR action server: RR section repair was stopped or failed") return None rospy.loginfo("RR action server: Planner returned a trajectory of %d points for %d to %d" % (len(repairedSection), start_invalid, end_invalid)) new_path += repairedSection if i+1 < len(invalid_sections): new_path += original_path[end_invalid+1:invalid_sections[i+1][0]] else: rospy.loginfo("RR action server: RR was stopped while it was repairing the retrieved path") return None new_path += original_path[invalid_sections[-1][1]+1:] rospy.loginfo("RR action server: Trajectory after replan has %d points" % len(new_path)) else: new_path = original_path rospy.loginfo("RR action server: new trajectory has %i points" % (len(new_path))) return new_path def _stop_rr_planner(self, msg): self._set_stop_value(True) rospy.loginfo("RR action server: RR node got a stop message") self.stop_rr_planner_publisher.publish(msg) def _do_manage_action(self, request): """ Processes a ManagePathLibraryRequest as part of the ManagePathLibrary service. Basically, either stores a path in the library or deletes it. """ response = ManagePathLibraryResponse() response.result = response.FAILURE if request.robot_name == "" or len(request.joint_names) == 0: rospy.logerr("RR action server: robot name or joint names were not provided") return response self.working_lock.acquire() if request.action == request.ACTION_STORE: rospy.loginfo("RR action server: got a path to store in path library") if len(request.path_to_store) > 0: new_path = [p.positions for p in request.path_to_store] if len(request.retrieved_path) == 0: #PFS won so just store the path store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names) else: store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names, [p.positions for p in request.retrieved_path]) response.result = response.SUCCESS response.path_stored, response.num_library_paths = store_path_result else: response.message = "Path to store had no points" elif request.action == request.ACTION_DELETE_PATH: rospy.loginfo("RR action server: got a request to delete path %i in the path library" % (request.delete_id)) if self.path_library.delete_path_by_id(request.delete_id, request.robot_name, request.joint_names): response.result = response.SUCCESS else: response.message = "No path in the library had id %i" % (request.delete_id) elif request.action == request.ACTION_DELETE_LIBRARY: rospy.loginfo("RR action server: got a request to delete library corresponding to robot %s and joints %s" % (request.robot_name, request.joint_names)) if self.path_library.delete_library(request.robot_name, request.joint_names): response.result = response.SUCCESS else: response.message = "No library corresponding to robot %s and joint names %s exists" else: rospy.logerr("RR action server: manage path library request did not have a valid action set") self.working_lock.release() return response if __name__ == "__main__": try: rospy.init_node("rr_node") RRNode() rospy.loginfo("Retrieve-repair: ready") rospy.spin() except rospy.ROSInterruptException: pass
WPI-ARC/lightning_ros
scripts/RR_action_server.py
Python
bsd-3-clause
22,385
package de.uni.freiburg.iig.telematik.sewol.accesscontrol.rbac.lattice.graphic; import org.apache.commons.collections15.Factory; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; public class RoleGraphViewer { Graph<Integer, String> g; int nodeCount, edgeCount; Factory<Integer> vertexFactory; Factory<String> edgeFactory; /** Creates a new instance of SimpleGraphView */ public RoleGraphViewer() { // Graph<V, E> where V is the type of the vertices and E is the type of // the edges g = new SparseMultigraph<Integer, String>(); nodeCount = 0; edgeCount = 0; vertexFactory = new Factory<Integer>() { // My vertex factory public Integer create() { return nodeCount++; } }; edgeFactory = new Factory<String>() { // My edge factory public String create() { return "E" + edgeCount++; } }; } }
iig-uni-freiburg/SEWOL
src/de/uni/freiburg/iig/telematik/sewol/accesscontrol/rbac/lattice/graphic/RoleGraphViewer.java
Java
bsd-3-clause
874
/** * @author */ imports("Controls.Composite.Carousel"); using("System.Fx.Marquee"); var Carousel = Control.extend({ onChange: function (e) { var ul = this.find('.x-carousel-header'), t; if (t = ul.first(e.from)) t.removeClass('x-carousel-header-selected'); if(t = ul.first(e.to)) t.addClass('x-carousel-header-selected'); }, init: function (options) { var me = this; me.marquee = new Marquee(me, options.direction, options.loop, options.deferUpdate); if (options.duration != null) me.marquee.duration = options.duration; if (options.delay != null) me.marquee.delay = options.delay; me.marquee.on('changing', me.onChange, me); me.query('.x-carousel-header > li').setWidth(me.getWidth() / me.marquee.length).on(options.event || 'mouseover', function (e) { me.marquee.moveTo(this.index()); }); me.onChange({to: 0}); me.marquee.start(); } }).defineMethods("marquee", "moveTo moveBy start stop");
jplusui/jplusui-en
src/Controls/Composite/assets/scripts/Carousel.js
JavaScript
bsd-3-clause
994
#include <lib.h> #include <string.h> /* lsearch(3) and lfind(3) * * Author: Terrence W. Holm Sep. 1988 */ #include <stddef.h> char *lsearch(key, base, count, width, keycmp) char *key; char *base; unsigned *count; unsigned width; _PROTOTYPE( int (*keycmp), (const void *, const void *)); { char *entry; char *last = base + *count * width; for (entry = base; entry < last; entry += width) if (keycmp(key, entry) == 0) return(entry); bcopy(key, last, width); *count += 1; return(last); } char *lfind(key, base, count, width, keycmp) char *key; char *base; unsigned *count; unsigned width; _PROTOTYPE( int (*keycmp), (const void *, const void *)); { char *entry; char *last = base + *count * width; for (entry = base; entry < last; entry += width) if (keycmp(key, entry) == 0) return(entry); return((char *)NULL); }
macminix/MacMinix
src/lib/other/lsearch.c
C
bsd-3-clause
858
#!/usr/bin/env python from django.core.management import setup_environ import settings setup_environ(settings) import socket from trivia.models import * irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) irc.connect((settings.IRC_SERVER, settings.IRC_PORT)) def send(msg): irc.send(msg + "\r\n") print "{SENT} " + msg return def msg(user, msg): send("PRIVMSG " + user + " :" + msg) return def processline(line): parts = line.split(' :',1) args = parts[0].split(' ') if (len(parts) > 1): args.append(parts[1]) if args[0] == "PING": send("PONG :" + args[1]) return try: if args[3] == "!questions": questions = str(Question.objects.all()) msg(args[2], questions) return except IndexError: return # When we're done, remember to return. return send("USER " + (settings.IRC_NICKNAME + " ")*4) send("NICK " + settings.IRC_NICKNAME) for channel in settings.IRC_CHANNELS: send("JOIN " + channel) while True: # EXIST line = irc.recv(1024).rstrip() if "\r\n" in line: linesep = line.split() for l in linesep: processline(l) continue processline(line)
relrod/pib
bot.py
Python
bsd-3-clause
1,205
/// <reference path="../../src/CaseModel.ts" /> /// <reference path="../../src/CaseViewer.ts" /> /// <reference path="../../src/PlugInManager.ts" /> class AnnotationPlugIn extends AssureIt.PlugInSet { constructor(public plugInManager: AssureIt.PlugInManager) { super(plugInManager); this.HTMLRenderPlugIn = new AnnotationHTMLRenderPlugIn(plugInManager); } } class AnnotationHTMLRenderPlugIn extends AssureIt.HTMLRenderPlugIn { IsEnabled(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel) : boolean { return true; } Delegate(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel, element: JQuery) : boolean { if(caseModel.Annotations.length == 0) return; var text : string = ""; var p : {top: number; left: number} = element.position(); for(var i : number = 0; i < caseModel.Annotations.length; i++) { text += "@" + caseModel.Annotations[i].Name + "<br>"; } $('<div class="anno">' + '<p>' + text + '</p>' + '</div>') .css({position: 'absolute', 'font-size': 25, color: 'gray', top: p.top - 20, left: p.left + 80}).appendTo(element); return true; } }
assureit/AssureIt
plugins/Annotation/Annotation.ts
TypeScript
bsd-3-clause
1,118
import React from "react"; import { expect } from "chai"; import { mount } from "enzyme"; import { Provider } from "react-redux"; import Editor from "../../../src/notebook/providers/editor"; import { dummyStore } from "../../utils"; import { UPDATE_CELL_SOURCE, FOCUS_CELL_EDITOR } from "../../../src/notebook/constants"; describe("EditorProvider", () => { const store = dummyStore(); const setup = (id, cellFocused = true) => mount( <Provider store={store}> <Editor id={id} cellFocused={cellFocused} /> </Provider> ); it("can be constructed", () => { const component = setup("test"); expect(component).to.not.be.null; }); it("onChange updates cell source", () => new Promise(resolve => { const dispatch = action => { expect(action.id).to.equal("test"); expect(action.source).to.equal("i love nteract"); expect(action.type).to.equal(UPDATE_CELL_SOURCE); resolve(); }; store.dispatch = dispatch; const wrapper = setup("test"); const onChange = wrapper .findWhere(n => n.prop("onChange") !== undefined) .first() .prop("onChange"); onChange("i love nteract"); })); it("onFocusChange can update editor focus", () => new Promise(resolve => { const dispatch = action => { expect(action.id).to.equal("test"); expect(action.type).to.equal(FOCUS_CELL_EDITOR); resolve(); }; store.dispatch = dispatch; const wrapper = setup("test"); const onFocusChange = wrapper .findWhere(n => n.prop("onFocusChange") !== undefined) .first() .prop("onFocusChange"); onFocusChange(true); })); });
temogen/nteract
test/renderer/providers/editor-spec.js
JavaScript
bsd-3-clause
1,719
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in * the LICENSE file in the root directory of this source tree. An * additional grant of patent rights can be found in the PATENTS file * in the same directory. * */ #include <errno.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <stdint.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <assert.h> #include <limits.h> #include "child.h" #include "net.h" extern char** environ; struct internal_child_info { int flags; const struct child_start_info* csi; int* childfd; int pty_slave; }; __attribute__((noreturn)) static void child_child_1(void* arg) { struct internal_child_info* ci = arg; /* Resets O_CLOEXEC */ for (int i = 0; i < 3; ++i) xdup3nc(ci->childfd[i], i, 0); if (ci->csi->child_chdir && chdir(ci->csi->child_chdir) == -1) die_errno("chdir"); if (ci->flags & CHILD_SETSID) if (setsid() == (pid_t) -1) die_errno("setsid"); if (ci->pty_slave != -1) { if (ioctl(ci->pty_slave, TIOCSCTTY, 0) == -1) die_errno("TIOCSCTTY"); if (tcsetpgrp(ci->pty_slave, getpid()) == -1) die_errno("tcsetpgrp"); } for (int i = 0; i < NSIG; ++i) signal(i, SIG_DFL); sigset_t no_signals; VERIFY(sigemptyset(&no_signals) == 0); VERIFY(sigprocmask(SIG_SETMASK, &no_signals, NULL) == 0); if (ci->csi->pre_exec) ci->csi->pre_exec(ci->csi->pre_exec_data); xexecvpe(ci->csi->exename, ci->csi->argv, ci->csi->environ ?: (const char* const*) environ); } __attribute__((noreturn)) static void child_child(struct internal_child_info* ci) { struct errinfo ei = { 0 }; ei.want_msg = true; if (!catch_error(child_child_1, ci, &ei)) abort(); fprintf(stderr, "%s: %s\n", ei.prgname, ei.msg); fflush(stderr); _exit(127); // Do not allow errors to propagate further } static void child_cleanup(void* arg) { struct child* child = arg; if (!child->dead) { if (child->pty_master == NULL) { int sig = child->deathsig ?: SIGTERM; pid_t child_pid = child->pid; if (sig < 0) { /* Send to process group instead */ sig = -sig; child_pid = -child_pid; } (void) kill(child_pid, sig); } else { /* In the pty case, the system's automatic SIGHUP should * take care of the killing. */ fdh_destroy(child->pty_master); } if (!child->skip_cleanup_wait && !signal_quit_in_progress) child_wait(child); } } struct child* child_start(const struct child_start_info* csi) { struct child* child = xcalloc(sizeof (*child)); struct cleanup* cl_waiter = cleanup_allocate(); SCOPED_RESLIST(rl); int flags = csi->flags; int pty_master = -1; int pty_slave = -1; if (flags & (CHILD_PTY_STDIN | CHILD_PTY_STDOUT | CHILD_PTY_STDERR | CHILD_CTTY)) { flags |= (CHILD_CTTY | CHILD_SETSID); } if (flags & CHILD_CTTY) { pty_master = xopen("/dev/ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC, 0); if (grantpt(pty_master) || unlockpt(pty_master)) die_errno("grantpt/unlockpt"); #ifdef HAVE_PTSNAME // Yes, yes, ptsname is not thread-safe. We're // single-threaded. char* pty_slave_name = xstrdup(ptsname(pty_master)); #else int pty_slave_num; if (ioctl(pty_master, TIOCGPTN, &pty_slave_num) != 0) die_errno("TIOCGPTN"); char* pty_slave_name = xaprintf("/dev/pts/%d", pty_slave_num); #endif pty_slave = xopen(pty_slave_name, O_RDWR | O_NOCTTY | O_CLOEXEC, 0); if (csi->pty_setup) csi->pty_setup(pty_master, pty_slave, csi->pty_setup_data); } int childfd[3]; int parentfd[3]; if (flags & CHILD_SOCKETPAIR_STDIO) { flags &= ~(CHILD_PTY_STDIN | CHILD_PTY_STDOUT); xsocketpair(AF_UNIX, SOCK_STREAM, 0, &childfd[0], &parentfd[0]); childfd[1] = xdup(childfd[0]); parentfd[1] = xdup(parentfd[0]); } else { if (flags & CHILD_PTY_STDIN) { childfd[0] = xdup(pty_slave); parentfd[0] = xdup(pty_master); } else if (flags & CHILD_NULL_STDIN) { childfd[0] = xopen("/dev/null", O_RDONLY, 0); parentfd[0] = xopen("/dev/null", O_WRONLY, 0); } else { xpipe(&childfd[0], &parentfd[0]); } if (flags & CHILD_PTY_STDOUT) { childfd[1] = xdup(pty_slave); parentfd[1] = xdup(pty_master); } else if (flags & CHILD_NULL_STDOUT) { childfd[1] = xopen("/dev/null", O_WRONLY, 0); parentfd[1] = xopen("/dev/null", O_RDONLY, 0); } else { xpipe(&parentfd[1], &childfd[1]); } } // If child has a pty for both stdout and stderr, from our POV, it // writes only to stdout. if ((flags & CHILD_PTY_STDERR) && (flags & CHILD_PTY_STDOUT)) flags |= CHILD_MERGE_STDERR; if (flags & CHILD_MERGE_STDERR) { childfd[2] = xdup(childfd[1]); parentfd[2] = xopen("/dev/null", O_RDONLY, 0); } else if (flags & CHILD_PTY_STDERR) { childfd[2] = xdup(pty_slave); parentfd[2] = xdup(pty_master); } else if (flags & CHILD_INHERIT_STDERR) { childfd[2] = xdup(2); } else if (flags & CHILD_NULL_STDERR) { childfd[2] = xopen("/dev/null", O_WRONLY, 0); parentfd[2] = xopen("/dev/null", O_RDONLY, 0); } else { xpipe(&parentfd[2], &childfd[2]); } WITH_CURRENT_RESLIST(rl->parent); child->flags = flags; child->deathsig = csi->deathsig; if (pty_master != -1) child->pty_master = fdh_dup(pty_master); child->fd[0] = fdh_dup(parentfd[0]); child->fd[1] = fdh_dup(parentfd[1]); if ((flags & CHILD_INHERIT_STDERR) == 0) child->fd[2] = fdh_dup(parentfd[2]); // We need to block all signals until the child calls signal(2) to // reset its signal handlers to the default. If we didn't, the // child could run handlers we didn't expect. sigset_t all_blocked; sigset_t prev_blocked; VERIFY(sigfillset(&all_blocked) == 0); VERIFY(sigprocmask(SIG_SETMASK, &all_blocked, &prev_blocked) == 0); pid_t child_pid = fork(); if (child_pid == 0) { struct internal_child_info ci = { .flags = flags, .csi = csi, .pty_slave = pty_slave, .childfd = childfd, }; child_child(&ci); // Never returns } VERIFY(sigprocmask(SIG_SETMASK, &prev_blocked, NULL) == 0); if (child_pid == -1) die_errno("fork"); child->pid = child_pid; cleanup_commit(cl_waiter, child_cleanup, child); return child; } bool child_poll_death(struct child* child) { if (!child->dead) { int ret = waitpid(child->pid, &child->status, WNOHANG); if (ret < 0) die_errno("waitpid"); if (ret > 0) child->dead = true; } return child->dead; } int child_wait(struct child* child) { int ret; // N.B. THE COMMENTED CODE BELOW IS WRONG. // // do { // WITH_IO_SIGNALS_ALLOWED(); // ret = waitpid(child->pid, &child->status, 0); // } while (ret < 0 && errno == EINTR); // // It looks correct, doesn't it? // // Consider what happens if we get a fatal signal, say SIGINT, // immediately after a successful return from waitpid() and // before we restore the signal mask that blocks SIGINT. // SIGINT runs the global cleanup handlers, one of which calls // kill() on our subprocess's PID. (Normally, the assignment // to child->dead below prevents our calling kill().) When // waitpid() completes successfully, the kernel frees the // process table entry for the process waited on. Between the // waitpid() return and our call to kill(), another process // can move into that process table slot, resulting in our // subsequent kill() going to wrong process and killing an // innocent program. // // Instead, we first block SIGCHLD (in addition to signals like // SIGINT), then, _WITHOUT_ unblocking signals, call waitpid(..., // WNOHANG). If that succeeds, our child is dead and we remember // its status. If waitpid() indicates that our child is still // running, we then wait for signals; when the child dies, we loop // around and call waitpid() again. That waitpid() might fail if // a different child died, or if we got a non-SIGCHLD signal, but // eventually our child will die, waitpid() will succeed, and // we'll exit the loop. // sigset_t block_during_poll; if (!child->dead) { sigemptyset(&block_during_poll); for (int i = 1; i < NSIG; ++i) if (!sigismember(&signals_unblock_for_io, i)) sigaddset(&block_during_poll, i); sigdelset(&block_during_poll, SIGCHLD); } while (!child->dead) { ret = waitpid(child->pid, &child->status, WNOHANG); if (ret < 0) { // waitpid will fail if child->pid isn't really our child; // that means we have a bug somewhere, since it should be // a zombie until we wait for it. die_errno("waitpid(%u)", (unsigned) child->pid); } if (ret > 0) { child->dead = true; } else { sigsuspend(&block_during_poll); } } return child->status; } void child_kill(struct child* child, int signo) { if (!child->dead && kill(child->pid, signo) == -1) die_errno("kill"); } static bool any_poll_active_p(const struct pollfd* p, size_t n) { for (size_t i = 0; i < n; ++i) if (p[i].fd != -1) return true; return false; } struct child_communication* child_communicate( struct child* child, const void* data_for_child_in, size_t data_for_child_size) { const uint8_t* data_for_child = data_for_child_in; size_t bytes_consumed = 0; size_t chunk_size = 512; struct pollfd p[ARRAYSIZE(child->fd)]; memset(&p, 0, sizeof (p)); struct { struct cleanup* cl; uint8_t* buf; size_t pos; size_t sz; } ob[ARRAYSIZE(child->fd)-1]; memset(&ob, 0, sizeof (ob)); for (int i = 0; i < ARRAYSIZE(p); ++i) { int fd = child->fd[i]->fd; fd_set_blocking_mode(fd, non_blocking); p[i].fd = fd; p[i].events = (i == 0) ? POLLIN : POLLOUT; } for (;;) { if (p[0].fd != -1) { size_t nr_to_write = data_for_child_size - bytes_consumed; if (nr_to_write > 0) { ssize_t nr_written = write(p[0].fd, data_for_child + bytes_consumed, XMIN(nr_to_write, (size_t) SSIZE_MAX)); if (nr_written == -1 && !error_temporary_p(errno)) die_errno("write[child]"); bytes_consumed += XMAX(nr_written, 0); } if (bytes_consumed == data_for_child_size) { fdh_destroy(child->fd[0]); p[0].fd = -1; } } for (size_t i = 0; i < ARRAYSIZE(ob); ++i) { int fd = p[i+1].fd; if (fd == -1) continue; if (ob[i].pos == ob[i].sz) { struct cleanup* newcl = cleanup_allocate(); size_t newsz; if (SATADD(&newsz, ob[i].sz, chunk_size)) die(ERANGE, "too many bytes from child"); void* newbuf = realloc(ob[i].buf, newsz); if (newbuf == NULL) die(ENOMEM, "could not allocate iobuf"); cleanup_commit(newcl, free, newbuf); cleanup_forget(ob[i].cl); ob[i].cl = newcl; ob[i].buf = newbuf; ob[i].sz = newsz; } size_t to_read = ob[i].sz - ob[i].pos; ssize_t nr_read = read(fd, ob[i].buf + ob[i].pos, to_read); if (nr_read == -1 && !error_temporary_p(errno)) die_errno("read[child:%d]", fd); ob[i].pos += XMAX(0, nr_read); if (nr_read == 0) { fdh_destroy(child->fd[i+1]); p[i+1].fd = -1; } } if (!any_poll_active_p(p, ARRAYSIZE(p))) break; int rc; { WITH_IO_SIGNALS_ALLOWED(); rc = poll(p, ARRAYSIZE(p), -1); } if (rc == -1 && errno != EINTR) die_errno("poll"); } struct child_communication* com = xcalloc(sizeof (*com)); com->status = child_wait(child); com->bytes_consumed = bytes_consumed; for (size_t i = 0; i < ARRAYSIZE(ob); ++i) { com->out[i].bytes = ob[i].buf; com->out[i].nr = ob[i].pos; } return com; } bool child_status_success_p(int status) { return WIFEXITED(status) && WEXITSTATUS(status) == 0; }
dalinaum/fb-adb
child.c
C
bsd-3-clause
13,390
{-# LANGUAGE TemplateHaskell #-} {-| Contains TemplateHaskell stuff I don't want to recompile every time I make changes to other files, a pre-compiled header, so to say. Don't know if that even works. -} module FeedGipeda.THGenerated ( benchmarkClosure , stringDict , __remoteTable ) where import Control.Distributed.Process (Closure, Process, Static, liftIO) import Control.Distributed.Process.Closure (SerializableDict, functionTDict, mkClosure, remotable) import FeedGipeda.GitShell (SHA) import FeedGipeda.Repo (Repo) import qualified FeedGipeda.Slave as Slave import FeedGipeda.Types (Timeout) benchmarkProcess :: (String, Repo, SHA, Rational) -> Process String benchmarkProcess (benchmarkScript, repo, sha, timeout) = liftIO (Slave.benchmark benchmarkScript repo sha (fromRational timeout)) remotable ['benchmarkProcess] benchmarkClosure :: String -> Repo -> SHA -> Timeout -> Closure (Process String) benchmarkClosure benchmarkScript repo commit timeout = $(mkClosure 'benchmarkProcess) (benchmarkScript, repo, commit, toRational timeout) stringDict :: Static (SerializableDict String) stringDict = $(functionTDict 'benchmarkProcess)
sgraf812/feed-gipeda
src/FeedGipeda/THGenerated.hs
Haskell
bsd-3-clause
1,466
<?php namespace app\models; use Yii; /** * This is the model class for table "record". * * @property string $todaydetail * @property string $st_classmark * @property string $startday * @property string $endday * @property integer $totalday * @property string $country * @property string $countryEN * @property string $st_name * @property string $st_nameEN * @property string $gaokaohao * @property string $idcard * @property string $sex * @property string $st_year * @property string $st_class * @property string $academy * @property string $major * @property string $status * @property string $model * @property string $today */ class Record extends \yii\db\ActiveRecord { private static $_instance; public static function getinstance() { if(!(self::$_instance instanceof self)) { self::$_instance =new self(); } return self::$_instance; } /** * @inheritdoc */ public static function tableName() { return 'record'; } /** * @inheritdoc */ public function rules() { return [ [['todaydetail', 'st_classmark'], 'required'], [['idcard'],'string', 'length' =>18], [['startday', 'endday'],'string', 'length' =>10], [['totalday'], 'integer'], [['todaydetail', 'model', 'today'], 'string', 'max' => 50], [['st_classmark','refusereason','reason', 'country', 'countryEN', 'st_name', 'st_nameEN', 'gaokaohao', 'st_year', 'st_class', 'academy', 'major'], 'string', 'max' => 100], [['sex', 'status'], 'string', 'max' => 20] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'todaydetail' => '时间编号', 'today' => '申请时间(点击可排序)', 'st_classmark' => '学号', 'refusereason' => '拒绝理由(若批审核不通过时填写)', 'reason' => '申请理由(必填 例具体缘由:医保证明)', 'startday' => '出发日期', 'endday' => '来校报到日期', 'totalday' => '出国总天数', 'country' => '目的国家(中文)', 'countryEN' => '目的国家(英文)', 'st_name' => '学生姓名', 'st_nameEN' => '英文名(中文姓名拼音)', 'gaokaohao' => '高考报名号(由学生处填写)', 'idcard' => '身份证', 'sex' => '性别(male/female)', 'st_year' => '入学年份', 'st_class' => '班级编号', 'academy' => '学院', 'major' => '专业', 'status' => '状态(点击可排序)', 'model' => '申请类型', ]; } }
Jirachiii/sues_print
models/Record.php
PHP
bsd-3-clause
2,805
package com.michaelbaranov.microba.gradient; import java.awt.Color; import java.util.ArrayList; import java.util.List; import com.michaelbaranov.microba.common.AbstractBoundedTableModel; /** * A very basic implementation of {@link AbstractBoundedTableModel} used by * default by {@link GradientBar}. This implementation has bounds 0 - 100 and * is mutable. * * @author Michael Baranov * */ public class DefaultGradientModel extends AbstractBoundedTableModel { protected static final int POSITION_COLUMN = 0; protected static final int COLOR_COLUMN = 1; protected List positionList = new ArrayList(32); protected List colorList = new ArrayList(32); /** * Constructor. */ public DefaultGradientModel() { super(); positionList.add(new Integer(0)); colorList.add(Color.YELLOW); positionList.add(new Integer(50)); colorList.add(Color.RED); positionList.add(new Integer(100)); colorList.add(Color.GREEN); } public int getLowerBound() { return 0; } public int getUpperBound() { return 100; } public int getRowCount() { return positionList.size(); } public int getColumnCount() { return 2; } public Class getColumnClass(int columnIndex) { switch (columnIndex) { case POSITION_COLUMN: return Integer.class; case COLOR_COLUMN: return Color.class; } return super.getColumnClass(columnIndex); } public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case POSITION_COLUMN: return positionList.get(rowIndex); case COLOR_COLUMN: return colorList.get(rowIndex); } return null; } /** * Adds a color point. * * @param color * @param position */ public void add(Color color, int position) { colorList.add(color); positionList.add(new Integer(position)); fireTableDataChanged(); } /** * Removes a color point at specified index. * * @param index */ public void remove(int index) { colorList.remove(index); positionList.remove(index); fireTableDataChanged(); } /** * Removes all color points. */ public void clear() { colorList.clear(); positionList.clear(); fireTableDataChanged(); } }
ezegarra/microbrowser
microba/com/michaelbaranov/microba/gradient/DefaultGradientModel.java
Java
bsd-3-clause
2,149
/* Scala.js runtime support * Copyright 2013 LAMP/EPFL * Author: Sébastien Doeraene */ /* ---------------------------------- * * The top-level Scala.js environment * * ---------------------------------- */ //!if outputMode == ECMAScript51Global var ScalaJS = {}; //!endif // Get the environment info ScalaJS.env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {}; // Global scope ScalaJS.g = (typeof ScalaJS.env["global"] === "object" && ScalaJS.env["global"]) ? ScalaJS.env["global"] : ((typeof global === "object" && global && global["Object"] === Object) ? global : this); ScalaJS.env["global"] = ScalaJS.g; // Where to send exports //!if moduleKind == CommonJSModule ScalaJS.e = exports; //!else ScalaJS.e = (typeof ScalaJS.env["exportsNamespace"] === "object" && ScalaJS.env["exportsNamespace"]) ? ScalaJS.env["exportsNamespace"] : ScalaJS.g; //!endif ScalaJS.env["exportsNamespace"] = ScalaJS.e; // Freeze the environment info ScalaJS.g["Object"]["freeze"](ScalaJS.env); // Linking info - must be in sync with scala.scalajs.runtime.LinkingInfo ScalaJS.linkingInfo = { "envInfo": ScalaJS.env, "semantics": { //!if asInstanceOfs == Compliant "asInstanceOfs": 0, //!else //!if asInstanceOfs == Fatal "asInstanceOfs": 1, //!else "asInstanceOfs": 2, //!endif //!endif //!if arrayIndexOutOfBounds == Compliant "arrayIndexOutOfBounds": 0, //!else //!if arrayIndexOutOfBounds == Fatal "arrayIndexOutOfBounds": 1, //!else "arrayIndexOutOfBounds": 2, //!endif //!endif //!if moduleInit == Compliant "moduleInit": 0, //!else //!if moduleInit == Fatal "moduleInit": 1, //!else "moduleInit": 2, //!endif //!endif //!if floats == Strict "strictFloats": true, //!else "strictFloats": false, //!endif //!if productionMode == true "productionMode": true //!else "productionMode": false //!endif }, //!if outputMode == ECMAScript6 "assumingES6": true, //!else "assumingES6": false, //!endif "linkerVersion": "{{LINKER_VERSION}}" }; ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo); ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo["semantics"]); // Snapshots of builtins and polyfills //!if outputMode == ECMAScript6 ScalaJS.imul = ScalaJS.g["Math"]["imul"]; ScalaJS.fround = ScalaJS.g["Math"]["fround"]; ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"]; //!else ScalaJS.imul = ScalaJS.g["Math"]["imul"] || (function(a, b) { // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul const ah = (a >>> 16) & 0xffff; const al = a & 0xffff; const bh = (b >>> 16) & 0xffff; const bl = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }); ScalaJS.fround = ScalaJS.g["Math"]["fround"] || //!if floats == Strict (ScalaJS.g["Float32Array"] ? (function(v) { const array = new ScalaJS.g["Float32Array"](1); array[0] = v; return array[0]; }) : (function(v) { return ScalaJS.m.sjsr_package$().froundPolyfill__D__D(+v); })); //!else (function(v) { return +v; }); //!endif ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"] || (function(i) { // See Hacker's Delight, Section 5-3 if (i === 0) return 32; let r = 1; if ((i & 0xffff0000) === 0) { i <<= 16; r += 16; }; if ((i & 0xff000000) === 0) { i <<= 8; r += 8; }; if ((i & 0xf0000000) === 0) { i <<= 4; r += 4; }; if ((i & 0xc0000000) === 0) { i <<= 2; r += 2; }; return r + (i >> 31); }); //!endif // Other fields //!if outputMode == ECMAScript51Global ScalaJS.d = {}; // Data for types ScalaJS.a = {}; // Scala.js-defined JS class value accessors ScalaJS.b = {}; // Scala.js-defined JS class value fields ScalaJS.c = {}; // Scala.js constructors ScalaJS.h = {}; // Inheritable constructors (without initialization code) ScalaJS.s = {}; // Static methods ScalaJS.t = {}; // Static fields ScalaJS.f = {}; // Default methods ScalaJS.n = {}; // Module instances ScalaJS.m = {}; // Module accessors ScalaJS.is = {}; // isInstanceOf methods ScalaJS.isArrayOf = {}; // isInstanceOfArrayOf methods //!if asInstanceOfs != Unchecked ScalaJS.as = {}; // asInstanceOf methods ScalaJS.asArrayOf = {}; // asInstanceOfArrayOf methods //!endif ScalaJS.lastIDHash = 0; // last value attributed to an id hash code ScalaJS.idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!else let $lastIDHash = 0; // last value attributed to an id hash code //!if outputMode == ECMAScript6 const $idHashCodeMap = new ScalaJS.g["WeakMap"](); //!else const $idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!endif //!endif // Core mechanism ScalaJS.makeIsArrayOfPrimitive = function(primitiveData) { return function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && (obj.$classData.arrayBase === primitiveData)); } }; //!if asInstanceOfs != Unchecked ScalaJS.makeAsArrayOfPrimitive = function(isInstanceOfFunction, arrayEncodedName) { return function(obj, depth) { if (isInstanceOfFunction(obj, depth) || (obj === null)) return obj; else ScalaJS.throwArrayCastException(obj, arrayEncodedName, depth); } }; //!endif /** Encode a property name for runtime manipulation * Usage: * env.propertyName({someProp:0}) * Returns: * "someProp" * Useful when the property is renamed by a global optimizer (like Closure) * but we must still get hold of a string of that name for runtime * reflection. */ ScalaJS.propertyName = function(obj) { for (const prop in obj) return prop; }; // Runtime functions ScalaJS.isScalaJSObject = function(obj) { return !!(obj && obj.$classData); }; //!if asInstanceOfs != Unchecked ScalaJS.throwClassCastException = function(instance, classFullName) { //!if asInstanceOfs == Compliant throw new ScalaJS.c.jl_ClassCastException().init___T( instance + " is not an instance of " + classFullName); //!else throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable( new ScalaJS.c.jl_ClassCastException().init___T( instance + " is not an instance of " + classFullName)); //!endif }; ScalaJS.throwArrayCastException = function(instance, classArrayEncodedName, depth) { for (; depth; --depth) classArrayEncodedName = "[" + classArrayEncodedName; ScalaJS.throwClassCastException(instance, classArrayEncodedName); }; //!endif //!if arrayIndexOutOfBounds != Unchecked ScalaJS.throwArrayIndexOutOfBoundsException = function(i) { const msg = (i === null) ? null : ("" + i); //!if arrayIndexOutOfBounds == Compliant throw new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg); //!else throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable( new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg)); //!endif }; //!endif ScalaJS.noIsInstance = function(instance) { throw new ScalaJS.g["TypeError"]( "Cannot call isInstance() on a Class representing a raw JS trait/object"); }; ScalaJS.makeNativeArrayWrapper = function(arrayClassData, nativeArray) { return new arrayClassData.constr(nativeArray); }; ScalaJS.newArrayObject = function(arrayClassData, lengths) { return ScalaJS.newArrayObjectInternal(arrayClassData, lengths, 0); }; ScalaJS.newArrayObjectInternal = function(arrayClassData, lengths, lengthIndex) { const result = new arrayClassData.constr(lengths[lengthIndex]); if (lengthIndex < lengths.length-1) { const subArrayClassData = arrayClassData.componentData; const subLengthIndex = lengthIndex+1; const underlying = result.u; for (let i = 0; i < underlying.length; i++) { underlying[i] = ScalaJS.newArrayObjectInternal( subArrayClassData, lengths, subLengthIndex); } } return result; }; ScalaJS.objectToString = function(instance) { if (instance === void 0) return "undefined"; else return instance.toString(); }; ScalaJS.objectGetClass = function(instance) { switch (typeof instance) { case "string": return ScalaJS.d.T.getClassOf(); case "number": { const v = instance | 0; if (v === instance) { // is the value integral? if (ScalaJS.isByte(v)) return ScalaJS.d.jl_Byte.getClassOf(); else if (ScalaJS.isShort(v)) return ScalaJS.d.jl_Short.getClassOf(); else return ScalaJS.d.jl_Integer.getClassOf(); } else { if (ScalaJS.isFloat(instance)) return ScalaJS.d.jl_Float.getClassOf(); else return ScalaJS.d.jl_Double.getClassOf(); } } case "boolean": return ScalaJS.d.jl_Boolean.getClassOf(); case "undefined": return ScalaJS.d.sr_BoxedUnit.getClassOf(); default: if (instance === null) return instance.getClass__jl_Class(); else if (ScalaJS.is.sjsr_RuntimeLong(instance)) return ScalaJS.d.jl_Long.getClassOf(); else if (ScalaJS.isScalaJSObject(instance)) return instance.$classData.getClassOf(); else return null; // Exception? } }; ScalaJS.objectClone = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.clone__O(); else throw new ScalaJS.c.jl_CloneNotSupportedException().init___(); }; ScalaJS.objectNotify = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notify__V(); }; ScalaJS.objectNotifyAll = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notifyAll__V(); }; ScalaJS.objectFinalize = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) instance.finalize__V(); // else no-op }; ScalaJS.objectEquals = function(instance, rhs) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.equals__O__Z(rhs); else if (typeof instance === "number") return typeof rhs === "number" && ScalaJS.numberEquals(instance, rhs); else return instance === rhs; }; ScalaJS.numberEquals = function(lhs, rhs) { return (lhs === rhs) ? ( // 0.0.equals(-0.0) must be false lhs !== 0 || 1/lhs === 1/rhs ) : ( // are they both NaN? (lhs !== lhs) && (rhs !== rhs) ); }; ScalaJS.objectHashCode = function(instance) { switch (typeof instance) { case "string": return ScalaJS.m.sjsr_RuntimeString$().hashCode__T__I(instance); case "number": return ScalaJS.m.sjsr_Bits$().numberHashCode__D__I(instance); case "boolean": return instance ? 1231 : 1237; case "undefined": return 0; default: if (ScalaJS.isScalaJSObject(instance) || instance === null) return instance.hashCode__I(); //!if outputMode != ECMAScript6 else if (ScalaJS.idHashCodeMap === null) return 42; //!endif else return ScalaJS.systemIdentityHashCode(instance); } }; ScalaJS.comparableCompareTo = function(instance, rhs) { switch (typeof instance) { case "string": //!if asInstanceOfs != Unchecked ScalaJS.as.T(rhs); //!endif return instance === rhs ? 0 : (instance < rhs ? -1 : 1); case "number": //!if asInstanceOfs != Unchecked ScalaJS.as.jl_Number(rhs); //!endif return ScalaJS.m.jl_Double$().compare__D__D__I(instance, rhs); case "boolean": //!if asInstanceOfs != Unchecked ScalaJS.asBoolean(rhs); //!endif return instance - rhs; // yes, this gives the right result default: return instance.compareTo__O__I(rhs); } }; ScalaJS.charSequenceLength = function(instance) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["length"]); //!else return instance["length"] | 0; //!endif else return instance.length__I(); }; ScalaJS.charSequenceCharAt = function(instance, index) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["charCodeAt"](index)) & 0xffff; //!else return instance["charCodeAt"](index) & 0xffff; //!endif else return instance.charAt__I__C(index); }; ScalaJS.charSequenceSubSequence = function(instance, start, end) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.as.T(instance["substring"](start, end)); //!else return instance["substring"](start, end); //!endif else return instance.subSequence__I__I__jl_CharSequence(start, end); }; ScalaJS.booleanBooleanValue = function(instance) { if (typeof instance === "boolean") return instance; else return instance.booleanValue__Z(); }; ScalaJS.numberByteValue = function(instance) { if (typeof instance === "number") return (instance << 24) >> 24; else return instance.byteValue__B(); }; ScalaJS.numberShortValue = function(instance) { if (typeof instance === "number") return (instance << 16) >> 16; else return instance.shortValue__S(); }; ScalaJS.numberIntValue = function(instance) { if (typeof instance === "number") return instance | 0; else return instance.intValue__I(); }; ScalaJS.numberLongValue = function(instance) { if (typeof instance === "number") return ScalaJS.m.sjsr_RuntimeLong$().fromDouble__D__sjsr_RuntimeLong(instance); else return instance.longValue__J(); }; ScalaJS.numberFloatValue = function(instance) { if (typeof instance === "number") return ScalaJS.fround(instance); else return instance.floatValue__F(); }; ScalaJS.numberDoubleValue = function(instance) { if (typeof instance === "number") return instance; else return instance.doubleValue__D(); }; ScalaJS.isNaN = function(instance) { return instance !== instance; }; ScalaJS.isInfinite = function(instance) { return !ScalaJS.g["isFinite"](instance) && !ScalaJS.isNaN(instance); }; ScalaJS.doubleToInt = function(x) { return (x > 2147483647) ? (2147483647) : ((x < -2147483648) ? -2147483648 : (x | 0)); }; /** Instantiates a JS object with variadic arguments to the constructor. */ ScalaJS.newJSObjectWithVarargs = function(ctor, args) { // This basically emulates the ECMAScript specification for 'new'. const instance = ScalaJS.g["Object"]["create"](ctor.prototype); const result = ctor["apply"](instance, args); switch (typeof result) { case "string": case "number": case "boolean": case "undefined": case "symbol": return instance; default: return result === null ? instance : result; } }; ScalaJS.resolveSuperRef = function(initialProto, propName) { const getPrototypeOf = ScalaJS.g["Object"]["getPrototypeOf"]; const getOwnPropertyDescriptor = ScalaJS.g["Object"]["getOwnPropertyDescriptor"]; let superProto = getPrototypeOf(initialProto); while (superProto !== null) { const desc = getOwnPropertyDescriptor(superProto, propName); if (desc !== void 0) return desc; superProto = getPrototypeOf(superProto); } return void 0; }; ScalaJS.superGet = function(initialProto, self, propName) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const getter = desc["get"]; if (getter !== void 0) return getter["call"](self); else return desc["value"]; } return void 0; }; ScalaJS.superSet = function(initialProto, self, propName, value) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const setter = desc["set"]; if (setter !== void 0) { setter["call"](self, value); return void 0; } } throw new ScalaJS.g["TypeError"]("super has no setter '" + propName + "'."); }; //!if moduleKind == CommonJSModule ScalaJS.moduleDefault = function(m) { return (m && (typeof m === "object") && "default" in m) ? m["default"] : m; }; //!endif ScalaJS.propertiesOf = function(obj) { const result = []; for (const prop in obj) result["push"](prop); return result; }; ScalaJS.systemArraycopy = function(src, srcPos, dest, destPos, length) { const srcu = src.u; const destu = dest.u; //!if arrayIndexOutOfBounds != Unchecked if (srcPos < 0 || destPos < 0 || length < 0 || (srcPos > ((srcu.length - length) | 0)) || (destPos > ((destu.length - length) | 0))) { ScalaJS.throwArrayIndexOutOfBoundsException(null); } //!endif if (srcu !== destu || destPos < srcPos || (((srcPos + length) | 0) < destPos)) { for (let i = 0; i < length; i = (i + 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } else { for (let i = (length - 1) | 0; i >= 0; i = (i - 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } }; ScalaJS.systemIdentityHashCode = //!if outputMode != ECMAScript6 (ScalaJS.idHashCodeMap !== null) ? //!endif (function(obj) { switch (typeof obj) { case "string": case "number": case "boolean": case "undefined": return ScalaJS.objectHashCode(obj); default: if (obj === null) { return 0; } else { let hash = ScalaJS.idHashCodeMap["get"](obj); if (hash === void 0) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; ScalaJS.idHashCodeMap["set"](obj, hash); } return hash; } } //!if outputMode != ECMAScript6 }) : (function(obj) { if (ScalaJS.isScalaJSObject(obj)) { let hash = obj["$idHashCode$0"]; if (hash !== void 0) { return hash; } else if (!ScalaJS.g["Object"]["isSealed"](obj)) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; obj["$idHashCode$0"] = hash; return hash; } else { return 42; } } else if (obj === null) { return 0; } else { return ScalaJS.objectHashCode(obj); } //!endif }); // is/as for hijacked boxed classes (the non-trivial ones) ScalaJS.isByte = function(v) { return (v << 24 >> 24) === v && 1/v !== 1/-0; }; ScalaJS.isShort = function(v) { return (v << 16 >> 16) === v && 1/v !== 1/-0; }; ScalaJS.isInt = function(v) { return (v | 0) === v && 1/v !== 1/-0; }; ScalaJS.isFloat = function(v) { //!if floats == Strict return v !== v || ScalaJS.fround(v) === v; //!else return typeof v === "number"; //!endif }; //!if asInstanceOfs != Unchecked ScalaJS.asUnit = function(v) { if (v === void 0 || v === null) return v; else ScalaJS.throwClassCastException(v, "scala.runtime.BoxedUnit"); }; ScalaJS.asBoolean = function(v) { if (typeof v === "boolean" || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Boolean"); }; ScalaJS.asByte = function(v) { if (ScalaJS.isByte(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Byte"); }; ScalaJS.asShort = function(v) { if (ScalaJS.isShort(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Short"); }; ScalaJS.asInt = function(v) { if (ScalaJS.isInt(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Integer"); }; ScalaJS.asFloat = function(v) { if (ScalaJS.isFloat(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Float"); }; ScalaJS.asDouble = function(v) { if (typeof v === "number" || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Double"); }; //!endif // Unboxes //!if asInstanceOfs != Unchecked ScalaJS.uZ = function(value) { return !!ScalaJS.asBoolean(value); }; ScalaJS.uB = function(value) { return ScalaJS.asByte(value) | 0; }; ScalaJS.uS = function(value) { return ScalaJS.asShort(value) | 0; }; ScalaJS.uI = function(value) { return ScalaJS.asInt(value) | 0; }; ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : ScalaJS.as.sjsr_RuntimeLong(value); }; ScalaJS.uF = function(value) { /* Here, it is fine to use + instead of fround, because asFloat already * ensures that the result is either null or a float. */ return +ScalaJS.asFloat(value); }; ScalaJS.uD = function(value) { return +ScalaJS.asDouble(value); }; //!else ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : value; }; //!endif // TypeArray conversions ScalaJS.byteArray2TypedArray = function(value) { return new ScalaJS.g["Int8Array"](value.u); }; ScalaJS.shortArray2TypedArray = function(value) { return new ScalaJS.g["Int16Array"](value.u); }; ScalaJS.charArray2TypedArray = function(value) { return new ScalaJS.g["Uint16Array"](value.u); }; ScalaJS.intArray2TypedArray = function(value) { return new ScalaJS.g["Int32Array"](value.u); }; ScalaJS.floatArray2TypedArray = function(value) { return new ScalaJS.g["Float32Array"](value.u); }; ScalaJS.doubleArray2TypedArray = function(value) { return new ScalaJS.g["Float64Array"](value.u); }; ScalaJS.typedArray2ByteArray = function(value) { const arrayClassData = ScalaJS.d.B.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int8Array"](value)); }; ScalaJS.typedArray2ShortArray = function(value) { const arrayClassData = ScalaJS.d.S.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int16Array"](value)); }; ScalaJS.typedArray2CharArray = function(value) { const arrayClassData = ScalaJS.d.C.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Uint16Array"](value)); }; ScalaJS.typedArray2IntArray = function(value) { const arrayClassData = ScalaJS.d.I.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int32Array"](value)); }; ScalaJS.typedArray2FloatArray = function(value) { const arrayClassData = ScalaJS.d.F.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float32Array"](value)); }; ScalaJS.typedArray2DoubleArray = function(value) { const arrayClassData = ScalaJS.d.D.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float64Array"](value)); }; // TypeData class //!if outputMode != ECMAScript6 /** @constructor */ ScalaJS.TypeData = function() { //!else class $TypeData { constructor() { //!endif // Runtime support this.constr = void 0; this.parentData = void 0; this.ancestors = null; this.componentData = null; this.arrayBase = null; this.arrayDepth = 0; this.zero = null; this.arrayEncodedName = ""; this._classOf = void 0; this._arrayOf = void 0; this.isArrayOf = void 0; // java.lang.Class support this["name"] = ""; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = false; this["isRawJSType"] = false; this["isInstance"] = void 0; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initPrim = function( //!else initPrim( //!endif zero, arrayEncodedName, displayName) { // Runtime support this.ancestors = {}; this.componentData = null; this.zero = zero; this.arrayEncodedName = arrayEncodedName; this.isArrayOf = function(obj, depth) { return false; }; // java.lang.Class support this["name"] = displayName; this["isPrimitive"] = true; this["isInstance"] = function(obj) { return false; }; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initClass = function( //!else initClass( //!endif internalNameObj, isInterface, fullName, ancestors, isRawJSType, parentData, isInstance, isArrayOf) { const internalName = ScalaJS.propertyName(internalNameObj); isInstance = isInstance || function(obj) { return !!(obj && obj.$classData && obj.$classData.ancestors[internalName]); }; isArrayOf = isArrayOf || function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && obj.$classData.arrayBase.ancestors[internalName]) }; // Runtime support this.parentData = parentData; this.ancestors = ancestors; this.arrayEncodedName = "L"+fullName+";"; this.isArrayOf = isArrayOf; // java.lang.Class support this["name"] = fullName; this["isInterface"] = isInterface; this["isRawJSType"] = !!isRawJSType; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initArray = function( //!else initArray( //!endif componentData) { // The constructor const componentZero0 = componentData.zero; // The zero for the Long runtime representation // is a special case here, since the class has not // been defined yet, when this file is read const componentZero = (componentZero0 == "longZero") ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : componentZero0; //!if outputMode != ECMAScript6 /** @constructor */ const ArrayClass = function(arg) { if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } } ArrayClass.prototype = new ScalaJS.h.O; ArrayClass.prototype.constructor = ArrayClass; //!if arrayIndexOutOfBounds != Unchecked ArrayClass.prototype.get = function(i) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); return this.u[i]; }; ArrayClass.prototype.set = function(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); this.u[i] = v; }; //!endif ArrayClass.prototype.clone__O = function() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; //!else class ArrayClass extends ScalaJS.c.O { constructor(arg) { super(); if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } }; //!if arrayIndexOutOfBounds != Unchecked get(i) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); return this.u[i]; }; set(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); this.u[i] = v; }; //!endif clone__O() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; }; //!endif ArrayClass.prototype.$classData = this; // Don't generate reflective call proxies. The compiler special cases // reflective calls to methods on scala.Array // The data const encodedName = "[" + componentData.arrayEncodedName; const componentBase = componentData.arrayBase || componentData; const arrayDepth = componentData.arrayDepth + 1; const isInstance = function(obj) { return componentBase.isArrayOf(obj, arrayDepth); } // Runtime support this.constr = ArrayClass; this.parentData = ScalaJS.d.O; this.ancestors = {O: 1, jl_Cloneable: 1, Ljava_io_Serializable: 1}; this.componentData = componentData; this.arrayBase = componentBase; this.arrayDepth = arrayDepth; this.zero = null; this.arrayEncodedName = encodedName; this._classOf = undefined; this._arrayOf = undefined; this.isArrayOf = undefined; // java.lang.Class support this["name"] = encodedName; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = true; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getClassOf = function() { //!else getClassOf() { //!endif if (!this._classOf) this._classOf = new ScalaJS.c.jl_Class().init___jl_ScalaJSClassData(this); return this._classOf; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getArrayOf = function() { //!else getArrayOf() { //!endif if (!this._arrayOf) this._arrayOf = new ScalaJS.TypeData().initArray(this); return this._arrayOf; }; // java.lang.Class support //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getFakeInstance"] = function() { //!else "getFakeInstance"() { //!endif if (this === ScalaJS.d.T) return "some string"; else if (this === ScalaJS.d.jl_Boolean) return false; else if (this === ScalaJS.d.jl_Byte || this === ScalaJS.d.jl_Short || this === ScalaJS.d.jl_Integer || this === ScalaJS.d.jl_Float || this === ScalaJS.d.jl_Double) return 0; else if (this === ScalaJS.d.jl_Long) return ScalaJS.m.sjsr_RuntimeLong$().Zero$1; else if (this === ScalaJS.d.sr_BoxedUnit) return void 0; else return {$classData: this}; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getSuperclass"] = function() { //!else "getSuperclass"() { //!endif return this.parentData ? this.parentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getComponentType"] = function() { //!else "getComponentType"() { //!endif return this.componentData ? this.componentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["newArrayOfThisClass"] = function(lengths) { //!else "newArrayOfThisClass"(lengths) { //!endif let arrayClassData = this; for (let i = 0; i < lengths.length; i++) arrayClassData = arrayClassData.getArrayOf(); return ScalaJS.newArrayObject(arrayClassData, lengths); }; //!if outputMode == ECMAScript6 }; //!endif // Create primitive types ScalaJS.d.V = new ScalaJS.TypeData().initPrim(undefined, "V", "void"); ScalaJS.d.Z = new ScalaJS.TypeData().initPrim(false, "Z", "boolean"); ScalaJS.d.C = new ScalaJS.TypeData().initPrim(0, "C", "char"); ScalaJS.d.B = new ScalaJS.TypeData().initPrim(0, "B", "byte"); ScalaJS.d.S = new ScalaJS.TypeData().initPrim(0, "S", "short"); ScalaJS.d.I = new ScalaJS.TypeData().initPrim(0, "I", "int"); ScalaJS.d.J = new ScalaJS.TypeData().initPrim("longZero", "J", "long"); ScalaJS.d.F = new ScalaJS.TypeData().initPrim(0.0, "F", "float"); ScalaJS.d.D = new ScalaJS.TypeData().initPrim(0.0, "D", "double"); // Instance tests for array of primitives ScalaJS.isArrayOf.Z = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.Z); ScalaJS.d.Z.isArrayOf = ScalaJS.isArrayOf.Z; ScalaJS.isArrayOf.C = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.C); ScalaJS.d.C.isArrayOf = ScalaJS.isArrayOf.C; ScalaJS.isArrayOf.B = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.B); ScalaJS.d.B.isArrayOf = ScalaJS.isArrayOf.B; ScalaJS.isArrayOf.S = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.S); ScalaJS.d.S.isArrayOf = ScalaJS.isArrayOf.S; ScalaJS.isArrayOf.I = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.I); ScalaJS.d.I.isArrayOf = ScalaJS.isArrayOf.I; ScalaJS.isArrayOf.J = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.J); ScalaJS.d.J.isArrayOf = ScalaJS.isArrayOf.J; ScalaJS.isArrayOf.F = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.F); ScalaJS.d.F.isArrayOf = ScalaJS.isArrayOf.F; ScalaJS.isArrayOf.D = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.D); ScalaJS.d.D.isArrayOf = ScalaJS.isArrayOf.D; //!if asInstanceOfs != Unchecked // asInstanceOfs for array of primitives ScalaJS.asArrayOf.Z = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.Z, "Z"); ScalaJS.asArrayOf.C = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.C, "C"); ScalaJS.asArrayOf.B = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.B, "B"); ScalaJS.asArrayOf.S = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.S, "S"); ScalaJS.asArrayOf.I = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.I, "I"); ScalaJS.asArrayOf.J = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.J, "J"); ScalaJS.asArrayOf.F = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.F, "F"); ScalaJS.asArrayOf.D = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.D, "D"); //!endif
xuwei-k/scala-js
tools/scalajsenv.js
JavaScript
bsd-3-clause
32,145
// 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 "chrome/browser/ui/panels/panel_resize_controller.h" #include "base/logging.h" #include "chrome/browser/ui/panels/panel.h" #include "chrome/browser/ui/panels/panel_manager.h" namespace { static bool ResizingLeft(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_LEFT || sides == panel::RESIZE_LEFT || sides == panel::RESIZE_BOTTOM_LEFT; } static bool ResizingRight(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_RIGHT || sides == panel::RESIZE_RIGHT || sides == panel::RESIZE_BOTTOM_RIGHT; } static bool ResizingTop(panel::ResizingSides sides) { return sides == panel::RESIZE_TOP_LEFT || sides == panel::RESIZE_TOP || sides == panel::RESIZE_TOP_RIGHT; } static bool ResizingBottom(panel::ResizingSides sides) { return sides == panel::RESIZE_BOTTOM_RIGHT || sides == panel::RESIZE_BOTTOM || sides == panel::RESIZE_BOTTOM_LEFT; } } PanelResizeController::PanelResizeController(PanelManager* panel_manager) : panel_manager_(panel_manager), resizing_panel_(NULL), sides_resized_(panel::RESIZE_NONE) { } void PanelResizeController::StartResizing(Panel* panel, const gfx::Point& mouse_location, panel::ResizingSides sides) { DCHECK(!IsResizing()); DCHECK_NE(panel::RESIZE_NONE, sides); panel::Resizability resizability = panel->CanResizeByMouse(); DCHECK_NE(panel::NOT_RESIZABLE, resizability); panel::Resizability resizability_to_test; switch (sides) { case panel::RESIZE_TOP_LEFT: resizability_to_test = panel::RESIZABLE_TOP_LEFT; break; case panel::RESIZE_TOP: resizability_to_test = panel::RESIZABLE_TOP; break; case panel::RESIZE_TOP_RIGHT: resizability_to_test = panel::RESIZABLE_TOP_RIGHT; break; case panel::RESIZE_LEFT: resizability_to_test = panel::RESIZABLE_LEFT; break; case panel::RESIZE_RIGHT: resizability_to_test = panel::RESIZABLE_RIGHT; break; case panel::RESIZE_BOTTOM_LEFT: resizability_to_test = panel::RESIZABLE_BOTTOM_LEFT; break; case panel::RESIZE_BOTTOM: resizability_to_test = panel::RESIZABLE_BOTTOM; break; case panel::RESIZE_BOTTOM_RIGHT: resizability_to_test = panel::RESIZABLE_BOTTOM_RIGHT; break; default: resizability_to_test = panel::NOT_RESIZABLE; break; } if ((resizability & resizability_to_test) == 0) { DLOG(WARNING) << "Resizing not allowed. Is this a test?"; return; } mouse_location_at_start_ = mouse_location; bounds_at_start_ = panel->GetBounds(); sides_resized_ = sides; resizing_panel_ = panel; resizing_panel_->OnPanelStartUserResizing(); } void PanelResizeController::Resize(const gfx::Point& mouse_location) { DCHECK(IsResizing()); panel::Resizability resizability = resizing_panel_->CanResizeByMouse(); if (panel::NOT_RESIZABLE == resizability) { EndResizing(false); return; } gfx::Rect bounds = resizing_panel_->GetBounds(); if (ResizingRight(sides_resized_)) { bounds.set_width(std::max(bounds_at_start_.width() + mouse_location.x() - mouse_location_at_start_.x(), 0)); } if (ResizingBottom(sides_resized_)) { bounds.set_height(std::max(bounds_at_start_.height() + mouse_location.y() - mouse_location_at_start_.y(), 0)); } if (ResizingLeft(sides_resized_)) { bounds.set_width(std::max(bounds_at_start_.width() + mouse_location_at_start_.x() - mouse_location.x(), 0)); } if (ResizingTop(sides_resized_)) { int new_height = std::max(bounds_at_start_.height() + mouse_location_at_start_.y() - mouse_location.y(), 0); int new_y = bounds_at_start_.bottom() - new_height; // If the mouse is within the main screen area, make sure that the top // border of panel cannot go outside the work area. This is to prevent // panel's titlebar from being resized under the taskbar or OSX menu bar // that is aligned to top screen edge. int display_area_top_position = panel_manager_->display_area().y(); if (panel_manager_->display_settings_provider()-> GetPrimaryScreenArea().Contains(mouse_location) && new_y < display_area_top_position) { new_height -= display_area_top_position - new_y; } bounds.set_height(new_height); } resizing_panel_->IncreaseMaxSize(bounds.size()); // This effectively only clamps using the min size, since the max_size was // updated above. bounds.set_size(resizing_panel_->ClampSize(bounds.size())); if (ResizingLeft(sides_resized_)) bounds.set_x(bounds_at_start_.right() - bounds.width()); if (ResizingTop(sides_resized_)) bounds.set_y(bounds_at_start_.bottom() - bounds.height()); if (bounds != resizing_panel_->GetBounds()) resizing_panel_->OnWindowResizedByMouse(bounds); } Panel* PanelResizeController::EndResizing(bool cancelled) { DCHECK(IsResizing()); if (cancelled) resizing_panel_->OnWindowResizedByMouse(bounds_at_start_); // Do a thorough cleanup. resizing_panel_->OnPanelEndUserResizing(); Panel* resized_panel = resizing_panel_; resizing_panel_ = NULL; sides_resized_ = panel::RESIZE_NONE; bounds_at_start_ = gfx::Rect(); mouse_location_at_start_ = gfx::Point(); return resized_panel; } void PanelResizeController::OnPanelClosed(Panel* panel) { if (!resizing_panel_) return; // If the resizing panel is closed, abort the resize operation. if (resizing_panel_ == panel) EndResizing(false); }
zcbenz/cefode-chromium
chrome/browser/ui/panels/panel_resize_controller.cc
C++
bsd-3-clause
5,852
/* $OpenBSD: limits.h,v 1.5 1998/03/22 21:15:24 millert Exp $ */ /* $NetBSD: limits.h,v 1.7 1996/01/05 18:10:57 pk Exp $ */ /* * Copyright (c) 1988 The Regents of the University of California. * All rights reserved. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 THE REGENTS 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 REGENTS 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. * * @(#)limits.h 8.3 (Berkeley) 1/4/94 */ #define CHAR_BIT 8 /* number of bits in a char */ #define MB_LEN_MAX 1 /* no multibyte characters */ #define SCHAR_MIN (-0x7f-1) /* max value for a signed char */ #define SCHAR_MAX 0x7f /* min value for a signed char */ #define UCHAR_MAX 0xffU /* max value for an unsigned char */ #define CHAR_MAX 0x7f /* max value for a char */ #define CHAR_MIN (-0x7f-1) /* min value for a char */ #define USHRT_MAX 0xffffU /* max value for an unsigned short */ #define SHRT_MAX 0x7fff /* max value for a short */ #define SHRT_MIN (-0x7fff-1) /* min value for a short */ #define UINT_MAX 0xffffffffU /* max value for an unsigned int */ #define INT_MAX 0x7fffffff /* max value for an int */ #define INT_MIN (-0x7fffffff-1) /* min value for an int */ #define ULONG_MAX 0xffffffffUL /* max value for an unsigned long */ #define LONG_MAX 0x7fffffffL /* max value for a long */ #define LONG_MIN (-0x7fffffffL-1) /* min value for a long */ #if !defined(_ANSI_SOURCE) #define SSIZE_MAX INT_MAX /* max value for a ssize_t */ #if !defined(_POSIX_SOURCE) && !defined(_XOPEN_SOURCE) #define SIZE_T_MAX UINT_MAX /* max value for a size_t */ #define UID_MAX UINT_MAX /* max value for a uid_t */ #define GID_MAX UINT_MAX /* max value for a gid_t */ /* GCC requires that quad constants be written as expressions. */ #define UQUAD_MAX ((u_quad_t)0-1) /* max value for a uquad_t */ /* max value for a quad_t */ #define QUAD_MAX ((quad_t)(UQUAD_MAX >> 1)) #define QUAD_MIN (-QUAD_MAX-1) /* min value for a quad_t */ #endif /* !_POSIX_SOURCE && !_XOPEN_SOURCE */ #endif /* !_ANSI_SOURCE */ #if (!defined(_ANSI_SOURCE)&&!defined(_POSIX_SOURCE)) || defined(_XOPEN_SOURCE) #define LONG_BIT 32 #define WORD_BIT 32 #define DBL_DIG 15 #define DBL_MAX 1.7976931348623157E+308 #define DBL_MIN 2.2250738585072014E-308 #define FLT_DIG 6 #define FLT_MAX 3.40282347E+38F #define FLT_MIN 1.17549435E-38F #endif
MarginC/kame
openbsd/sys/arch/sparc/include/limits.h
C
bsd-3-clause
3,892
package com.percolate.sdk.dto; import com.fasterxml.jackson.annotation.*; import com.percolate.sdk.interfaces.HasExtraFields; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings("UnusedDeclaration") @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class FacebookConversationMessage implements Serializable, HasExtraFields { private static final long serialVersionUID = -7978616001157824820L; @JsonIgnore public List<FacebookConversationMessage> extraMessages = new ArrayList<>(); // Set by client to group messages happening around the same time @JsonIgnore public String stickerUrl; //Set by client. If message is empty, ApiGetFacebookMessage is used to check for images/stickers. @JsonIgnore public List<FacebookMessageAttachment> attachments; //Set by client after calling ApiGetFacebookMessage. @JsonIgnore public Flag flag; //Set by client after calling ApiGetFlags @JsonProperty("id") protected String id; @JsonProperty("conversation_id") protected String conversationId; @JsonProperty("from") protected FacebookUser from; // ApiGetFacebookConversations API returns "from" // ApiGetFlag API returns "from_user" // The setter method for this value sets <code>from</code> field. @JsonProperty("from_user") protected FacebookUser tempFromUser; @JsonProperty("created_at") protected String createdAt; @JsonProperty("has_attachments") protected Boolean hasAttachments; @JsonProperty("message") protected String message; @JsonIgnore protected Map<String, Object> extraFields = new HashMap<>(); @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public FacebookUser getFrom() { return from; } public void setFrom(FacebookUser from) { this.from = from; } public void setTempFromUser(FacebookUser from) { this.tempFromUser = from; this.from = from; } public FacebookUser getTempFromUser() { return tempFromUser; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public Boolean getHasAttachments() { return hasAttachments; } public void setHasAttachments(Boolean hasAttachments) { this.hasAttachments = hasAttachments; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public Map<String, Object> getExtraFields() { if(extraFields == null) { extraFields = new HashMap<>(); } return extraFields; } @Override @JsonAnySetter public void putExtraField(String key, Object value) { getExtraFields().put(key, value); } }
percolate/percolate-java-sdk
core/src/main/java/com/percolate/sdk/dto/FacebookConversationMessage.java
Java
bsd-3-clause
3,496
<?php use yii\helpers\Html; use kartik\grid\GridView; use yii\helpers\ArrayHelper; use backend\modules\qtn\models\Survey; /* @var $this yii\web\View */ /* @var $searchModel backend\modules\qtn\Models\SurveySearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Qtn Surveys'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="qtn-survey-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Create Qtn Survey', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, // 'filterModel' => $searchModel, 'showPageSummary'=>true, 'pjax'=>true, 'striped'=>true, 'hover'=>true, 'panel'=>['type'=>'primary', 'heading'=>'Grid Grouping Example'], 'columns' => [ ['class'=>'kartik\grid\SerialColumn'], [ 'attribute'=>'id', 'format' => 'raw', 'width'=>'310px', 'value'=>function ($model, $key, $index, $widget) { $txt= $model->surveyTab->survey->name; if($model->surveyTab->survey->status==0){ $txt .= '&nbsp;'.Html::a('<span class=" glyphicon glyphicon-pencil"></span>',[ 'survey/update?id=' . $model->surveyTab->survey_id]); } $txt .= '___' .Html::a('<span class="glyphicon glyphicon-list-alt"></span>',[ 'survey/view?id=' .$model->surveyTab->survey_id]); return $txt; }, 'filterInputOptions'=>['placeholder'=>'Any supplier'], 'group'=>true, // enable grouping, 'groupedRow'=>true, // move grouped column to a single grouped row 'groupOddCssClass'=>'kv-grouped-row', // configure odd group cell css class 'groupEvenCssClass'=>'kv-grouped-row', // configure even group cell css class ], [ 'attribute'=>'survey_tab_id', 'width'=>'310px', 'value'=>function ($model, $key, $index, $widget) { return $model->surveyTab->name; }, 'group'=>true, ], [ 'attribute'=>'name', 'format' => 'raw', 'value'=>function ($data) { $txt= $data->name; if($data->surveyTab->survey->status==0){ $txt .= '&nbsp;'.Html::a('คำถาม',[ 'survey/question?id=' . $data->surveyTab->survey_id]); //$txt .=Html::a('table',[ 'survey/choice-title?id=' . $data->id]); } return $txt; }, ], ], ]); ?> </div>
yuttapong/webapp
backend/modules/qtn/views/survey/index.php
PHP
bsd-3-clause
2,807
@echo off rem rem Collective Knowledge rem rem See CK LICENSE.txt for licensing details. rem See CK Copyright.txt for copyright details. rem rem Developer: Grigori Fursin rem rem CK entry point rem Set default path by detecting the path to this script set ck_path=%~dp0\.. rem Check if CK_ROOT is defined and used it, otherwise use auto-detected path IF "%CK_ROOT%"=="" set CK_ROOT=%ck_path% rem Load kernel module IF EXIST %CK_ROOT%\ck\kernel.py ( python -W ignore::DeprecationWarning %CK_ROOT%\ck\kernel.py %* ) ELSE ( echo cK Error: kernel module not found! )
gmarkall/ck
bin/ck.bat
Batchfile
bsd-3-clause
571
Bool_t SetGeneratedSmearingHistos = kFALSE; Bool_t GetCentralityFromAlien = kFALSE; std::string centralityFilename = ""; std::string centralityFilenameFromAlien = "/alice/cern.ch/user/a/acapon/.root"; const Int_t triggerNames = AliVEvent::kINT7; const Int_t nMCSignal = 0; const Int_t nCutsetting = 0; const Double_t minGenPt = 0.05; const Double_t maxGenPt = 20; const Double_t minGenEta = -1.5; const Double_t maxGenEta = 1.5; const Double_t minPtCut = 0.2; const Double_t maxPtCut = 15.0; const Double_t minEtaCut = -0.8; const Double_t maxEtaCut = 0.8; // const Double_t minPtCut = 0.2; // const Double_t maxPtCut = 8.0; // const Double_t minEtaCut = -0.8; // const Double_t maxEtaCut = 0.8; // binning of single leg histograms Bool_t usePtVector = kTRUE; Double_t ptBins[] = {0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40, 0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85, 0.90,0.95,1.00,1.10,1.20,1.30,1.40,1.50,1.60, 1.70,1.80,1.90,2.00,2.10,2.30,2.50,3.00,3.50, 4.00,5.00,6.00,7.00,8.00,10.0,15.0}; const Int_t nBinsPt = ( sizeof(ptBins) / sizeof(ptBins[0]) )-1; const Double_t minPtBin = 0; const Double_t maxPtBin = 20; const Int_t stepsPtBin = 800; const Double_t minEtaBin = -1.0; const Double_t maxEtaBin = 1.0; const Int_t stepsEtaBin = 20; const Double_t minPhiBin = 0; const Double_t maxPhiBin = 6.3; const Int_t stepsPhiBin = 20; const Double_t minThetaBin = 0; const Double_t maxThetaBin = TMath::TwoPi(); const Int_t stepsThetaBin = 60; const Double_t minMassBin = 0; const Double_t maxMassBin = 5; const Int_t stepsMassBin = 500; const Double_t minPairPtBin = 0; const Double_t maxPairPtBin = 10; const Int_t stepsPairPtBin = 100; // Binning of resolution histograms const Int_t NbinsDeltaMom = 2000; const Double_t DeltaMomMin = -10.0; const Double_t DeltaMomMax = 10.0; const Int_t NbinsRelMom = 400; const Double_t RelMomMin = 0.0; const Double_t RelMomMax = 2.0; const Int_t NbinsDeltaEta = 200; const Double_t DeltaEtaMin = -0.4; const Double_t DeltaEtaMax = 0.4; const Int_t NbinsDeltaTheta = 200; const Double_t DeltaThetaMin = -0.4; const Double_t DeltaThetaMax = 0.4; const Int_t NbinsDeltaPhi = 200; const Double_t DeltaPhiMin = -0.4; const Double_t DeltaPhiMax = 0.4; void GetCentrality(const Int_t centrality, Double_t& CentMin, Double_t& CentMax){ std::cout << "GetCentrality with centrality " << centrality << std::endl; if (centrality == 0){CentMin = 0; CentMax = 100;} else if(centrality == 1){CentMin = 0; CentMax = 20;} else if(centrality == 2){CentMin = 20; CentMax = 40;} else if(centrality == 3){CentMin = 40; CentMax = 60;} else if(centrality == 4){CentMin = 60; CentMax = 100;} else if(centrality == 5){CentMin = 60; CentMax = 80;} else if(centrality == 6){CentMin = 80; CentMax = 100;} else if(centrality == 7){CentMin = 0; CentMax = 5;} else if(centrality == 8){CentMin = -1; CentMax = -1;} else {std::cout << "WARNING::Centrality range not found....." std::endl;} return; } void ApplyPIDpostCalibration(AliAnalysisTaskElectronEfficiencyV2* task, Int_t whichDet, Bool_t wSDD){ std::cout << task << std::endl; std::cout << "starting ApplyPIDpostCalibration()\n"; if(whichDet == 0 && wSDD){// ITS std::cout << "Loading ITS correction" << std::endl; TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/"; TString fileName = "outputITS_MC.root"; TFile* inFile = TFile::Open(localPath+fileName); if(!inFile){ gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" ."); std::cout << "Copy ITS correction from Alien" << std::endl; inFile = TFile::Open(fileName); } else { std::cout << "Correction loaded" << std::endl; } TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction")); TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction")); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly); task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kITS, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly); } if(whichDet == 1){// TOF std::cout << "Loading TOF correction" << std::endl; TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/"; TString fileName = "outputTOF"; if(wSDD == kTRUE){ fileName.Append("_MC.root"); }else{ fileName.Append("_woSDD_MC.root"); } TFile* inFile = TFile::Open(localPath+fileName); if(!inFile){ gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" ."); std::cout << "Copy TOF correction from Alien" << std::endl; inFile = TFile::Open(fileName); } else { std::cout << "Correction loaded" << std::endl; } TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction")); TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction")); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly); task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kTOF, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly); } } // ######################################################### // ######################################################### AliAnalysisFilter* SetupTrackCutsAndSettings(TString cutDefinition, Bool_t wSDD) { std::cout << "SetupTrackCutsAndSettings( cutInstance = " << cutDefinition << " )" <<std::endl; AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory! LMEECutLib* LMcutlib = new LMEECutLib(wSDD); if(cutDefinition == "kResolutionCuts"){ std::cout << "Resolution Track Cuts being set" << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kResolutionTrackCuts, LMEECutLib::kResolutionTrackCuts)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutSet1"){ //TMVA std::cout << "Setting up cut set 1" << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kCutSet1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kTheoPID"){ // PID cut set from a Run 1 pPb analysis. Standard track cuts std::cout << "Setting up Theo PID. Standard track cuts." << std::endl; anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kTheoPID)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kScheidCuts"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kScheidCuts, LMEECutLib::kScheidCuts)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } // ######## PID Cut variation settings ################# // These variations use the kCutSet1 track cuts and only vary PID else if(cutDefinition == "kPIDcut1"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut2"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut2)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut3"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut3)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut4"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut4)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut5"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut5)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut6"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut6)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut7"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut7)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut8"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut8)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut9"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut9)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut10"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut10)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut11"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut11)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut12"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut12)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut13"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut13)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut14"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut14)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut15"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut15)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut16"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut16)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut17"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut17)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut18"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut18)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut19"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut19)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kPIDcut20"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut20)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } // ######## Track+ePID Cut variation settings ################# else if(cutDefinition == "kCutVar1"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar1, LMEECutLib::kCutVar1)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar2"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar2, LMEECutLib::kCutVar2)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar3"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar3, LMEECutLib::kCutVar3)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar4"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar4, LMEECutLib::kCutVar4)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar5"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar5, LMEECutLib::kCutVar5)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar6"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar6, LMEECutLib::kCutVar6)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar7"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar7, LMEECutLib::kCutVar7)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar8"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar8, LMEECutLib::kCutVar8)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar9"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar9, LMEECutLib::kCutVar9)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar10"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar10, LMEECutLib::kCutVar10)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar11"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar11, LMEECutLib::kCutVar11)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar12"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar12, LMEECutLib::kCutVar12)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar13"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar13, LMEECutLib::kCutVar13)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar14"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar14, LMEECutLib::kCutVar14)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar15"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar15, LMEECutLib::kCutVar15)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar16"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar16, LMEECutLib::kCutVar16)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar17"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar17, LMEECutLib::kCutVar17)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar18"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar18, LMEECutLib::kCutVar18)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar19"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar19, LMEECutLib::kCutVar19)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else if(cutDefinition == "kCutVar20"){ anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar20, LMEECutLib::kCutVar20)); anaFilter->SetName(cutDefinition); anaFilter->Print(); } else{ std::cout << "Undefined cut definition...." << std::endl; return 0x0; } return anaFilter; } // ######################################################### // ######################################################### std::vector<Bool_t> AddSingleLegMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){ // SetLegPDGs() requires two pdg codes. For single tracks a dummy value is // passed, "1". // All final state electrons (excluding conversion electrons) AliDielectronSignalMC eleFinalState("eleFinalState","eleFinalState"); eleFinalState.SetLegPDGs(11,1); eleFinalState.SetCheckBothChargesLegs(kTRUE,kTRUE); eleFinalState.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); eleFinalState.SetMotherPDGs(22, 22, kTRUE, kTRUE); // Exclude conversion electrons // Electrons from open charm mesons and baryons AliDielectronSignalMC eleFinalStateFromD("eleFinalStateFromD","eleFinalStateFromD"); eleFinalStateFromD.SetLegPDGs(11,1); eleFinalStateFromD.SetCheckBothChargesLegs(kTRUE,kTRUE); eleFinalStateFromD.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); eleFinalStateFromD.SetMotherPDGs(402, 402); eleFinalStateFromD.SetCheckBothChargesMothers(kTRUE,kTRUE); // Electrons from open beauty mesons and baryons AliDielectronSignalMC eleFinalStateFromB("eleFinalStateFromB","eleFinalStateFromB"); eleFinalStateFromB.SetLegPDGs(11,1); eleFinalStateFromB.SetCheckBothChargesLegs(kTRUE,kTRUE); eleFinalStateFromB.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); eleFinalStateFromB.SetMotherPDGs(502, 502); eleFinalStateFromB.SetCheckBothChargesMothers(kTRUE,kTRUE); // Add signals task->AddSingleLegMCSignal(eleFinalState); task->AddSingleLegMCSignal(eleFinalStateFromD); task->AddSingleLegMCSignal(eleFinalStateFromB); // This is used to get electrons not from same mother for pair efficiency. // Needed to look at D and B meson electrons as functionality to pair those is // not implemented in the framework. Instead, use all final start electrons // from D or B decays for efficiency correction, for example. // The ordering must match the ordering of the added signals above*. std::vector<Bool_t> DielectronsPairNotFromSameMother; DielectronsPairNotFromSameMother.push_back(kFALSE); DielectronsPairNotFromSameMother.push_back(kTRUE); DielectronsPairNotFromSameMother.push_back(kTRUE); return DielectronsPairNotFromSameMother; } // ######################################################### // ######################################################### void AddPairMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){ // Dielectron pairs from same mother (excluding conversions) AliDielectronSignalMC pair_sameMother("sameMother","sameMother"); pair_sameMother.SetLegPDGs(11,-11); pair_sameMother.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother.SetMotherPDGs(22,22,kTRUE,kTRUE); // Exclude conversion //################################################################### // Signals for specific dielectron decay channels AliDielectronSignalMC pair_sameMother_pion("sameMother_pion","sameMother_pion"); pair_sameMother_pion.SetLegPDGs(11,-11); pair_sameMother_pion.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_pion.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_pion.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_pion.SetMotherPDGs(111,111); AliDielectronSignalMC pair_sameMother_eta("sameMother_eta","sameMother_eta"); pair_sameMother_eta.SetLegPDGs(11,-11); pair_sameMother_eta.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_eta.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_eta.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_eta.SetMotherPDGs(221,221); AliDielectronSignalMC pair_sameMother_etaP("sameMother_etaP","sameMother_etaP"); pair_sameMother_etaP.SetLegPDGs(11,-11); pair_sameMother_etaP.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_etaP.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_etaP.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_etaP.SetMotherPDGs(331,331); AliDielectronSignalMC pair_sameMother_rho("sameMother_rho","sameMother_rho"); pair_sameMother_rho.SetLegPDGs(11,-11); pair_sameMother_rho.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_rho.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_rho.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_rho.SetMotherPDGs(113, 113); AliDielectronSignalMC pair_sameMother_omega("sameMother_omega","sameMother_omega"); pair_sameMother_omega.SetLegPDGs(11,-11); pair_sameMother_omega.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_omega.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_omega.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_omega.SetMotherPDGs(223, 223); AliDielectronSignalMC pair_sameMother_phi("sameMother_phi","sameMother_phi"); pair_sameMother_phi.SetLegPDGs(11,-11); pair_sameMother_phi.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_phi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_phi.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_phi.SetMotherPDGs(333, 333); AliDielectronSignalMC pair_sameMother_jpsi("sameMother_jpsi","sameMother_jpsi"); pair_sameMother_jpsi.SetLegPDGs(11,-11); pair_sameMother_jpsi.SetCheckBothChargesLegs(kTRUE,kTRUE); pair_sameMother_jpsi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState); // Set mother properties pair_sameMother_jpsi.SetMothersRelation(AliDielectronSignalMC::kSame); pair_sameMother_jpsi.SetMotherPDGs(443, 443); task->AddPairMCSignal(pair_sameMother); // task->AddPairMCSignal(pair_sameMother_pion); // task->AddPairMCSignal(pair_sameMother_eta); // task->AddPairMCSignal(pair_sameMother_etaP); // task->AddPairMCSignal(pair_sameMother_rho); // task->AddPairMCSignal(pair_sameMother_omega); // task->AddPairMCSignal(pair_sameMother_phi); // task->AddPairMCSignal(pair_sameMother_jpsi); }
carstooon/AliPhysics
PWGDQ/dielectron/macrosLMEE/Config_acapon_Efficiency.C
C++
bsd-3-clause
22,296
<?php /* Copyright (c) 2007, Till Brehm, projektfarm Gmbh 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 THConfig 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 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. */ /****************************************** * Begin Form configuration ******************************************/ $list_def_file = "list/web_aliasdomain.list.php"; $tform_def_file = "form/web_aliasdomain.tform.php"; /****************************************** * End Form configuration ******************************************/ require_once('../../lib/config.inc.php'); require_once('../../lib/app.inc.php'); //* Check permissions for module $app->auth->check_module_permissions('sites'); $app->uses("tform_actions"); $app->tform_actions->onDelete(); ?>
TR-Host/THConfig
interface/web/sites/web_aliasdomain_del.php
PHP
bsd-3-clause
2,098
// 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 "chrome/browser/renderer_preferences_util.h" #include <stdint.h> #include <string> #include <vector> #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/convert_explicitly_allowed_network_ports_pref.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/login/demo_mode/demo_session.h" #endif #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/pref_names.h" #include "components/language/core/browser/language_prefs.h" #include "components/language/core/browser/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/renderer_preferences_util.h" #include "media/media_buildflags.h" #include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h" #include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h" #include "third_party/blink/public/public_buildflags.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/ui_base_features.h" #if defined(TOOLKIT_VIEWS) #include "ui/views/controls/textfield/textfield.h" #endif #if defined(OS_MAC) #include "ui/base/cocoa/defaults_utils.h" #endif #if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "ui/views/linux_ui/linux_ui.h" #endif #include "content/nw/src/common/nw_content_common_hooks.h" namespace { // Parses a string |range| with a port range in the form "<min>-<max>". // If |range| is not in the correct format or contains an invalid range, zero // is written to |min_port| and |max_port|. // TODO(guidou): Consider replacing with remoting/protocol/port_range.cc void ParsePortRange(const std::string& range, uint16_t* min_port, uint16_t* max_port) { *min_port = 0; *max_port = 0; if (range.empty()) return; size_t separator_index = range.find('-'); if (separator_index == std::string::npos) return; std::string min_port_string, max_port_string; base::TrimWhitespaceASCII(range.substr(0, separator_index), base::TRIM_ALL, &min_port_string); base::TrimWhitespaceASCII(range.substr(separator_index + 1), base::TRIM_ALL, &max_port_string); unsigned min_port_uint, max_port_uint; if (!base::StringToUint(min_port_string, &min_port_uint) || !base::StringToUint(max_port_string, &max_port_uint)) { return; } if (min_port_uint == 0 || min_port_uint > max_port_uint || max_port_uint > UINT16_MAX) { return; } *min_port = static_cast<uint16_t>(min_port_uint); *max_port = static_cast<uint16_t>(max_port_uint); } // Extracts the string representation of URLs allowed for local IP exposure. std::vector<std::string> GetLocalIpsAllowedUrls( const base::ListValue* allowed_urls) { std::vector<std::string> ret; if (allowed_urls) { const auto& urls = allowed_urls->GetList(); for (const auto& url : urls) ret.push_back(url.GetString()); } return ret; } std::string GetLanguageListForProfile(Profile* profile, const std::string& language_list) { if (profile->IsOffTheRecord()) { // In incognito mode return only the first language. return language::GetFirstLanguage(language_list); } #if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, if in demo mode, add the demo mode private language list. if (ash::DemoSession::IsDeviceInDemoMode()) { return language_list + "," + ash::DemoSession::GetAdditionalLanguageList(); } #endif return language_list; } } // namespace namespace renderer_preferences_util { void UpdateFromSystemSettings(blink::RendererPreferences* prefs, Profile* profile) { const PrefService* pref_service = profile->GetPrefs(); prefs->accept_languages = GetLanguageListForProfile( profile, pref_service->GetString(language::prefs::kAcceptLanguages)); prefs->enable_referrers = pref_service->GetBoolean(prefs::kEnableReferrers); prefs->enable_do_not_track = pref_service->GetBoolean(prefs::kEnableDoNotTrack); prefs->enable_encrypted_media = pref_service->GetBoolean(prefs::kEnableEncryptedMedia); prefs->webrtc_ip_handling_policy = std::string(); #if !defined(OS_ANDROID) prefs->caret_browsing_enabled = pref_service->GetBoolean(prefs::kCaretBrowsingEnabled); content::BrowserAccessibilityState::GetInstance()->SetCaretBrowsingState( prefs->caret_browsing_enabled); #endif if (prefs->webrtc_ip_handling_policy.empty()) { prefs->webrtc_ip_handling_policy = pref_service->GetString(prefs::kWebRTCIPHandlingPolicy); } std::string webrtc_udp_port_range = pref_service->GetString(prefs::kWebRTCUDPPortRange); ParsePortRange(webrtc_udp_port_range, &prefs->webrtc_udp_min_port, &prefs->webrtc_udp_max_port); const base::ListValue* allowed_urls = pref_service->GetList(prefs::kWebRtcLocalIpsAllowedUrls); prefs->webrtc_local_ips_allowed_urls = GetLocalIpsAllowedUrls(allowed_urls); prefs->webrtc_allow_legacy_tls_protocols = pref_service->GetBoolean(prefs::kWebRTCAllowLegacyTLSProtocols); #if defined(USE_AURA) prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE); #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) // This color is 0x544d90fe modulated with 0xffffff. prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA); prefs->active_selection_fg_color = SK_ColorBLACK; prefs->inactive_selection_bg_color = SkColorSetRGB(0xEA, 0xEA, 0xEA); prefs->inactive_selection_fg_color = SK_ColorBLACK; #endif #endif #if defined(TOOLKIT_VIEWS) prefs->caret_blink_interval = views::Textfield::GetCaretBlinkInterval(); #endif #if defined(OS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) prefs->caret_blink_interval = interval; #endif #if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)) views::LinuxUI* linux_ui = views::LinuxUI::instance(); if (linux_ui) { if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) { prefs->focus_ring_color = linux_ui->GetFocusRingColor(); prefs->active_selection_bg_color = linux_ui->GetActiveSelectionBgColor(); prefs->active_selection_fg_color = linux_ui->GetActiveSelectionFgColor(); prefs->inactive_selection_bg_color = linux_ui->GetInactiveSelectionBgColor(); prefs->inactive_selection_fg_color = linux_ui->GetInactiveSelectionFgColor(); } // If we have a linux_ui object, set the caret blink interval regardless of // whether we're in native theme mode. prefs->caret_blink_interval = linux_ui->GetCursorBlinkInterval(); } #endif #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \ defined(OS_WIN) content::UpdateFontRendererPreferencesFromSystemSettings(prefs); #endif #if !defined(OS_MAC) prefs->plugin_fullscreen_allowed = pref_service->GetBoolean(prefs::kFullscreenAllowed); #endif PrefService* local_state = g_browser_process->local_state(); if (local_state) { prefs->allow_cross_origin_auth_prompt = local_state->GetBoolean(prefs::kAllowCrossOriginAuthPrompt); prefs->explicitly_allowed_network_ports = ConvertExplicitlyAllowedNetworkPortsPref(local_state); } #if defined(OS_MAC) prefs->focus_ring_color = SkColorSetRGB(0x00, 0x5F, 0xCC); #else prefs->focus_ring_color = SkColorSetRGB(0x10, 0x10, 0x10); #endif std::string user_agent; if (nw::GetUserAgentFromManifest(&user_agent)) prefs->user_agent_override.ua_string_override = user_agent; } } // namespace renderer_preferences_util
nwjs/chromium.src
chrome/browser/renderer_preferences_util.cc
C++
bsd-3-clause
8,221
package net.minidev.ovh.api.price.dedicatedcloud._2014v1.sbg1a.infrastructure.filer; import com.fasterxml.jackson.annotation.JsonProperty; /** * Enum of Hourlys */ public enum OvhHourlyEnum { @JsonProperty("iscsi-1200-GB") iscsi_1200_GB("iscsi-1200-GB"), @JsonProperty("iscsi-13200g-GB") iscsi_13200g_GB("iscsi-13200g-GB"), @JsonProperty("iscsi-3300-GB") iscsi_3300_GB("iscsi-3300-GB"), @JsonProperty("iscsi-6600-GB") iscsi_6600_GB("iscsi-6600-GB"), @JsonProperty("iscsi-800-GB") iscsi_800_GB("iscsi-800-GB"), @JsonProperty("nfs-100-GB") nfs_100_GB("nfs-100-GB"), @JsonProperty("nfs-1200-GB") nfs_1200_GB("nfs-1200-GB"), @JsonProperty("nfs-13200-GB") nfs_13200_GB("nfs-13200-GB"), @JsonProperty("nfs-1600-GB") nfs_1600_GB("nfs-1600-GB"), @JsonProperty("nfs-2400-GB") nfs_2400_GB("nfs-2400-GB"), @JsonProperty("nfs-3300-GB") nfs_3300_GB("nfs-3300-GB"), @JsonProperty("nfs-6600-GB") nfs_6600_GB("nfs-6600-GB"), @JsonProperty("nfs-800-GB") nfs_800_GB("nfs-800-GB"); final String value; OvhHourlyEnum(String s) { this.value = s; } public String toString() { return this.value; } }
UrielCh/ovh-java-sdk
ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/price/dedicatedcloud/_2014v1/sbg1a/infrastructure/filer/OvhHourlyEnum.java
Java
bsd-3-clause
1,119
<?php /** * Rules_Whitespace_SuperfluousWhitespaceRule. * * Checks that no whitespace at the end of each line and no two empty lines in the content. * * @package SmartyLint * @author Umakant Patil <[email protected]> * @copyright 2013-15 Umakant Patil * @license https://github.com/umakantp/SmartyLint/blob/master/LICENSE BSD Licence * @link https://github.com/umakantp/SmartyLint */ class Rules_Whitespace_SuperfluousWhitespaceRule implements SmartyLint_Rule { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array('NEW_LINE'); } /** * Processes this rule, when one of its tokens is encountered. * * @param SmartyLint_File $smartylFile The file being scanned. * @param int $stackPtr The position of the current token in * the stack passed in $tokens. * * @return void */ public function process(SmartyLint_File $smartylFile, $stackPtr) { $tokens = $smartylFile->getTokens(); $beforeNewLine = false; if (isset($tokens[($stackPtr - 1)])) { $beforeNewLine = $tokens[($stackPtr - 1)]['type']; if ($beforeNewLine == 'TAB' || $beforeNewLine == 'SPACE') { $smartylFile->addError('Whitespace found at end of line', $stackPtr, 'EndFile'); } } $newLinesFound = 1; for ($i = ($stackPtr-1); $i >= 0; $i--) { if (isset($tokens[$i]) && $tokens[$i]['type'] == 'NEW_LINE') { $newLinesFound++; } else { break; } } if ($newLinesFound > 3) { $error = 'Found %s empty lines in a row.'; $data = array($newLinesFound); $smartylFile->addError($error, ($stackPtr - $newLinesFound), 'EmptyLines', $data); } } }
umakantp/SmartyLint
SmartyLint/Rules/Whitespace/SuperfluousWhitespaceRule.php
PHP
bsd-3-clause
1,961
<?php App::uses('CloggyAppModel', 'Cloggy.Model'); class CloggySearchFullText extends CloggyAppModel { public $name = 'CloggySearchFullText'; public $useTable = 'search_fulltext'; public $actsAs = array('CloggySearchFullTexIndex','CloggySearchFullTextTerm'); public function getTotal() { return $this->find('count'); } /** * Do search using MysqlFullTextSearch * * @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html NATURAL SEARCH * @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html BOOLEAN MODE * @param string $query * @return array */ public function search($query) { //default used mode $usedMode = __d('cloggy','Natural Search'); /* * first try to search with natural search * NATURAL SEARCH */ $data = $this->find('all',array( 'contain' => false, 'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\') AS rating'), 'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\')'), 'order' => array('rating' => 'desc') )); /* * if failed or empty results then * reset search in BOOLEAN MODE * with operator '*' that means search * data which contain 'query' or 'queries', etc */ if (empty($data)) { //format query string $query = $this->buildTerm($query); /* * begin searching data */ $data = $this->find('all',array( 'contain' => false, 'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE) AS rating'), 'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE)'), 'order' => array('rating' => 'desc') )); //switch search mode $usedMode = __d('cloggy','Boolean Mode'); } return array( 'mode' => $usedMode, 'results' => $data ); } }
hiraq/Cloggy
Module/CloggySearch/Model/CloggySearchFullText.php
PHP
bsd-3-clause
2,568
<!DOCTYPE html> <html> <head> <title>{title} - Montage Docs</title> <link rel="stylesheet" href="/mdl/material.min.css"> <link rel="stylesheet" href="/mdl/styles.css"> <script src="/mdl/material.min.js"></script> <link rel="stylesheet" href="https://tools-static.wmflabs.org/fontcdn/css?family=Roboto:400,200,100"> </head> <body class="mdl-montage mdl-color--grey-100 mdl-color-text--grey-700 mdl-base"> <header class="mdl-layout__header mdl-layout__header--scroll"> <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header"> <div class="mdl-layout--large-screen-only mdl-layout__header-row"> <button class="mdl-button mdl-js-button mdl-button--icon" disabled="disabled"> <img alt="Montage Logo" src="/dist/images/logo_white_fat.svg"> </button> <h1><a href="/docs/">Montage</a>: {title}</h1> </div> </div> </header> <main class="mdl-layout__content"> <section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp"> <div class="mdl-card mdl-cell mdl-cell--12-col"> <div class="mdl-card__supporting-text mdl-grid"> <p> <p>{?body}{body|s}{:else}Nothing to see here!{/body}</p> </p> </div> </div> </section> </main> </body> </html>
hatnote/montage
montage/templates/docs/base.html
HTML
bsd-3-clause
1,272
package org.usfirst.frc369.Robot2017Code.subsystems; import org.usfirst.frc369.Robot2017Code.Robot; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class LED extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void LEDOn(){ Robot.LEDSys.equals(Relay.Value.kForward); } public void LEDelse(){ Robot.LEDSys.equals(Relay.Value.kReverse); } public void LEDOff(){ Robot.LEDSys.equals(Relay.Value.kOff); } }
ShadowShitler/Bridgette
src/org/usfirst/frc369/Robot2017Code/subsystems/LED.java
Java
bsd-3-clause
726
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Javadoc API documentation for Fresco." /> <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> <title> com.facebook.imagepipeline.nativecode Details - Fresco API | Fresco </title> <link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" /> <script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script> <script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script> <script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script> <script src="../../../../../assets/prettify.js" type="text/javascript"></script> <script type="text/javascript"> setToRoot("../../../../", "../../../../../assets/"); </script> <script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script> <script src="../../../../../assets/navtree_data.js" type="text/javascript"></script> <script src="../../../../../assets/customizations.js" type="text/javascript"></script> <noscript> <style type="text/css"> html,body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> </head> <body class=""> <div id="header"> <div id="headerLeft"> <span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span> </div> <div id="headerRight"> <div id="search" > <div id="searchForm"> <form accept-charset="utf-8" class="gsc-search-box" onsubmit="return submit_search()"> <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody> <tr> <td class="gsc-input"> <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off" title="search developer docs" name="q" value="search developer docs" onFocus="search_focus_changed(this, true)" onBlur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../')" onkeyup="return search_changed(event, false, '../../../../')" /> <div id="search_filtered_div" class="no-display"> <table id="search_filtered" cellspacing=0> </table> </div> </td> <!-- <td class="gsc-search-button"> <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" /> </td> <td class="gsc-clear-button"> <div title="clear results" class="gsc-clear-button">&nbsp;</div> </td> --> </tr></tbody> </table> </form> </div><!-- searchForm --> </div><!-- search --> </div> </div><!-- header --> <div class="g-section g-tpl-240" id="body-content"> <div class="g-unit g-first side-nav-resizable" id="side-nav"> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> <ul> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li> <li class="selected api apilevel-"> <a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li> </ul><br/> </div> <!-- end packages --> </div> <!-- end resize-packages --> <div id="classes-nav"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoder.html">WebpTranscoder</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/Bitmaps.html">Bitmaps</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html">ImagePipelineNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/JpegTranscoder.html">JpegTranscoder</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeBlurFilter.html">NativeBlurFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeRoundingFilter.html">NativeRoundingFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/StaticWebpNativeLoader.html">StaticWebpNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderFactory.html">WebpTranscoderFactory</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderImpl.html">WebpTranscoderImpl</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> </div><!-- end nav-tree --> </div><!-- end swapper --> </div> <!-- end side-nav --> <script> if (!isMobile) { //$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../"); } else { addLoadEvent(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); } //$("#swapper").css({borderBottom:"2px solid #aaa"}); } else { swapNav(); // tree view should be used on mobile } </script> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <div class="api-level"> </div> </div> <div id="jd-header"> package <h1>com.facebook.imagepipeline.nativecode</b></h1> <div class="jd-nav"> <a class="jd-navlink" href="package-summary.html">Classes</a> | Description </div> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <div class="jd-descr"> <p></p> </div> <div id="footer"> +Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>. +</div> <!-- end footer - @generated --> </div><!-- end jd-content --> </div> <!-- end doc-content --> </div> <!-- end body-content --> <script type="text/javascript"> init(); /* initialize doclava-developer-docs.js */ </script> </body> </html>
MaTriXy/fresco
docs/javadoc/reference/com/facebook/imagepipeline/nativecode/package-descr.html
HTML
bsd-3-clause
17,812
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset', 'fct': 'Factom Factoid', 'fec': 'Factom Entry Credit', 'eth': 'Ethereum Ether' }; function isWalletName(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
netkicorp/walletname-chrome-extension
app/scripts.babel/netkiUtils.js
JavaScript
bsd-3-clause
573
<?php /** * Cache subsystem library * @package Cotonti * @version 0.9.10 * @author Cotonti Team * @copyright Copyright (c) Cotonti Team 2009-2014 * @license BSD */ defined('COT_CODE') or die('Wrong URL'); /** * Stores the list of advanced cachers provided by the host * @var array */ $cot_cache_drivers = array(); /** * Default cache realm */ define('COT_DEFAULT_REALM', 'cot'); /** * Default time to live for temporary cache objects */ define('COT_DEFAULT_TTL', 3600); /** * Default cache type, uneffective */ define('COT_CACHE_TYPE_ALL', 0); /** * Disk cache type */ define('COT_CACHE_TYPE_DISK', 1); /** * Database cache type */ define('COT_CACHE_TYPE_DB', 2); /** * Shared memory cache type */ define('COT_CACHE_TYPE_MEMORY', 3); /** * Page cache type */ define('COT_CACHE_TYPE_PAGE', 4); /** * Default cache type */ define('COT_CACHE_TYPE_DEFAULT', COT_CACHE_TYPE_DB); /** * Abstract class containing code common for all cache drivers * @author Cotonti Team */ abstract class Cache_driver { /** * Clears all cache entries served by current driver * @param string $realm Cache realm name, to clear specific realm only * @return bool */ abstract public function clear($realm = COT_DEFAULT_REALM); /** * Checks if an object is stored in cache * @param string $id Object identifier * @param string $realm Cache realm * @return bool */ abstract public function exists($id, $realm = COT_DEFAULT_REALM); /** * Returns value of cached image * @param string $id Object identifier * @param string $realm Realm name * @return mixed Cached item value or NULL if the item was not found in cache */ abstract public function get($id, $realm = COT_DEFAULT_REALM); /** * Removes object image from cache * @param string $id Object identifier * @param string $realm Realm name * @return bool */ abstract public function remove($id, $realm = COT_DEFAULT_REALM); } /** * Static cache is used to store large amounts of rarely modified data */ abstract class Static_cache_driver { /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @return bool */ abstract public function store($id, $data, $realm = COT_DEFAULT_REALM); } /** * Dynamic cache is used to store data that is not too large * and is modified more or less frequently */ abstract class Dynamic_cache_driver { /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool */ abstract public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL); } /** * Persistent cache driver that writes all entries back on script termination. * Persistent cache drivers work slower but guarantee long-term data consistency. */ abstract class Writeback_cache_driver extends Dynamic_cache_driver { /** * Values for delayed writeback to persistent cache * @var array */ protected $writeback_data = array(); /** * Keys that are to be removed */ protected $removed_data = array(); /** * Writes modified entries back to persistent storage */ abstract public function flush(); /** * Removes cache image of the object from the database * @param string $id Object identifier * @param string $realm Realm name */ public function remove($id, $realm = COT_DEFAULT_REALM) { $this->removed_data[] = array('id' => $id, 'realm' => $realm); } /** * Removes item immediately, avoiding writeback. * @param string $id Item identifirer * @param string $realm Cache realm * @return bool * @see Cache_driver::remove() */ abstract public function remove_now($id, $realm = COT_DEFAULT_REALM); /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0) { $this->writeback_data[] = array('id' => $id, 'data' => $data, 'realm' => $realm, 'ttl' => $ttl); return true; } /** * Writes item to cache immediately, avoiding writeback. * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ abstract public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL); } /** * Query cache drivers are driven by database */ abstract class Db_cache_driver extends Writeback_cache_driver { /** * Loads all variables from a specified realm(s) into the global scope * @param mixed $realm Realm name or array of realm names * @return int Number of items loaded */ abstract public function get_all($realm = COT_DEFAULT_REALM); } /** * Temporary cache driver is fast in-memory cache. It usually works faster and provides * automatic garbage collection, but it doesn't save data if PHP stops whatsoever. * Use it for individual frequently modified variables. */ abstract class Temporary_cache_driver extends Dynamic_cache_driver { /** * Increments counter value * @param string $id Counter identifier * @param string $realm Realm name * @param int $value Increment value * return int Result value */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { $res = $this->get($id, $realm); $res += $value; $this->store($id, $res, $realm); return $res; } /** * Decrements counter value * @param string $id Counter identifier * @param string $realm Realm name * @param int $value Increment value * return int Result value */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { $res = $this->get($id, $realm); $res -= $value; $this->store($id, $res, $realm); return $res; } /** * Returns information about memory usage if available. * Possible keys: available, occupied, max. * If the driver cannot provide a value, it sets it to -1. * @return array Associative array containing information */ abstract public function get_info(); /** * Gets a size limit from php.ini * @param string $name INI setting name * @return int Number of bytes */ protected function get_ini_size($name) { $ini = ini_get($name); $suffix = strtoupper(substr($ini, -1)); $prefix = substr($ini, 0, -1); switch ($suffix) { case 'K': return ((int) $prefix) * 1024; break; case 'M': return ((int) $prefix) * 1048576; break; case 'G': return ((int) $prefix) * 1073741824; break; default: return (int) $ini; } } } /** * A persistent cache using local file system tree. It does not use multilevel structure * or lexicograph search, so it may slow down when your cache grows very big. * But normally it is very fast reads. * @author Cotonti Team */ class File_cache extends Static_cache_driver { /** * Cache root directory * @var string */ private $dir; /** * Cache storage object constructor * @param string $dir Cache root directory. System default will be used if empty. * @throws Exception * @return File_cache */ public function __construct($dir = '') { global $cfg; if (empty($dir)) $dir = $cfg['cache_dir']; if (!empty($dir) && !file_exists($dir)) mkdir($dir, 0755, true); if (file_exists($dir) && is_writeable($dir)) { $this->dir = $dir; } else { throw new Exception('Cache directory '.$dir.' is not writeable!'); // TODO: Need translate } } /** * @see Cache_driver::clear() */ public function clear($realm = COT_DEFAULT_REALM) { if (empty($realm)) { if(is_dir($this->dir)) { $dp = opendir($this->dir); while ($f = readdir($dp)) { $dname = $this->dir.'/'.$f; if ($f[0] != '.' && is_dir($dname)) { $this->clear($f); } } closedir($dp); } } else { if(is_dir($this->dir.'/'.$realm)) { $dp = opendir($this->dir.'/'.$realm); while ($f = readdir($dp)) { $fname = $this->dir.'/'.$realm.'/'.$f; if (is_file($fname)) { unlink($fname); } } closedir($dp); } } return TRUE; } /** * Checks if an object is stored in disk cache * @param string $id Object identifier * @param string $realm Cache realm * @param int $ttl Lifetime in seconds, 0 means unlimited * @return bool */ public function exists($id, $realm = COT_DEFAULT_REALM, $ttl = 0) { $filename = $this->dir.'/'.$realm.'/'.$id; return file_exists($filename) && ($ttl == 0 || time() - filemtime($filename) < $ttl); } /** * Gets an object directly from disk * @param string $id Object identifier * @param string $realm Realm name * @param int $ttl Lifetime in seconds, 0 means unlimited * @return mixed Cached item value or NULL if the item was not found in cache */ public function get($id, $realm = COT_DEFAULT_REALM, $ttl = 0) { if ($this->exists($id, $realm, $ttl)) { return unserialize(file_get_contents($this->dir.'/'.$realm.'/'.$id)); } else { return NULL; } } /** * Removes cache image of the object from disk * @param string $id Object identifier * @param string $realm Realm name */ public function remove($id, $realm = COT_DEFAULT_REALM) { if ($this->exists($id, $realm)) { unlink($this->dir.'/'.$realm.'/'.$id); return true; } else return false; } /** * Stores disk cache entry * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @return bool */ public function store($id, $data, $realm = COT_DEFAULT_REALM) { if (!file_exists($this->dir.'/'.$realm)) { mkdir($this->dir.'/'.$realm); } file_put_contents($this->dir.'/'.$realm.'/'.$id, serialize($data)); return true; } } /** * A cache that stores entire page outputs. Disk-based. */ class Page_cache { /** * Cache root */ private $dir; /** * Relative page (item) path */ private $path; /** * Short file name */ private $name; /** * Parameters to exclude */ private $excl; /** * Filename extension */ private $ext; /** * Full path to page cache image */ private $filename; /** * Directory permissions */ private $perms; /** * Constructs controller object and sets basic configuration * @param string $dir Cache directory * @param int $perms Octal permission mask for cache directories */ public function __construct($dir, $perms = 0777) { $this->dir = $dir; $this->perms = $perms; } /** * Removes an item and all contained items and cache files * @param string $path Item path * @return int Number of files removed */ public function clear($path) { return $this->rm_r($this->dir . '/' . $path); } /** * Initializes actual page cache * @param string $path Page path string * @param string $name Short name for the cache file * @param array $exclude A list of GET params to be excluded from consideration * @param string $ext File extension */ public function init($path, $name, $exclude = array(), $ext = '') { $this->path = $path; $this->name = $name; $this->excl = $exclude; $this->ext = $ext; } /** * Reads the page cache object from disk and sends it to output. * If the cache object does not exist, then just calculates the path * for a following write() call. */ public function read() { $filename = $this->dir. '/' . $this->path . '/' . $this->name; $args = array(); foreach ($_GET as $key => $val) { if (!in_array($key, $this->excl)) { $args[$key] = $val; } } ksort($args); if (count($args) > 0) { $hashkey = serialize($args); $filename .= '_' . md5($hashkey) . sha1($hashkey); } if (!empty($this->ext)) { $filename .= '.' . $this->ext; } if (file_exists($filename)) { // Browser cache headers $filemtime = filemtime($filename); $etag = md5($filename . filesize($filename) . $filemtime); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // convert to unix timestamp $if_modified_since = strtotime(preg_replace('#;.*$#', '', stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']))); } else { $if_modified_since = false; } $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); if ($if_none_match == $etag && $if_modified_since >= $filemtime) { $protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; header($protocol . ' 304 Not Modified'); header("Etag: $etag"); exit; } header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', $filemtime)); header("ETag: $etag"); header('Expires: Mon, 01 Apr 1974 00:00:00 GMT'); header('Cache-Control: must-revalidate, proxy-revalidate'); // Page output header('Content-Type: text/html; charset=UTF-8'); if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE) { readgzfile($filename); } else { header('Content-Encoding: gzip'); echo file_get_contents($filename); } exit; } $this->filename = $filename; } /** * Writes output buffer contents to a cache image file */ public function write() { if (!empty($this->filename)) { if (!file_exists($this->dir . '/' . $this->path)) { mkdir($this->dir . '/' . $this->path, $this->perms, true); } file_put_contents($this->filename, gzencode(cot_outputfilters(ob_get_contents()))); } } /** * Removes a directory with all its contents recursively * @param string $path Directory path * @return int Number of items removed */ private function rm_r($path) { $cnt = 0; if(is_dir($path)) { $dp = opendir($path); while ($f = readdir($dp)) { $fpath = $path . '/' . $f; if (is_dir($fpath) && $f != '.' && $f != '..') { $cnt += $this->rm_r($fpath); } elseif (is_file($fpath)) { unlink($fpath); ++$cnt; } } closedir($dp); rmdir($path); } return ++$cnt; } } /** * A very popular caching solution using MySQL as a storage. It is quite slow compared to * File_cache but may be considered more reliable. * @author Cotonti Team */ class MySQL_cache extends Db_cache_driver { /** * Prefetched data to avoid duplicate queries * @var array */ private $buffer = array(); /** * Performs pre-load actions */ public function __construct() { // 10% GC probability if (mt_rand(1, 10) == 5) { $this->gc(); } } /** * Enforces flush() */ public function __destruct() { $this->flush(); } /** * Saves all modified data with one query */ public function flush() { global $db, $db_cache, $sys; if (count($this->removed_data) > 0) { $q = "DELETE FROM $db_cache WHERE"; $i = 0; foreach ($this->removed_data as $entry) { $c_name = $db->quote($entry['id']); $c_realm = $db->quote($entry['realm']); $or = $i == 0 ? '' : ' OR'; $q .= $or." (c_name = $c_name AND c_realm = $c_realm)"; $i++; } $this->removed_data = array(); $db->query($q); } if (count($this->writeback_data) > 0) { $q = "INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value) VALUES "; $i = 0; foreach ($this->writeback_data as $entry) { $c_name = $db->quote($entry['id']); $c_realm = $db->quote($entry['realm']); $c_expire = $entry['ttl'] > 0 ? $sys['now'] + $entry['ttl'] : 0; $c_value = $db->quote(serialize($entry['data'])); $comma = $i == 0 ? '' : ','; $q .= $comma."($c_name, $c_realm, $c_expire, $c_value)"; $i++; } $this->writeback_data = array(); $q .= " ON DUPLICATE KEY UPDATE c_value=VALUES(c_value), c_expire=VALUES(c_expire)"; $db->query($q); } } /** * @see Cache_driver::clear() */ public function clear($realm = '') { global $db, $db_cache; if (empty($realm)) { $db->query("TRUNCATE $db_cache"); } else { $db->query("DELETE FROM $db_cache WHERE c_realm = " . $db->quote($realm)); } $this->buffer = array(); return TRUE; } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { global $db, $db_cache; if (isset($this->buffer[$realm][$id])) { return true; } $sql = $db->query("SELECT c_value FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id)); $res = $sql->rowCount() == 1; if ($res) { $this->buffer[$realm][$id] = unserialize($sql->fetchColumn()); } return $res; } /** * Garbage collector function. Removes cache entries which are not valid anymore. * @return int Number of entries removed */ private function gc() { global $db, $db_cache, $sys; $db->query("DELETE FROM $db_cache WHERE c_expire > 0 AND c_expire < ".$sys['now']); return $db->affectedRows; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { if($this->exists($id, $realm)) { return $this->buffer[$realm][$id]; } else { return null; } } /** * @see Db_cache_driver::get_all() */ public function get_all($realms = COT_DEFAULT_REALM) { global $db, $db_cache; if (is_array($realms)) { $r_where = "c_realm IN("; $i = 0; foreach ($realms as $realm) { $glue = $i == 0 ? "'" : ",'"; $r_where .= $glue.$db->prep($realm)."'"; $i++; } $r_where .= ')'; } else { $r_where = "c_realm = '".$db->prep($realms)."'"; } $sql = $db->query("SELECT c_name, c_value FROM `$db_cache` WHERE c_auto=1 AND $r_where"); $i = 0; while ($row = $sql->fetch()) { global ${$row['c_name']}; ${$row['c_name']} = unserialize($row['c_value']); $i++; } $sql->closeCursor(); return $i; } /** * @see Writeback_cache_driver::remove_now() */ public function remove_now($id, $realm = COT_DEFAULT_REALM) { global $db, $db_cache; $db->query("DELETE FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id)); unset($this->buffer[$realm][$id]); return $db->affectedRows == 1; } /** * Stores data as object image in cache * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0) { global $db; // Check data length if ($data) { if (strlen($db->prep(serialize($data))) > 16777215) // MySQL max MEDIUMTEXT size { return false; } } return parent::store($id, $data, $realm, $ttl); } /** * Writes item to cache immediately, avoiding writeback. * @param string $id Object identifier * @param mixed $data Object value * @param string $realm Realm name * @param int $ttl Time to live, 0 for unlimited * @return bool * @see Cache_driver::store() */ public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { global $db, $db_cache, $sys; $c_name = $db->quote($id); $c_realm = $db->quote($realm); $c_expire = $ttl > 0 ? $sys['now'] + $ttl : 0; $c_value = $db->quote(serialize($data)); $db->query("INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value) VALUES ($c_name, $c_realm, $c_expire, $c_value)"); $this->buffer[$realm][$id] = $data; return $db->affectedRows == 1; } } if (extension_loaded('memcache')) { $cot_cache_drivers[] = 'Memcache_driver'; /** * Memcache distributed persistent cache driver implementation. Give it a higher priority * if a cluster of webservers is used and Memcached is running via TCP/IP between them. * In other circumstances this only should be used if no APC/XCache available, * keeping in mind that File_cache might be still faster. * @author Cotonti Team */ class Memcache_driver extends Temporary_cache_driver { /** * PHP Memcache instance * @var Memcache */ protected $memcache = NULL; /** * Creates an object and establishes Memcached server connection * @param string $host Memcached host * @param int $port Memcached port * @param bool $persistent Use persistent connection * @return Memcache_driver */ public function __construct($host = 'localhost', $port = 11211, $persistent = true) { $this->memcache = new Memcache; $this->memcache->addServer($host, $port, $persistent); } /** * Make unique key for one of different sites on one memcache pool * @param $key * @return string */ public static function createKey($key) { if (is_array($key)) $key = serialize($key); return md5(cot::$cfg['site_id'].$key); } /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (empty($realm)) { return $this->memcache->flush(); } else { // FIXME implement exact realm cleanup (not yet provided by Memcache) return $this->memcache->flush(); } } /** * @see Temporary_cache_driver::dec() */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { $id = self::createKey($id); return $this->memcache->decrement($realm.'/'.$id, $value); } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->get($realm.'/'.$id) !== FALSE; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->get($realm.'/'.$id); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { $info = $this->memcache->getstats(); return array( 'available' => $info['limit_maxbytes'] - $info['bytes'], 'max' => $info['limit_maxbytes'], 'occupied' => $info['bytes'] ); } /** * @see Temporary_cache_driver::inc() */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { $id = self::createKey($id); return $this->memcache->increment($realm.'/'.$id, $value); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { $id = self::createKey($id); return $this->memcache->delete($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { $id = self::createKey($id); return $this->memcache->set($realm.'/'.$id, $data, 0, $ttl); } } } if (extension_loaded('apc')) { $cot_cache_drivers[] = 'APC_driver'; /** * Accelerated PHP Cache driver implementation. This should be used as default cacher * on APC-enabled hosts. * @author Cotonti Team */ class APC_driver extends Temporary_cache_driver { /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (empty($realm)) { return apc_clear_cache(); } else { // TODO implement exact realm cleanup return FALSE; } } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { return apc_fetch($realm.'/'.$id) !== FALSE; } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { return unserialize(apc_fetch($realm.'/'.$id)); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { $info = apc_sma_info(); $max = ini_get('apc.shm_segments') * ini_get('apc.shm_size') * 1024 * 1024; $occupied = $max - $info['avail_mem']; return array( 'available' => $info['avail_mem'], 'max' => $max, 'occupied' => $occupied ); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { return apc_delete($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { // Protect from exhausted memory $info = $this->get_info(); if ($info['available'] < $info['max'] * 0.2) { $this->clear(); } return apc_store($realm.'/'.$id, serialize($data), $ttl); } } } if (extension_loaded('xcache')) { $cot_cache_drivers[] = 'Xcache_driver'; /** * XCache variable cache driver. It should be used on hosts that use XCache for * PHP acceleration and variable cache. * @author Cotonti Team */ class Xcache_driver extends Temporary_cache_driver { /** * @see Cache_driver::clear() */ public function clear($realm = '') { if (function_exists('xcache_unset_by_prefix')) { if (empty($realm)) { return xcache_unset_by_prefix(''); } else { return xcache_unset_by_prefix($realm.'/'); } } else { // This does not actually mean success but we can do nothing with it return true; } } /** * @see Cache_driver::exists() */ public function exists($id, $realm = COT_DEFAULT_REALM) { return xcache_isset($realm.'/'.$id); } /** * @see Temporary_cache_driver::dec() */ public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1) { return xcache_dec($realm.'/'.$id, $value); } /** * @see Cache_driver::get() */ public function get($id, $realm = COT_DEFAULT_REALM) { return xcache_get($realm.'/'.$id); } /** * @see Temporary_cache_driver::get_info() */ public function get_info() { return array( 'available' => -1, 'max' => $this->get_ini_size('xcache.var_size'), 'occupied' => -1 ); } /** * @see Temporary_cache_driver::inc() */ public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1) { return xcache_inc($realm.'/'.$id, $value); } /** * @see Cache_driver::remove() */ public function remove($id, $realm = COT_DEFAULT_REALM) { return xcache_unset($realm.'/'.$id); } /** * @see Dynamic_cache_driver::store() */ public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL) { return xcache_set($realm.'/'.$id, $data, $ttl); } } } /** * Multi-layer universal cache controller for Cotonti * * @property-read bool $mem_available Memory storage availability flag */ class Cache { /** * Persistent cache underlayer driver. * Stores disk-only cache entries. Use it for large objects, which you don't want to put * into memory cache. * @var Static_cache_driver */ public $disk; /** * Intermediate database cache driver. * It is recommended to use memory cache for particular objects rather than DB cache. * @var Db_cache_driver */ public $db; /** * Mutable top-layer shared memory driver. * Is FALSE if memory cache is not available * @var Temporary_cache_driver */ public $mem; /** * Page cache driver. * Is FALSE if page cache is disabled * @var Page_cache */ public $page; /** * Event bindings * @var array */ private $bindings; /** * A flag to apply binding changes before termination * @var bool */ private $resync_on_exit = false; /** * Selected memory driver * @var string */ private $selected_drv = ''; /** * Initializes Page cache for early page caching */ public function __construct() { global $cfg; $this->page = new Page_cache($cfg['cache_dir'], $cfg['dir_perms']); } /** * Performs actions before script termination */ public function __destruct() { if ($this->resync_on_exit) { $this->resync_bindings(); } } /** * Property handler * @param string $name Property name * @return mixed Property value */ public function __get($name) { switch ($name) { case 'mem_available': return $this->mem !== FALSE; break; case 'mem_driver': return $this->selected_drv; break; default: return null; break; } } /** * Initializes the rest Cache components when the sources are available */ public function init() { global $cfg, $cot_cache_autoload, $cot_cache_drivers, $cot_cache_bindings, $env; $this->disk = new File_cache($cfg['cache_dir']); $this->db = new MySQL_cache(); $cot_cache_autoload = is_array($cot_cache_autoload) ? array_merge(array('system', 'cot', $env['ext']), $cot_cache_autoload) : array('system', 'cot', $env['ext']); $this->db->get_all($cot_cache_autoload); $cfg['cache_drv'] .= '_driver'; if (in_array($cfg['cache_drv'], $cot_cache_drivers)) { $selected = $cfg['cache_drv']; } if (!empty($selected)) { $mem = new $selected(); // Some drivers may be enabled but without variable cache $info = $mem->get_info(); if ($info['max'] > 1024) { $this->mem = $mem; $this->selected_drv = $selected; } } else { $this->mem = false; } if (!$cot_cache_bindings) { $this->resync_bindings(); } else { unset($cot_cache_bindings); } } /** * Rereads bindings from database */ private function resync_bindings() { // global $db, $db_cache_bindings; $this->bindings = array(); // $sql = $db->query("SELECT * FROM `$db_cache_bindings`"); // while ($row = $sql->fetch()) // { // $this->bindings[$row['c_event']][] = array('id' => $row['c_id'], 'realm' => $row['c_realm']); // } // $sql->closeCursor(); // $this->db->store('cot_cache_bindings', $this->bindings, 'system'); } /** * Binds an event to automatic cache field invalidation * @param string $event Event name * @param string $id Cache entry id * @param string $realm Cache realm name * @param int $type Storage type, one of COT_CACHE_TYPE_* values * @return bool TRUE on success, FALSE on error */ public function bind($event, $id, $realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_DEFAULT) { global $db, $db_cache_bindings; $c_event = $db->quote($event); $c_id = $db->quote($id); $c_realm = $db->quote($realm); $c_type = (int) $type; $db->query("INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type) VALUES ($c_event, $c_id, $c_realm, $c_type)"); $res = $db->affectedRows == 1; if ($res) { $this->resync_on_exit = true; } return $res; } /** * Binds multiple cache fields to events, all represented as an associative array * Binding keys: * event - name of the event the field is binded to * id - cache object id * realm - cache realm name * type - cache storage type, one of COT_CACHE_TYPE_* constants * @param array $bindings An indexed array of bindings. * Each binding is an associative array with keys: event, realm, id, type. * @return int Number of bindings added */ public function bind_array($bindings) { global $db, $db_cache_bindings; $q = "INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type) VALUES "; $i = 0; foreach ($bindings as $entry) { $c_event = $db->prep($entry['event']); $c_id = $db->prep($entry['id']); $c_realm = $db->prep($entry['realm']); $c_type = (int) $entry['type']; $comma = $i == 0 ? '' : ','; $q .= $comma."('$c_event', '$c_id', '$c_realm', $c_type)"; } $db->query($q); $res = $db->affectedRows; if ($res > 0) { $this->resync_on_exit = true; } return $res; } /** * Clears all cache entries * @param int $type Cache storage type: * COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY. * @return bool */ public function clear($type = COT_CACHE_TYPE_ALL) { $res = true; switch ($type) { case COT_CACHE_TYPE_DB: $res = $this->db->clear(); break; case COT_CACHE_TYPE_DISK: $res = $this->disk->clear(); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $res = $this->mem->clear(); } break; case COT_CACHE_TYPE_PAGE: $res = $this->disk->clear(); break; default: if ($this->mem) { $res &= $this->mem->clear(); } $res &= $this->db->clear(); $res &= $this->disk->clear(); } return $res; } /** * Clears cache in specific realm * @param string $realm Realm name * @param int $type Cache storage type: * COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY. */ public function clear_realm($realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_ALL) { switch ($type) { case COT_CACHE_TYPE_DB: $this->db->clear($realm); break; case COT_CACHE_TYPE_DISK: $this->disk->clear($realm); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $this->mem->clear($realm); } break; case COT_CACHE_TYPE_PAGE: $this->page->clear($realm); break; default: if ($this->mem) { $this->mem->clear($realm); } $this->db->clear($realm); $this->disk->clear($realm); $this->page->clear($realm); } } /** * Returns information about memory driver usage * @return array Usage information */ public function get_info() { if ($this->mem) { return $this->mem->get_info(); } else { return array(); } } /** * Invalidates cache cells which were binded to the event. * @param string $event Event name * @return int Number of cells cleaned */ public function trigger($event) { $cnt = 0; if (isset($this->bindings[$event]) && count($this->bindings[$event]) > 0) { foreach ($this->bindings[$event] as $cell) { switch ($cell['type']) { case COT_CACHE_TYPE_DISK: $this->disk->remove($cell['id'], $cell['realm']); break; case COT_CACHE_TYPE_DB: $this->db->remove($cell['id'], $cell['realm']); break; case COT_CACHE_TYPE_MEMORY: if ($this->mem) { $this->mem->remove($cell['id'], $cell['realm']); } break; case COT_CACHE_TYPE_PAGE: $this->page->clear($cell['realm'] . '/' . $cell['id']); break; default: if ($this->mem) { $this->mem->remove($cell['id'], $cell['realm']); } $this->disk->remove($cell['id'], $cell['realm']); $this->db->remove($cell['id'], $cell['realm']); $this->page->clear($cell['realm'] . '/' . $cell['id']); } $cnt++; } } return $cnt; } /** * Removes event/cache bindings * @param string $realm Realm name (required) * @param string $id Object identifier. Optional, if not specified, all bindings from the realm are removed. * @return int Number of bindings removed */ public function unbind($realm, $id = '') { global $db, $db_cache_bindings; $c_realm = $db->quote($realm); $q = "DELETE FROM `$db_cache_bindings` WHERE c_realm = $c_realm"; if (!empty($id)) { $c_id = $db->quote($id); $q .= " AND c_id = $c_id"; } $db->query($q); $res = $db->affectedRows; if ($res > 0) { $this->resync_on_exit = true; } return $res; } }
Velm14/dribascorp
system/cache.php
PHP
bsd-3-clause
35,088
#!/bin/bash set -x # configure tweaks mv /tmp/docker-* /etc/apt/apt.conf.d chown root:root /etc/apt/apt.conf.d/docker-* chmod 644 /etc/apt/apt.conf.d/docker-* # make sure we're fully up-to-date apt-get update && apt-get dist-upgrade -y reboot
iknite/trusty64
src/provision/update.sh
Shell
bsd-3-clause
246
/*L * Copyright Ekagra Software Technologies Ltd. * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details. */ package gov.nih.nci.system.webservice; import gov.nih.nci.system.applicationservice.ApplicationService; import gov.nih.nci.system.client.proxy.ListProxy; import gov.nih.nci.system.query.hibernate.HQLCriteria; import gov.nih.nci.system.query.nestedcriteria.NestedCriteriaPath; import gov.nih.nci.system.util.ClassCache; import gov.nih.nci.system.webservice.util.WSUtils; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.rpc.ServiceException; import org.apache.log4j.Logger; import org.springframework.remoting.jaxrpc.ServletEndpointSupport; public class WSQueryImpl extends ServletEndpointSupport implements WSQuery{ private static Logger log = Logger.getLogger(WSQueryImpl.class); private static ApplicationService applicationService; private static ClassCache classCache; private static int resultCountPerQuery = 1000; public void destroy() { applicationService = null; classCache = null; resultCountPerQuery = 0; } protected void onInit() throws ServiceException { classCache = (ClassCache)getWebApplicationContext().getBean("ClassCache"); applicationService = (ApplicationService)getWebApplicationContext().getBean("ApplicationServiceImpl"); Properties systemProperties = (Properties) getWebApplicationContext().getBean("SystemProperties"); try { String count = systemProperties.getProperty("resultCountPerQuery"); log.debug("resultCountPerQuery: " + count); if (count != null) { resultCountPerQuery = Integer.parseInt(count); } } catch (Exception ex) { log.error("Exception initializing resultCountPerQuery: ", ex); throw new ServiceException("Exception initializing resultCountPerQuery: ", ex); } } public int getTotalNumberOfRecords(String targetClassName, Object criteria) throws Exception{ return getNestedCriteriaResultSet(targetClassName, criteria, 0).size(); } public List queryObject(String targetClassName, Object criteria) throws Exception { return query(targetClassName,criteria,0); } public List query(String targetClassName, Object criteria, int startIndex) throws Exception { List results = new ArrayList(); results = getNestedCriteriaResultSet(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List getNestedCriteriaResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ List<Object> paramList = new ArrayList<Object>(); paramList.add(searchCriteria); NestedCriteriaPath pathCriteria = new NestedCriteriaPath(targetClassName,paramList); results = applicationService.query(pathCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } public List getAssociation(Object source, String associationName, int startIndex) throws Exception { List results = new ArrayList(); String targetClassName = source.getClass().getName(); log.debug("targetClassName: " + targetClassName); String hql = "select obj."+associationName+" from "+targetClassName+" obj where obj = ?"; log.debug("hql: " + hql); List<Object> params = new ArrayList<Object>(); params.add(source); HQLCriteria criteria = new HQLCriteria(hql,params); results = getHQLResultSet(targetClassName, criteria, startIndex); List alteredResults = alterResultSet(results); return alteredResults; } private List getHQLResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{ List results = new ArrayList(); String searchClassName = getSearchClassName(targetClassName); try { if(searchClassName != null && searchCriteria != null){ results = applicationService.query(searchCriteria, startIndex, targetClassName); } else{ throw new Exception("Invalid arguments passed over to the server"); } } catch(Exception e) { log.error("WSQuery caught an exception: ", e); throw e; } return results; } private String getSearchClassName(String targetClassName)throws Exception { String searchClassName = ""; if(targetClassName.indexOf(",")>0){ StringTokenizer st = new StringTokenizer(targetClassName, ","); while(st.hasMoreTokens()){ String className = st.nextToken(); String validClassName = classCache.getQualifiedClassName(className); log.debug("validClassName: " + validClassName); searchClassName += validClassName + ","; } searchClassName = searchClassName.substring(0,searchClassName.lastIndexOf(",")); } else{ searchClassName = classCache.getQualifiedClassName(targetClassName); } if(searchClassName == null){ throw new Exception("Invalid class name: " + targetClassName); } return searchClassName; } private List alterResultSet(List results) { List objList; if (results instanceof ListProxy) { ListProxy listProxy = (ListProxy)results; objList = listProxy.getListChunk(); } else { objList = results; } WSUtils util = new WSUtils(); objList = (List)util.convertToProxy(null, objList); return objList; } }
NCIP/cacore-sdk-pre411
SDK4/system/src/gov/nih/nci/system/webservice/WSQueryImpl.java
Java
bsd-3-clause
5,667
ls | `cat` | wc -l | wc -c
pbiggar/rash
b.sh
Shell
bsd-3-clause
27
package au.gov.ga.geodesy.sitelog.domain.model; import javax.validation.constraints.Size; /** * http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/contact/2004/baseContactLib.xsd:contactType */ public class Contact { private Integer id; @Size(max = 200) protected String name; @Size(max = 200) protected String telephonePrimary; @Size(max = 200) protected String telephoneSecondary; @Size(max = 200) protected String fax; @Size(max = 200) protected String email; @SuppressWarnings("unused") private Integer getId() { return id; } @SuppressWarnings("unused") private void setId(Integer id) { this.id = id; } /** * Return name. */ public String getName() { return name; } /** * Set name. */ public void setName(String value) { this.name = value; } /** * Return primary telephone number. */ public String getTelephonePrimary() { return telephonePrimary; } /** * Set primary telephone number. */ public void setTelephonePrimary(String value) { this.telephonePrimary = value; } /** * Return secondary telephone number. */ public String getTelephoneSecondary() { return telephoneSecondary; } /** * Set secondary telephone number. */ public void setTelephoneSecondary(String value) { this.telephoneSecondary = value; } /** * Return fax number. */ public String getFax() { return fax; } /** * Set fax number. */ public void setFax(String value) { this.fax = value; } /** * Return email address. */ public String getEmail() { return email; } /** * Set email address. */ public void setEmail(String value) { this.email = value; } }
GeoscienceAustralia/geodesy-sitelog-domain
src/main/java/au/gov/ga/geodesy/sitelog/domain/model/Contact.java
Java
bsd-3-clause
1,834
namespace Leaderboard { public enum SortBy { None, Score, Rank } }
jalaziz/leaderboard-csharp
Leaderboard/SortBy.cs
C#
bsd-3-clause
106
#region License Header // /******************************************************************************* // * Open Behavioral Health Information Technology Architecture (OBHITA.org) // * // * 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 <organization> 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 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 <COPYRIGHT HOLDER> 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. // ******************************************************************************/ #endregion namespace ProCenter.Mvc.Infrastructure.Service.Completeness { #region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Domain.AssessmentModule.Lookups; using ProCenter.Domain.AssessmentModule.Metadata; using ProCenter.Service.Message.Assessment; using ProCenter.Service.Message.Common.Lookups; using ProCenter.Service.Message.Metadata; #endregion /// <summary>The completeness model validtor provider class.</summary> public class CompletenessModelValidtorProvider : ModelValidatorProvider { #region Public Methods and Operators /// <summary> /// Gets a list of validators. /// </summary> /// <param name="metadata">The metadata.</param> /// <param name="context">The context.</param> /// <returns> /// A list of validators. /// </returns> public override IEnumerable<ModelValidator> GetValidators ( ModelMetadata metadata, ControllerContext context ) { if ( metadata.PropertyName != null && context is ViewContext && (context.Controller.ViewData.Model is IValidateCompleteness || context.Controller.ViewData.Model is SectionDto )) { var viewContext = context as ViewContext; if ( viewContext.ViewData != null ) { if ( ( metadata.ContainerType == typeof(ItemDto) && metadata.PropertyName == "Value" ) || ( metadata.ContainerType == typeof(LookupDto) && metadata.PropertyName == "Code" ) ) { // only care about value var sectionDto = context.Controller.ViewData.Model is IValidateCompleteness ? (context.Controller.ViewData.Model as IValidateCompleteness).CurrentSectionDto : context.Controller.ViewData.Model as SectionDto; if ( sectionDto != null ) { var propertyParts = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName ( metadata.PropertyName ).Split ( '.' ); if ( propertyParts.Length == 2 ) { var index = propertyParts[0].IndexOf ( "_Value", StringComparison.Ordinal ); if ( index != -1 ) { var code = propertyParts[0].Substring ( 0, index ); var itemDto = GetItemDtoByCode ( sectionDto, code ); if ( itemDto != null ) { var metadataItemDto = itemDto.Metadata.FindMetadataItem<RequiredForCompletenessMetadataItem> (); if ( metadataItemDto != null ) { yield return new CompletenessModelValidator ( metadata, context, metadataItemDto.CompletenessCategory ); } } } } } } } } } #endregion #region Methods private static ItemDto GetItemDtoByCode ( IContainItems sectionDto, string code ) { foreach ( var itemDto in sectionDto.Items ) { if ( itemDto.ItemDefinitionCode == code && itemDto.ItemType == ItemType.Question.CodedConcept.Code ) { return itemDto; } if ( itemDto.Items != null ) { foreach ( var childItemDto in itemDto.Items.Where ( childItemDto => childItemDto.ItemDefinitionCode == code && childItemDto.ItemType == ItemType.Question.CodedConcept.Code ) ) { return childItemDto; } foreach (var containerDto in itemDto.Items.Where(i => i.ItemType != ItemType.Question.CodedConcept.Code).OfType<IContainItems> ()) { var childItem = GetItemDtoByCode ( containerDto, code ); if ( childItem != null ) { return childItem; } } } } return null; } #endregion } }
OBHITA/PROCenter
ProCenter.Mvc.Infrastructure/Service/Completeness/CompletenessModelValidtorProvider.cs
C#
bsd-3-clause
6,717
""" Commands that are available from the connect screen. """ import re import traceback from django.conf import settings from src.players.models import PlayerDB from src.objects.models import ObjectDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, utils, ansi from src.commands.default.muxcommand import MuxCommand from src.commands.cmdhandler import CMD_LOGINSTART # limit symbol import for API __all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", "CmdUnconnectedQuit", "CmdUnconnectedLook", "CmdUnconnectedHelp", "Magic") CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE CONNECTION_SCREEN = "" try: CONNECTION_SCREEN = ansi.parse_ansi(utils.string_from_module(CONNECTION_SCREEN_MODULE)) except Exception: pass if not CONNECTION_SCREEN: CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid." class Magic(MuxCommand): """ Hidden command for the web client's magic cookie authenticator. """ key = "magic" def func(self): session = self.caller player = PlayerDB.objects.player_search(self.lhs) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != self.lhs.lower(): player=None pswd = None if player: pswd = self.rhs == player.db.magic_cookie if not (player and pswd): # No playername or password match session.msg("Could not verify Magic Cookie. Please email the server administrator for assistance.") return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.{x" session.msg(string) session.execute_cmd("quit") return session.sessionhandler.login(session, player) class Connect(MuxCommand): """ Connect to the game. Usage (at login screen): connect playername password connect "player name" "pass word" Use the create command to first create an account before logging in. If you have spaces in your name, enclose it in quotes. """ key = "connect" aliases = ["conn", "con", "co"] locks = "cmd:all()" # not really needed def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller args = self.args # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: session.msg("\n\r Usage (without <>): connect <name> <password>") return playername, password = parts # Match account name and check password player = PlayerDB.objects.player_search(playername) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != playername.lower(): player=None pswd = None if player: pswd = player.check_password(password) if not (player and pswd): # No playername or password match string = "Wrong login information given.\nIf you have spaces in your name or " string += "password, don't forget to enclose it in quotes. Also capitalization matters." string += "\nIf you are new you should first create a new account " string += "using the 'create' command." session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.{x" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all other hooks: # session.at_init() # if character: # at_first_login() # only once # at_pre_login() # player.at_post_login() - calls look if no character is set # character.at_post_login() - this calls look command by default session.sessionhandler.login(session, player) class Create(MuxCommand): """ Create a new account. Usage (at login screen): create <playername> <password> create "player name" "pass word" This creates a new player account. If you have spaces in your name, enclose it in quotes. """ key = "create" aliases = ["cre", "cr"] locks = "cmd:all()" def func(self): "Do checks and create account" session = self.caller args = self.args.strip() # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: string = "\n Usage (without <>): create <name> <password>" string += "\nIf <name> or <password> contains spaces, enclose it in quotes." session.msg(string) return playername, password = parts print "playername '%s', password: '%s'" % (playername, password) # sanity checks if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 30): # this echoes the restrictions made by django's auth module (except not # allowing spaces, for convenience of logging in). string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only." session.msg(string) return # strip excessive spaces in playername playername = re.sub(r"\s+", " ", playername).strip() if PlayerDB.objects.filter(user__username__iexact=playername) or PlayerDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg("Sorry, there is already a player with the name '%s'." % playername) return if not re.findall('^[\w. @+-]+$', password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characers. Letters, spaces, digits and @\.\+\-\_ only." string += "\nFor best security, make it longer than 8 characters. You can also use a phrase of" string += "\nmany words if you enclose the password in quotes." session.msg(string) return # everything's ok. Create the new player account. try: default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME) typeclass = settings.BASE_CHARACTER_TYPECLASS permissions = settings.PERMISSION_PLAYER_DEFAULT try: new_character = create.create_player(playername, None, password, permissions=permissions, character_typeclass=typeclass, character_location=default_home, character_home=default_home) except Exception: session.msg("There was an error creating the default Character/Player:\n%s\n If this problem persists, contact an admin.") return new_player = new_character.player # This needs to be called so the engine knows this player is logging in for the first time. # (so it knows to call the right hooks during login later) utils.init_new_player(new_player) # join the new player to the public channel pchanneldef = settings.CHANNEL_PUBLIC if pchanneldef: pchannel = Channel.objects.get_channel(pchanneldef[0]) if not pchannel.connect_to(new_player): string = "New player '%s' could not connect to public channel!" % new_player.key logger.log_errmsg(string) # allow only the character itself and the player to puppet this character (and Immortals). new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, new_player.id)) # If no description is set, set a default description if not new_character.db.desc: new_character.db.desc = "This is a Player." # tell the caller everything went well. string = "A new account '%s' was created. Welcome!" if " " in playername: string += "\n\nYou can now log in with the command 'connect \"%s\" <your password>'." else: string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (playername, playername)) except Exception: # We are in the middle between logged in and -not, so we have to handle tracebacks # ourselves at this point. If we don't, we won't see any errors at all. string = "%s\nThis is a bug. Please e-mail an admin if the problem persists." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) class CmdUnconnectedQuit(MuxCommand): """ We maintain a different version of the quit command here for unconnected players for the sake of simplicity. The logged in version is a bit more complicated. """ key = "quit" aliases = ["q", "qu"] locks = "cmd:all()" def func(self): "Simply close the connection." session = self.caller session.msg("Good bye! Disconnecting ...") session.session_disconnect() class CmdUnconnectedLook(MuxCommand): """ This is an unconnected version of the look command for simplicity. This is called by the server and kicks everything in gear. All it does is display the connect screen. """ key = CMD_LOGINSTART aliases = ["look", "l"] locks = "cmd:all()" def func(self): "Show the connect screen." self.caller.msg(CONNECTION_SCREEN) class CmdUnconnectedHelp(MuxCommand): """ This is an unconnected version of the help command, for simplicity. It shows a pane of info. """ key = "help" aliases = ["h", "?"] locks = "cmd:all()" def func(self): "Shows help" string = \ """ You are not yet logged into the game. Commands available at this point: {wcreate, connect, look, help, quit{n To login to the system, you need to do one of the following: {w1){n If you have no previous account, you need to use the 'create' command. {wcreate Anna c67jHL8p{n Note that if you use spaces in your name, you have to enclose in quotes. {wcreate "Anna the Barbarian" c67jHL8p{n It's always a good idea (not only here, but everywhere on the net) to not use a regular word for your password. Make it longer than 6 characters or write a passphrase. {w2){n If you have an account already, either because you just created one in {w1){n above or you are returning, use the 'connect' command: {wconnect Anna c67jHL8p{n (Again, if there are spaces in the name you have to enclose it in quotes). This should log you in. Run {whelp{n again once you're logged in to get more aid. Hope you enjoy your stay! You can use the {wlook{n command if you want to see the connect screen again. """ self.caller.msg(string)
TaliesinSkye/evennia
wintersoasis-master/commands/unloggedin.py
Python
bsd-3-clause
12,835
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_14) on Fri Sep 18 14:09:15 BST 2009 --> <TITLE> uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </TITLE> <META NAME="date" CONTENT="2009-09-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanPortType.html" title="interface in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanPortType</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanRequest.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanRequest</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanRequestInterProScanInput.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanRequestInterProScanInput</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanResourceProperties.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanResourceProperties</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/InterProScanResponse.html" title="class in uk.org.mygrid.cagrid.servicewrapper.service.interproscan.stubs">InterProScanResponse</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/service/globus/resource/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../../../uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/bindings/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
NCIP/taverna-grid
servicewrapper/doc/uk/org/mygrid/cagrid/servicewrapper/service/interproscan/stubs/package-summary.html
HTML
bsd-3-clause
8,735
package edu.cmu.minorthird.text.gui; import edu.cmu.minorthird.text.FancyLoader; import edu.cmu.minorthird.text.TextLabels; import edu.cmu.minorthird.util.gui.ControlledViewer; import edu.cmu.minorthird.util.gui.VanillaViewer; import edu.cmu.minorthird.util.gui.Viewer; import edu.cmu.minorthird.util.gui.ViewerFrame; import edu.cmu.minorthird.util.gui.ZoomedViewer; /** * View the contents of a bunch of spans, using the util.gui.Viewer framework. * * <p> Hopefully this will evolve into a cleaner version of the * TextBaseViewer, TextBaseEditor, etc suite. It replaces an earlier * attempt, the SpanLooperViewer. * * @author William Cohen */ public class ZoomingTextLabelsViewer extends ZoomedViewer{ static final long serialVersionUID=20080202L; public ZoomingTextLabelsViewer(TextLabels labels){ Viewer zoomedOut=new ControlledViewer(new TextLabelsViewer(labels),new MarkupControls(labels)); Viewer zoomedIn=new VanillaViewer("[Empty TextBase]"); if(labels.getTextBase().size()>0){ zoomedIn=new SpanViewer(labels,labels.getTextBase().documentSpanIterator().next()); } this.setSubViews(zoomedOut,zoomedIn); } // test case public static void main(String[] argv){ try{ final TextLabels labels=FancyLoader.loadTextLabels(argv[0]); new ViewerFrame(argv[0],new ZoomingTextLabelsViewer(labels)); }catch(Exception e){ e.printStackTrace(); System.out.println("Usage: labelKey"); } } }
TeamCohen/MinorThird
src/main/java/edu/cmu/minorthird/text/gui/ZoomingTextLabelsViewer.java
Java
bsd-3-clause
1,434
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.PGConstant ( TestPGConstant(..) , spec ) where import Data.Proxy (Proxy(..)) import Database.PostgreSQL.Simple.Bind.Parser import Test.Hspec (Spec, describe) import Test.QuickCheck (Arbitrary(..), oneof) import Test.Common (PGSql(..)) import Test.Utils (propParsingWorks) import Test.PGString (TestPGString(..)) data TestPGConstant = TPGCString TestPGString | TPGCNumeric Double deriving (Show, Eq) instance Arbitrary TestPGConstant where arbitrary = oneof [ TPGCString <$> arbitrary , TPGCNumeric <$> arbitrary] instance PGSql TestPGConstant where render (TPGCString s) = render s render (TPGCNumeric c) = show c spec :: Spec spec = do describe "pgConstant" $ do propParsingWorks pgConstant (Proxy :: Proxy TestPGConstant)
zohl/postgresql-simple-bind
tests/Test/PGConstant.hs
Haskell
bsd-3-clause
1,133
<?php $modules["recurringinvoices"]["name"] = "Recurring Invoices"; $modules["recurringinvoices"]["version"] = "1.01"; $modules["recurringinvoices"]["description"] = "This module adds the ability to repeat invoices on a scheduled basis."; $modules["recurringinvoices"]["requirements"] = "phpBMS Core v0.9 or greater; BMS module v0.9 or greater; phpBMS Scheduler activated through cron or other scheduling program."; ?>
eandbsoftware/phpbms
modules/recurringinvoices/install/version.php
PHP
bsd-3-clause
434
/* eslint-disable no-underscore-dangle */ export default function ({ client, filterQuery, mustContain, busy, encodeQueryAsString, }) { return { listUsers(query) { const params = filterQuery( query, 'text', 'limit', 'offset', 'sort', 'sortdir' ); return busy( client._.get('/user', { params, }) ); }, createUser(user) { const expected = [ 'login', 'email', 'firstName', 'lastName', 'password', 'admin', ]; const params = filterQuery(user, ...expected); const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.post(`/user${encodeQueryAsString(params)}`)); }, changePassword(old, newPassword) { const params = { old, new: newPassword, }; return busy(client._.put(`/user/password${encodeQueryAsString(params)}`)); }, resetPassword(email) { const params = { email, }; return busy( client._.delete('/user/password', { params, }) ); }, deleteUser(id) { return busy(client._.delete(`/user/${id}`)); }, getUser(id) { return busy(client._.get(`/user/${id}`)); }, updateUser(user) { const expected = ['email', 'firstName', 'lastName', '_id']; const params = filterQuery(user, ...expected.slice(0, 3)); // Remove '_id' const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.put(`/user/${user._id}${encodeQueryAsString(params)}`)); }, }; }
Kitware/paraviewweb
src/IO/Girder/CoreEndpoints/user.js
JavaScript
bsd-3-clause
1,750
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <div id="container"></div> <script src="KineticJS/kinetic.js"></script> <script src="kiigame.js"></script> <script src="latkazombit.js"></script> </body> </html>
PrinsessaDiana/kiigame
kiigame.html
HTML
bsd-3-clause
352
module.exports = (function () { var TypeChecker = Cactus.Util.TypeChecker; var JSON = Cactus.Util.JSON; var stringify = JSON.stringify; var object = Cactus.Addon.Object; var collection = Cactus.Data.Collection; var gettype = TypeChecker.gettype.bind(TypeChecker); return { "null and undefined" : function () { var o = new TypeChecker({ type : "number" }); exception(/Expected "number", but got undefined \(type "undefined"\)/, o.parse.bind(o, undefined)); exception(/Expected "number", but got null \(type "null"\)/, o.parse.bind(o, null)); }, "required values" : function () { var o = new TypeChecker({ required : false, type : "boolean" }); equal(true, o.parse(true)); o.parse(null); }, "default value" : function () { var o = new TypeChecker({ type : "number", defaultValue : 3 }); assert.eql(3, o.parse(null)); assert.eql(4, o.parse(4)); o = new TypeChecker({ type : { a : { type : "number", defaultValue : 1 } } }); var h = o.parse({ a : 2 }); assert.eql(2, o.parse({ a : 2}).a); assert.eql(1, o.parse({ a : null }).a); assert.eql(1, o.parse({}).a); o = new TypeChecker({ type : { x : { type : "boolean", defaultValue : false } } }); eql({ x : true }, o.parse({ x : true })); eql({ x : false }, o.parse({ x : false })); eql({ x : false }, o.parse({})); // When not passing bool properties. o = new TypeChecker({ type : { b : { type : "boolean", defaultValue : false } } }); eql({ b : false }, o.parse({})); // Default values with incorrect types should have special error message (always throw error) exception(/Expected "boolean", but got 1/, function () { return new TypeChecker({ type : "boolean", defaultValue : 1 }); }); }, defaultValueFunc : function () { var o = new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "number" }); assert.strictEqual(1, o.parse(null)); o = new TypeChecker({ type : { a : { defaultValueFunc : function () { return 2; }, type : "number" } } }); assert.strictEqual(2, o.parse({ a : null }).a); assert.strictEqual(2, o.parse({}).a); // defaultValueFunc return value must match type. exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "boolean" }).parse(undefined); }); exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ type : { a : { defaultValueFunc : function () { return 1; }, type : "boolean" } } }).parse({}); }); }, validators : function () { var o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; } }] }); o.parse(1); o.parse(0, false); eql({ "" : ["Validation failed: got 0."] }, o.getErrors()); // Validation error message. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected positive number." }] }); o.parse(1); exception(/TypeChecker: Error: Expected positive number./, o.parse.bind(o, 0)); eql({ "" : ["Expected positive number."] }, o.getErrors()); // Multiple ordered validators. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > -1; }, message : "Expected number bigger than -1." }, { func : function (v) { return v < 1; }, message : "Expected number smaller than 1." }] }); o.parse(0); exception(/Expected number bigger than -1/i, o.parse.bind(o, -1)); exception(/Expected number smaller than 1/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected number bigger than 0." }, { func : function (v) { return v > 1; }, message : "Expected number bigger than 1." }] }); o.parse(2); exception(/bigger than 0.+ bigger than 1./i, o.parse.bind(o, 0)); }, "simple interface" : function () { var o = TypeChecker.simple("number"); o.parse(1); o = TypeChecker.simple(["number"]); o.parse([1]); o = TypeChecker.simple({ a : "number", b : "boolean" }); o.parse({ a : 1, b : true }); o = TypeChecker.simple({ a : ["number"] }); o.parse({ a : [1] }); o = TypeChecker.simple({ a : { b : "boolean" } }); o.parse({ a : { b : true } }); // Classes. Class("X"); o = TypeChecker.simple({ _type : X }); o.parse(new X()); o = TypeChecker.simple({ a : { _type : X } }); o.parse({ a : new X() }); }, errorHash : function () { var o = TypeChecker.simple("string"); exception(/Nothing parsed/i, o.hasErrors.bind(o)); exception(/Nothing parsed/i, o.getErrors.bind(o)); o.parse("x", false); exception(/No errors exist/, o.getErrors.bind(o)); o.parse(1, false); ok(o.hasErrors()); var errors = o.getErrors(); ok(o.hasErrorsFor("")); not(o.hasErrorsFor("foo")); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, o.getErrors()); o = TypeChecker.simple({ a : "number", b : "number" }); o.parse({ a : "x", b : true }, false); ok(o.hasErrors()); eql({ a : ['Expected "number", but got "x" (type "string")'], b : ['Expected "number", but got true (type "boolean")'] }, o.getErrors()); ok(o.hasErrorsFor("a")); ok(o.hasErrorsFor("b")); eql(['Expected "number", but got "x" (type "string")'], o.getErrorsFor("a")); eql(['Expected "number", but got true (type "boolean")'], o.getErrorsFor("b")); o = new TypeChecker({ type : "number", validators : [{ func : Function.returning(false), message : "false" }] }); o.parse(1, false); eql({ "" : ["false"] }, o.getErrors()); // Errors for array validators. o = new TypeChecker({ type : { p : { type : "string", validators : [{ func : Function.returning(false), message : "Error #1." }, { func : Function.returning(false), message : "Error #2." }] } } }); o.parse({ p : "" }, false); eql({ p : ["Error #1.", "Error #2."] }, o.getErrors()); // When Error is thrown, there should be a hash property with the error // messages as well. o = new TypeChecker({ type : "string" }); o.parse(1, false); assert.throws(o.parse.bind(o, 1), function (e) { assert.ok(/expected "string".+got 1 \(type "number"\)/i.test(e.message)); assert.ok("hash" in e, "Missing hash property"); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, e.hash); return true; }); }, validators2 : function () { // Validators should run only if all other validations pass. var ran = false; var o = new TypeChecker({ type : "number", defaultValue : 0, validators : [{ func : function (v) { ran = true; return v === 0; }, message : "Only way to validate is to send null or 0." }] }); o.parse(0); o.parse("x", false); eql({ "" : [ 'Expected "number", but got "x" (type "string")', 'Only way to validate is to send null or 0.' ] }, o.getErrors()); // Do not run validators if constraints fail. o.parse("x", false); assert.strictEqual(1, object.count(o.getErrors())); o.parse(-1, false); eql({ "" : ["Only way to validate is to send null or 0."] }, o.getErrors()); // Default value should be applied before validation as well. ran = false; assert.strictEqual(0, o.parse(null)); assert.ok(ran, "Validation did not run."); }, "predefined validations" : function () { var o = new TypeChecker({ type : "number", validators : ["natural"] }); o.parse(1); o.parse(0); o.parse(-1, false); eql({ "" : ["Expected natural number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["positive"] }); o.parse(1); o.parse(0, false); eql({ "" : ["Expected positive number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["negative"] }); o.parse(-1); o.parse(0, false); eql({ "" : ["Expected negative number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["x"] }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : { a : { type : "number", validators : ["x"] } } }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, { a : 1 })); o = new TypeChecker({ type : "string", validators : ["non empty string"] }); o.parse("x"); o.parse("", false); eql({ "" : ["Expected non-empty string."] }, o.getErrors()); }, T_Array : function () { eql([{ type : "string" }], gettype(new TypeChecker.types.T_Array({ type : "string" }))); var o = new TypeChecker({ type : [{ type : "number" }] }); eql([1, 2], o.parse([1, 2])); eql([], o.parse([])); exception(/Expected \[\{"type":"number"\}\], but got "a" \(type "string"\)/i, o.parse.bind(o, "a")); exception(/error in property "0": expected "number", but got "a" \(type "string"\)/i, o.parse.bind(o, ["a"])); exception(/error in property "1": expected "number", but got true \(type "boolean"\)/i, o.parse.bind(o, [1, true])); exception(/error in property "0": expected "number", but got "a"[\s\S]+error in property "1": expected "number", but got true/i, o.parse.bind(o, ["a", true])); // Nesting of arrays. var o = new TypeChecker({ type : [{ type : [{ type : "number" }] }] }); eql([[1, 2]], o.parse([[1, 2]])); exception(/^TypeChecker: Error in property "0": expected \[\{"type":"number"\}\], but got 1/i, o.parse.bind(o, [1, [2, 3]])); exception(/^TypeChecker: Error in property "1.1": expected "number", but got true/i, o.parse.bind(o, [[1], [2, true]])); eql([[]], o.parse([[]])); eql([], o.parse([])); // Optional arrays. o = new TypeChecker({ type : [{ type : "mixed" }], defaultValue : [] }); o.parse(null); // Optional array in hash. o = new TypeChecker({ type : { a : { type : [{ type : "number" }], defaultValue : [] } } }); o.parse({}); }, T_Primitive : function () { var o = new TypeChecker({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected "string", but got 1 \(type "number"\)/i, o.parse.bind(o, 1)); exception(/expected "string", but got true \(type "boolean"\)/i, o.parse.bind(o, true)); o = new TypeChecker({ type : "number" }); assert.eql(100, o.parse(100)); exception(/^TypeChecker: Error: Expected "number", but got "1" \(type "string"\)$/, o.parse.bind(o, "1")); // Default values o = new TypeChecker({ type : "boolean", defaultValue : false }); o.parse(true); o.parse(false); not(o.parse(null)); }, T_Enumerable : function () { var o = new TypeChecker({ enumerable : [1,2,3] }); eql(1, o.parse(1)); o.parse(2); o.parse(3); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 0$/, o.parse.bind(o, 0)); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 4$/, o.parse.bind(o, 4)); eql({ enumerable : [1,2,3] }, gettype(new TypeChecker.types.T_Enumerable([1, 2, 3]))); }, "T_Union" : function () { var o = new TypeChecker({ union : ["string", "number"] }); eql(1, o.parse(1)); eql("x", o.parse("x")); exception(/Expected a Union/, o.parse.bind(o, true)); eql({ union : [ { type : "string"}, { type : "number" } ]}, gettype(new TypeChecker.types.T_Union([ { type : "string" }, { type : "number" } ]))); }, "T_Instance" : function () { var Foo2 = Class("Foo2", {}); Class("Bar", { isa : Foo2 }); var o = new TypeChecker({ type : Foo2 }); var foo2 = new Foo2(); equal(foo2, o.parse(foo2)); o.parse(new Bar()); exception(/Expected an instance of "Foo2", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); Class("Baz"); exception(/Expected an instance of "Foo2", but got value <a Baz> \(type "Baz"\)$/, o.parse.bind(o, new Baz())); // Non-Joose classes. function Bax() { } function Qux() { } Qux.extend(Bax); o = new TypeChecker({ type : Bax }); o.parse(new Bax()); o.parse(new Qux()); function Qax() { } Qax.prototype.toString = function () { return "my Qax"; }; exception(/Expected an instance of "Bax", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); exception(/Expected an instance of "Bax", but got value <my Qax> \(type "Qax"\)$/, o.parse.bind(o, new Qax())); // Anonymous classes. var F = function () {}; var G = function () {}; o = new TypeChecker({ type : F }); G.extend(F); o.parse(new F()); o.parse(new G()); var H = function () {}; H.prototype.toString = Function.returning("my H"); exception(/Expected an instance of "anonymous type", but got value <1>/, o.parse.bind(o, 1)); exception(/Expected an instance of "anonymous type", but got value <my H> \(type "anonymous type"\)/i, o.parse.bind(o, new H())); function I() {} equal(I, gettype(new TypeChecker.types.T_Instance(I)).type); }, T_Hash : function () { var o = new TypeChecker({ x : { type : "boolean" } }); eql({ x : { type : "boolean" } }, gettype(new TypeChecker.types.T_Hash({ x : { type : "boolean" } }))); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); eql({ a : 1, b : true }, o.parse({ a : 1, b : true })); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); exception(/Expected \{"a":\{"type":"number"\},"b":\{"type":"boolean"\}\}, but got 1/i, o.parse.bind(o, 1)); exception(/Error in property "a": expected "number", but got "2"/i, o.parse.bind(o, { a : "2", b : true })); exception(/Error in property "a": expected "number", but got "2"[\s\S]+Error in property "b": expected "boolean", but got "2"/i, o.parse.bind(o, { a : "2", b : "2" })); exception(/Error in property "b": Missing property/, o.parse.bind(o, { a : 1 })); exception(/Error in property "c": Property lacks definition/i, o.parse.bind(o, { a : 1, b : true, c : "1" })); // With required specified. o = new TypeChecker({ type : { name : { type : "string", required : true } } }); assert.throws(o.parse.bind(o, {}), function (e) { assert.ok(/"name": Missing property/.test(e.message)); return true; }); // Non-required properties. o = new TypeChecker({ type : { a : { type : "number", required : false }, b : { type : "boolean", required : false } } }); eql({ a : 1, b : false }, o.parse({ a : 1, b : false })); var h = o.parse({ a : 1, b : undefined }); ok(!("b" in h)); h = o.parse({ a : 1, b : null }); equal(null, h.b); h = o.parse({ a : undefined, b : undefined }); ok(object.isEmpty(h)); h = o.parse({}); ok(object.isEmpty(h)); // Skip properties not in definition. o = new TypeChecker({ allowUndefined : true, type : { a : { type : "number" } } }); o.parse({}, false); eql({ a : ["Missing property"] }, o.getErrors()); o.parse({ a : 1 }); o.parse({ a : 1, b : 2 }); o.parse({ b : 2 }, false); eql({ a : ["Missing property"] }, o.getErrors()); // Remove skipped props that are undefined. eql({ a : 1 }, o.parse({ a : 1 })); }, T_Map : function () { var o = new TypeChecker({ map : true, type : "number" }); eql({ a : 1, b : 1 }, o.parse({ a : 1, b : 1 })); o.parse({ a : 1, b : false }, false); eql({ b : ['Expected "number", but got false (type "boolean")'] }, o.getErrors()); }, "T_Mixed" : function () { var o = new TypeChecker({ type : "mixed" }); equal(true, o.parse(true)); o.parse(""); o.parse({}); eql([], o.parse([])); ok(null === o.parse(null)); ok(undefined === o.parse(undefined)); equal("mixed", gettype(new TypeChecker.types.T_Mixed())); }, "typeof" : function () { var t = TypeChecker.typeof.bind(TypeChecker); equal("number", t(1)); equal("boolean", t(true)); equal("undefined", t(undefined)); equal("null", t(null)); equal("Function", t(function () {})); equal("Object", t({})); equal("Array", t([])); Class("JooseClass"); equal("JooseClass", t(new JooseClass())); function MyClass() {} equal("MyClass", t(new MyClass())); var AnonymousClass = function () {}; equal("anonymous type", t(new AnonymousClass)); }, "BUILD errors" : function () { exception(/Must be a hash/i, function () { return new TypeChecker(); }); exception(/May only specify one of required, defaultValue and defaultValueFunc/i, function () { return new TypeChecker({ required : true, defaultValue : 1 }); }); // required or defaultValue or defaultValueFunc }, helpers : function () { //var tc = new TypeChecker({ // type : "number", // validators : [{ // func : function (o, helpers) { // return !!helpers; // }, // message : "helpers == false" // }] //}); //tc.parse(1, true, true); //tc.parse(1, false, true); //eql({ // "" : ["helpers == false"] //}, tc.getErrors()); }, "recursive definition" : function () { var o = new TypeChecker({ type : { // type type : { required : false, type : "mixed", validators : [{ func : function (v) { if (typeof v === "string") { return collection.hasValue(["string", "number", "object", "function", "boolean", "mixed"], v); } else if (v instanceof Array) { // Flat check only. return v.length === 1; } else if (v instanceof Object) { // Flat check only. return true; } return false; } }] }, required : { type : "boolean", defaultValue : true }, defaultValue : { required : false, type : "mixed" }, defaultValueFunc : { required : false, type : Function }, validators : { type : [{ type : { func : { type : Function }, message : { type : "string" } } }], defaultValue : [] }, enumerable : { required : false, type : Array }, allowUndefined : { defaultValue : false, type : "boolean" } } }); o.parse({ type : "string" }); o.parse({ type : "number" }); o.parse({ required : false, type : "number" }); o.parse({ defaultValue : 3, type : "number" }); o.parse({ defaultValue : true, type : "boolean" }); o.parse({ defaultValue : 4, type : "mixed" }); o.parse({ defaultValue : {}, type : "mixed" }); o.parse({ defaultValueFunc : function () { return 1; }, type : "number" }); o.parse({ type : [{ type : "string" }] }); o.parse({ type : "mixed", validators : [{ func : Function.empty, message : "msg" }] }); o.parse({ type : "number", enumerable : [1,2,3] }); o.parse({ type : {} }); o.parse({ allowUndefined : true, type : {} }); } }; })();
bergmark/Cactus
module/Core/lib/Util/Util.TypeChecker.test.js
JavaScript
bsd-3-clause
22,955
<?php namespace common\models; use Yii; /** * This is the model class for table "mcp_accesslogs". * * @property integer $user_id * @property string $browser * @property string $ip * @property string $session * @property string $intime * @property string $outtime */ class McpAccesslogs extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'mcp_accesslogs'; } /** * @return \yii\db\Connection the database connection used by this AR class. */ public static function getDb() { return Yii::$app->get('oldcmsdb'); } /** * @inheritdoc */ public function rules() { return [ [['user_id'], 'integer'], [['intime', 'outtime'], 'safe'], [['browser'], 'string', 'max' => 255], [['ip'], 'string', 'max' => 30], [['session'], 'string', 'max' => 40] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'user_id' => 'user,s reference', 'browser' => 'Browser', 'ip' => 'Ip', 'session' => 'Session', 'intime' => 'Intime', 'outtime' => 'Outtime', ]; } }
rajanishtimes/partnerapi
common/models/McpAccesslogs.php
PHP
bsd-3-clause
1,297
--- title: "Permissions - ACLs" weight: 3 card: name: concept_organization --- There are 3 types of permissions: + Read (as code value: 4) + Read / Execute (as code value: 5) + Read / Write / Execute (as code value: 7) These permissions can be attached to different objects: + Project + Workflow + Workflow node | | Project | Workflow | Workflow node | |---------------------------------------------------------------------------------------|---------|----------|---------------------------------------------| | Create a workflow | RWX | - | - | | Edit a workflow (change run conditions, add nodes, edit payload, notifications, ...) | RO | RWX | - | | Create/edit an environment/pipeline/application | RWX | - | - | | Manage permissions on project | RWX | - | - | | Manage permissions on a workflow | RO | RWX | | | Run a workflow | RO | RX | / - OR RX (if there is some groups on node) | Permissions cannot be attached directly to users, they need to be attached to groups of users. Users inherit their permissions from the groups they are belonging to. Example usage: Enforce a strict separation of duties by allowing a group of people to view/inspect a workflow, a second group will be able to push it to a `deploy-to-staging` node and a third group will be allowed to push it to a `deploy-to-production` node. You can have a fourth group responsible of editing the workflow if needed. A more common scenario consists in giving `Read / Execute` permissions on the node `deploy-to-staging` to everyone in your development team while restricting the `deploy-to-production` node and the project edition to a smaller group of users. **Warning:** when you add a new group permission on a workflow node, **only the groups linked on the node will be taken in account**.
ovh/cds
docs/content/docs/concepts/permissions.md
Markdown
bsd-3-clause
2,457
/** * Swedish translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["sv-SE"] = { font_styles: { normal: "Normal Text", h1: "Rubrik 1", h2: "Rubrik 2", h3: "Rubrik 3" }, emphasis: { bold: "Fet", italic: "Kursiv", underline: "Understruken" }, lists: { unordered: "Osorterad lista", ordered: "Sorterad lista", outdent: "Minska indrag", indent: "Öka indrag" }, link: { insert: "Lägg till länk", cancel: "Avbryt" }, image: { insert: "Lägg till Bild", cancel: "Avbryt" }, html: { edit: "Redigera HTML" }, colours: { black: "Svart", silver: "Silver", gray: "Grå", maroon: "Kastaniebrun", red: "Röd", purple: "Lila", green: "Grön", olive: "Olivgrön", navy: "Marinblå", blue: "Blå", orange: "Orange" } }; }(jQuery));
landasystems/tamanharapan
backend/extensions/bootstrap/assets/js/locales/bootstrap-wysihtml5.sv-SE.js
JavaScript
bsd-3-clause
1,185
<?php namespace Tests\Unit; use Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class TextPostTest extends TestCase { use RefreshDatabase; protected $textPost; public function setup() { parent::setUp(); $this->authenticate(); $this->textPost = create('Knot\Models\TextPost', ['user_id' => auth()->id()]); } /** @test */ public function a_text_post_belongs_to_a_user() { $this->assertInstanceOf('Knot\Models\User', $this->textPost->user); } /** @test */ public function a_text_has_an_associated_generic_post() { $this->assertInstanceOf('Knot\Models\Post', $this->textPost->post); } }
fam-jam/fam-jam-server
tests/Unit/TextPostTest.php
PHP
bsd-3-clause
702
/////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // This example code is from the book: // // Object-Oriented Programming with C++ and OSF/Motif // by // Douglas Young // Prentice Hall, 1992 // ISBN 0-13-630252-1 // // Copyright 1991 by Prentice Hall // All Rights Reserved // // Permission to use, copy, modify, and distribute this software for // any purpose except publication and without fee is hereby granted, provided // that the above copyright notice appear in all copies of the software. /////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // DialogManager.h: A base class for cached dialogs ////////////////////////////////////////////////////////// #ifndef DIALOGMANAGER_H #define DIALOGMANAGER_H #include "UIComponent.h" #include "DialogCallbackData.h" class DialogManager : public UIComponent { private: Widget getDialog(); static void destroyTmpDialogCallback ( Widget, XtPointer, XtPointer ); static void okCallback ( Widget, XtPointer, XtPointer ); static void cancelCallback ( Widget, XtPointer, XtPointer ); static void helpCallback ( Widget, XtPointer, XtPointer ); void cleanup ( Widget, DialogCallbackData* ); protected: // Called to get a new dialog virtual Widget createDialog ( Widget ) = 0; public: DialogManager ( const char * ); virtual Widget post ( const char *, void *clientData = NULL, DialogCallback ok = NULL, DialogCallback cancel = NULL, DialogCallback help = NULL ); }; #endif
marrocamp/nasa-VICAR
vos/MotifApp/DialogManager.h
C
bsd-3-clause
1,971
<?php namespace Users; use Zend\EventManager\EventInterface as Event; use Users\Model\AuthorisationClass as AuthorisationClass; class Module { public function onBootstrap(Event $e) { // This method is called once the MVC bootstrapping is complete $application = $e->getApplication(); $services = $application->getServiceManager(); $e -> getApplication() -> getEventManager() -> getSharedManager() -> attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) { $controller = $e -> getTarget(); $full_controller_name = $controller -> params('controller'); $id=0; if ($user = $controller -> identity()) { $role = $user -> getRoleName()->getName(); $id = $user->getId(); } else { $role = 'guest'; } $routeMatch = $e->getRouteMatch(); $checkId = $routeMatch->getParam('param0',0); $controllerClass = $routeMatch->getParam('controller',0); $controllerClassArray = explode('\\', $controllerClass); $controllerName = $controllerClassArray['2']; $moduleName = $controllerClassArray['0']; $role = strtolower($role); $routeCheck = $moduleName.'\\'.$controllerName; $acl = new AuthorisationClass($id,$checkId); if (!$acl->isAuthorised($role,$routeCheck,$routeMatch->getParam('action'))) { $response = $e -> getResponse(); $response -> getHeaders() -> addHeaderLine('Location', '/users/auth/failure/Please log in as an authorised user to view that page'); $response -> setStatusCode(302); $response -> sendHeaders(); exit ; } }, 100); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getServiceConfig() { return array( 'factories' => array( 'Zend\Authentication\AuthenticationService' => function($serviceManager) { // If you are using DoctrineORMModule: return $serviceManager->get('doctrine.authenticationservice.orm_default'); // If you are using DoctrineODMModule: return $serviceManager->get('doctrine.authenticationservice.odm_default'); } ) ); } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } }
JoostvdB94/RapidJupiter
module/Users/Module.php
PHP
bsd-3-clause
2,835
// RUN: %clang_builtins %s %librt -o %t && %run %t //===-- ctzti2_test.c - Test __ctzti2 -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file tests __ctzti2 for the compiler_rt library. // //===----------------------------------------------------------------------===// #include "int_lib.h" #include <stdio.h> #ifdef CRT_HAS_128BIT // Returns: the number of trailing 0-bits // Precondition: a != 0 COMPILER_RT_ABI si_int __ctzti2(ti_int a); int test__ctzti2(ti_int a, si_int expected) { si_int x = __ctzti2(a); if (x != expected) { twords at; at.all = a; printf("error in __ctzti2(0x%llX%.16llX) = %d, expected %d\n", at.s.high, at.s.low, x, expected); } return x != expected; } char assumption_1[sizeof(ti_int) == 2*sizeof(di_int)] = {0}; #endif int main() { #ifdef CRT_HAS_128BIT if (test__ctzti2(0x00000001, 0)) return 1; if (test__ctzti2(0x00000002, 1)) return 1; if (test__ctzti2(0x00000003, 0)) return 1; if (test__ctzti2(0x00000004, 2)) return 1; if (test__ctzti2(0x00000005, 0)) return 1; if (test__ctzti2(0x0000000A, 1)) return 1; if (test__ctzti2(0x10000000, 28)) return 1; if (test__ctzti2(0x20000000, 29)) return 1; if (test__ctzti2(0x60000000, 29)) return 1; if (test__ctzti2(0x80000000uLL, 31)) return 1; if (test__ctzti2(0x0000050000000000uLL, 40)) return 1; if (test__ctzti2(0x0200080000000000uLL, 43)) return 1; if (test__ctzti2(0x7200000000000000uLL, 57)) return 1; if (test__ctzti2(0x8000000000000000uLL, 63)) return 1; if (test__ctzti2(make_ti(0x00000000A0000000LL, 0x0000000000000000LL), 93)) return 1; if (test__ctzti2(make_ti(0xF000000000000000LL, 0x0000000000000000LL), 124)) return 1; if (test__ctzti2(make_ti(0x8000000000000000LL, 0x0000000000000000LL), 127)) return 1; #else printf("skipped\n"); #endif return 0; }
youtube/cobalt
third_party/llvm-project/compiler-rt/test/builtins/Unit/ctzti2_test.c
C
bsd-3-clause
2,303
CREATE TABLE test_table(column_integer INTEGER, column_smallint SMALLINT, column_numeric_9_2 NUMERIC(9,2), column_char_9 CHAR(9), column_varchar_92 VARCHAR(92), column_date DATE, column_bit BIT(4), column_time TIME, column_timestamp TIMESTAMP, column_datetime datetime, monet monetary, big bigint, float_num float, double_num double, PRIMARY KEY (column_integer) ); INSERT INTO test_table VALUES(1, 11, 1.1, '1', '2/28/2001', '12/31/2002', NULL, '07:00:34 PM', '05:55:31 PM 05/04/2002', '05:55:31 PM 05/04/2000', 123.3, 4444444444444, 44.44, 44.44); select str_to_date(column_varchar_92, '%m/%d/%Y') from test_table where column_integer = 1; select str_to_date(123, '%m/%d/%Y'); select str_to_date('07:00:34 PM', '%r'); select str_to_date('07:00:34 PM', '% r'); select str_to_date('05:55:31 PM 05/04/2002', '%r %m/%d/%Y'); select str_to_date('07:00:34 PM', '0%%%q %r'); select str_to_date('Sat Jan 12 3rd', '%a %b %c %D'), str_to_date('Foo', '%a'), str_to_date('Bar', '%b'), str_to_date('-1', '%c'), str_to_date('-2nd', '%D'); select str_to_date('31 999999 21', '%e %f %H'), str_to_date('-4', '%d'), str_to_date('-3', '%e'), str_to_date('-1', '%f'), str_to_date('-2', '%H'); select str_to_date('11 11 311 11', '%I %i %j %k'), str_to_date('-1', '%i'), str_to_date('-1', '%I'), str_to_date('-1', '%j'), str_to_date('-2', '%k'); select str_to_date('11 am pm', '%l %p %p'), str_to_date('-1', '%l'), str_to_date('genaro', '%M'), str_to_date('-1', '%m'), str_to_date('gm', '%p'); select str_to_date('07 : 00 : 34 PM 07:00:34 AM 88', '%r %r %S'), str_to_date('-07:00:34 PM', '%r'), str_to_date('07:-01:34 PM', '%r'), str_to_date('07:00:-34 PM', '%r'); select str_to_date('07x00:34 PM', '%r'), str_to_date('07:01x34 PM', '%r'), str_to_date('07:00:34 gm', '%r'), str_to_date('-99', '%S'), str_to_date('-14', '%s'); select str_to_date('07 : 00 : 34 88 33', '%T %u %U'), str_to_date('-07:00:34', '%T'), str_to_date('07:-01:34', '%T'), str_to_date('07:00:-34', '%T'); select str_to_date('07x00:34', '%T'), str_to_date('07:01x34', '%T'), str_to_date('-99', '%u'), str_to_date('-14', '%U'); select str_to_date('12 12 Monday 0', '%v %V %W %w'), str_to_date('-1', '%v'), str_to_date('-1', '%V'), str_to_date('mandei', '%W'), str_to_date('-2', '%w'); select str_to_date('12 12 78 30 2000', '%x %X %y %y %Y'), str_to_date('-1', '%x'), str_to_date('-1', '%X'), str_to_date('-99', '%y'), str_to_date('-2', '%Y'); select str_to_date('23 am', '%H %p'); select str_to_date('0000', '%Y'); select str_to_date('13 2002', '%m %Y'); select str_to_date('32 2002', '%d %Y'); select str_to_date('04/2002', '%d/%Y'); select str_to_date('29 02 2001', '%d %m %Y'); select str_to_date('2001 54', '%Y %u'); select str_to_date('2001 54', '%x %v'); select str_to_date('2001 0', '%x %v'); select str_to_date('2001 0', '%X %V'); select str_to_date('2001 999', '%Y %j'); select str_to_date('2001 9', '%Y %w'); select str_to_date('23 am', '%h %p'); select str_to_date('70', '%i'); select str_to_date('70', '%s'); select str_to_date('1999 40 0', '%Y %u %w'); select str_to_date('1999 40 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %U %w'); select str_to_date('1999 0 0', '%Y %u %w'); select str_to_date('1999 30 0', '%Y %u %w'); select str_to_date('1998 0 4', '%Y %u %w'); select str_to_date('1998 300', '%Y %j'); select str_to_date('1998 300 23:14:34', '%Y %j %T'); select str_to_date('2000 53 6', '%Y %U %w'); select str_to_date('2001 53 6', '%Y %U %w'); select str_to_date('2007 53 6', '%Y %U %w'); DROP TABLE test_table;
CUBRID/cubrid-testcases
sql/_12_mysql_compatibility/_11_code_coverage/_06_datetime_functions/cases/_012_str_to_date.sql
SQL
bsd-3-clause
3,516
<?php /* @var $this yii\web\View */ $this->title = 'My Yii Application'; ?> <div class="bodyParser"> <?=$this->render('table', [ 'dataHistory' => $dataHistory ])?> </div>
TexToro/parser-on-yii2
frontend/views/site/index.php
PHP
bsd-3-clause
189
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.sandbox.stats.multicomp.randmvn &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.sandbox.stats.multicomp.rankdata" href="statsmodels.sandbox.stats.multicomp.rankdata.html" /> <link rel="prev" title="statsmodels.sandbox.stats.multicomp.qcrit" href="statsmodels.sandbox.stats.multicomp.qcrit.html" /> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.sandbox.stats.multicomp.randmvn" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.11.1</span> <span class="md-header-nav__topic"> statsmodels.sandbox.stats.multicomp.randmvn </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.11.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.stats.multicomp.randmvn.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-sandbox-stats-multicomp-randmvn--page-root">statsmodels.sandbox.stats.multicomp.randmvn<a class="headerlink" href="#generated-statsmodels-sandbox-stats-multicomp-randmvn--page-root" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="statsmodels.sandbox.stats.multicomp.randmvn"> <code class="sig-prename descclassname">statsmodels.sandbox.stats.multicomp.</code><code class="sig-name descname">randmvn</code><span class="sig-paren">(</span><em class="sig-param">rho</em>, <em class="sig-param">size=(1</em>, <em class="sig-param">2)</em>, <em class="sig-param">standardize=False</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/stats/multicomp.html#randmvn"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.sandbox.stats.multicomp.randmvn" title="Permalink to this definition">¶</a></dt> <dd><p>create random draws from equi-correlated multivariate normal distribution</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>rho</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#float" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">float</span></code></a></span></dt><dd><p>correlation coefficient</p> </dd> <dt><strong>size</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#tuple" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">tuple</span></code></a> <code class="xref py py-obj docutils literal notranslate"><span class="pre">of</span></code> <a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">int</span></code></a></span></dt><dd><p>size is interpreted (nobs, nvars) where each row</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl> <dt><strong>rvs</strong><span class="classifier"><a class="reference external" href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray" title="(in NumPy v1.17)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ndarray</span></code></a></span></dt><dd><p>nobs by nvars where each row is a independent random draw of nvars- dimensional correlated rvs</p> </dd> </dl> </dd> </dl> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.sandbox.stats.multicomp.qcrit.html" title="Material" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.stats.multicomp.qcrit </span> </div> </a> <a href="statsmodels.sandbox.stats.multicomp.rankdata.html" title="Admonition" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.stats.multicomp.rankdata </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 21, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 2.4.2. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.11.1/generated/statsmodels.sandbox.stats.multicomp.randmvn.html
HTML
bsd-3-clause
19,790
/* * from: FreeBSD: src/sys/tools/fw_stub.awk,v 1.6 2007/03/02 11:42:53 flz */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cxgb/cxgb_t3fw.c 189643 2009-03-10 19:22:45Z gnn $"); #include <sys/param.h> #include <sys/errno.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/systm.h> #include <cxgb_t3fw.h> #include <t3b_protocol_sram.h> #include <t3b_tp_eeprom.h> #include <t3c_protocol_sram.h> #include <t3c_tp_eeprom.h> static int cxgb_t3fw_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3fw", t3fw, (size_t)t3fw_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3fw"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3fw_mod = { "cxgb_t3fw", cxgb_t3fw_modevent, 0 }; DECLARE_MODULE(cxgb_t3fw, cxgb_t3fw_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3fw, 1); MODULE_DEPEND(cxgb_t3fw, firmware, 1, 1, 1); static int cxgb_t3b_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_protocol_sram", t3b_protocol_sram, (size_t)t3b_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_protocol_sram_mod = { "cxgb_t3b_protocol_sram", cxgb_t3b_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_protocol_sram, cxgb_t3b_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_protocol_sram, 1); MODULE_DEPEND(cxgb_t3b_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3b_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3b_tp_eeprom", t3b_tp_eeprom, (size_t)t3b_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3b_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3b_tp_eeprom_mod = { "cxgb_t3b_tp_eeprom", cxgb_t3b_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3b_tp_eeprom, cxgb_t3b_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3b_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3b_tp_eeprom, firmware, 1, 1, 1); static int cxgb_t3c_protocol_sram_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_protocol_sram", t3c_protocol_sram, (size_t)t3c_protocol_sram_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_protocol_sram"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_protocol_sram_mod = { "cxgb_t3c_protocol_sram", cxgb_t3c_protocol_sram_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_protocol_sram, cxgb_t3c_protocol_sram_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_protocol_sram, 1); MODULE_DEPEND(cxgb_t3c_protocol_sram, firmware, 1, 1, 1); static int cxgb_t3c_tp_eeprom_modevent(module_t mod, int type, void *unused) { const struct firmware *fp, *parent; int error; switch (type) { case MOD_LOAD: fp = firmware_register("cxgb_t3c_tp_eeprom", t3c_tp_eeprom, (size_t)t3c_tp_eeprom_length, 0, NULL); if (fp == NULL) goto fail_0; parent = fp; return (0); fail_0: return (ENXIO); case MOD_UNLOAD: error = firmware_unregister("cxgb_t3c_tp_eeprom"); return (error); } return (EINVAL); } static moduledata_t cxgb_t3c_tp_eeprom_mod = { "cxgb_t3c_tp_eeprom", cxgb_t3c_tp_eeprom_modevent, 0 }; DECLARE_MODULE(cxgb_t3c_tp_eeprom, cxgb_t3c_tp_eeprom_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST); MODULE_VERSION(cxgb_t3c_tp_eeprom, 1); MODULE_DEPEND(cxgb_t3c_tp_eeprom, firmware, 1, 1, 1);
dcui/FreeBSD-9.3_kernel
sys/dev/cxgb/cxgb_t3fw.c
C
bsd-3-clause
4,506
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import os import subprocess import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import pynacl.platform python = sys.executable bash = '/bin/bash' echo = 'echo' BOT_ASSIGNMENT = { ###################################################################### # Buildbots. ###################################################################### 'xp-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', 'xp-bare-newlib-opt': python + ' buildbot\\buildbot_standard.py opt 32 newlib --no-gyp', 'xp-bare-glibc-opt': python + ' buildbot\\buildbot_standard.py opt 32 glibc --no-gyp', 'precise-64-validator-opt': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', # Clang. 'precise_64-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'mac10.7-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # ASan. 'precise_64-newlib-dbg-asan': python + ' buildbot/buildbot_standard.py opt 64 newlib --asan', 'mac10.7-newlib-dbg-asan': python + ' buildbot/buildbot_standard.py opt 32 newlib --asan', # PNaCl. 'oneiric_32-newlib-arm_hw-pnacl-panda-dbg': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-dbg', 'oneiric_32-newlib-arm_hw-pnacl-panda-opt': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-opt', 'precise_64-newlib-arm_qemu-pnacl-dbg': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-dbg', 'precise_64-newlib-arm_qemu-pnacl-opt': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-opt', 'precise_64-newlib-x86_32-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'precise_64-newlib-x86_64-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'mac10.8-newlib-opt-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'win7-64-newlib-opt-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'precise_64-newlib-mips-pnacl': echo + ' "TODO(mseaborn): add mips"', # PNaCl Spec 'precise_64-newlib-arm_qemu-pnacl-buildonly-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-buildonly', 'oneiric_32-newlib-arm_hw-pnacl-panda-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-arm-hw', 'lucid_64-newlib-x86_32-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8632', 'lucid_64-newlib-x86_64-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-x8664', # NaCl Spec 'lucid_64-newlib-x86_32-spec': bash + ' buildbot/buildbot_spec2k.sh nacl-x8632', 'lucid_64-newlib-x86_64-spec': bash + ' buildbot/buildbot_spec2k.sh nacl-x8664', # Valgrind bots. 'precise-64-newlib-dbg-valgrind': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', 'precise-64-glibc-dbg-valgrind': echo + ' "Valgrind bots are disabled: see ' 'https://code.google.com/p/nativeclient/issues/detail?id=3158"', # Coverage. 'mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'precise-64-32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), 'precise-64-64-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'xp-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), ###################################################################### # Trybots. ###################################################################### 'nacl-precise64_validator_opt': python + ' buildbot/buildbot_standard.py opt 64 glibc --validator', 'nacl-precise64_newlib_dbg_valgrind': bash + ' buildbot/buildbot_valgrind.sh newlib', 'nacl-precise64_glibc_dbg_valgrind': bash + ' buildbot/buildbot_valgrind.sh glibc', # Coverage trybots. 'nacl-mac10.6-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'nacl-precise-64-32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), 'nacl-precise-64-64-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 64 newlib --coverage'), 'nacl-win32-newlib-coverage': python + (' buildbot/buildbot_standard.py ' 'coverage 32 newlib --coverage'), # Clang trybots. 'nacl-precise_64-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 64 newlib --clang', 'nacl-mac10.6-newlib-dbg-clang': python + ' buildbot/buildbot_standard.py dbg 32 newlib --clang', # Pnacl main trybots 'nacl-precise_64-newlib-arm_qemu-pnacl': bash + ' buildbot/buildbot_pnacl.sh mode-trybot-qemu', 'nacl-precise_64-newlib-x86_32-pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'nacl-precise_64-newlib-x86_64-pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', 'nacl-precise_64-newlib-mips-pnacl': echo + ' "TODO(mseaborn): add mips"', 'nacl-arm_opt_panda': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-try', 'nacl-arm_hw_opt_panda': bash + ' buildbot/buildbot_pnacl.sh mode-buildbot-arm-hw-try', 'nacl-mac10.8_newlib_opt_pnacl': python + ' buildbot/buildbot_pnacl.py opt 32 pnacl', 'nacl-win7_64_newlib_opt_pnacl': python + ' buildbot/buildbot_pnacl.py opt 64 pnacl', # Pnacl spec2k trybots 'nacl-precise_64-newlib-x86_32-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8632', 'nacl-precise_64-newlib-x86_64-pnacl-spec': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-x8664', 'nacl-arm_perf_panda': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-arm-buildonly', 'nacl-arm_hw_perf_panda': bash + ' buildbot/buildbot_spec2k.sh pnacl-trybot-arm-hw', # Toolchain glibc. 'precise64-glibc': bash + ' buildbot/buildbot_linux-glibc-makefile.sh', 'mac-glibc': bash + ' buildbot/buildbot_mac-glibc-makefile.sh', 'win7-glibc': 'buildbot\\buildbot_windows-glibc-makefile.bat', # Toolchain newlib x86. 'win7-toolchain_x86': 'buildbot\\buildbot_toolchain_win.bat', 'mac-toolchain_x86': bash + ' buildbot/buildbot_toolchain.sh mac', 'precise64-toolchain_x86': bash + ' buildbot/buildbot_toolchain.sh linux', # Toolchain newlib arm. 'win7-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', 'mac-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', 'precise64-toolchain_arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --buildbot', # BIONIC toolchain builders. 'precise64-toolchain_bionic': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build_bionic' ' --buildbot', # Pnacl toolchain builders. 'linux-armtools-x86_32': bash + ' buildbot/buildbot_toolchain_arm_trusted.sh', 'linux-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'linux-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'precise-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'precise-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', 'mac-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # TODO(robertm): Delete this once we are using win-pnacl-x86_64 'win-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # TODO(robertm): use this in favor or the misnamed win-pnacl-x86_32 'win-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --buildbot', # Pnacl toolchain testers 'linux-pnacl-x86_64-tests-x86_64': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot x86-64', 'linux-pnacl-x86_64-tests-x86_32': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot x86-32', 'linux-pnacl-x86_64-tests-arm': bash + ' buildbot/buildbot_pnacl_toolchain_tests.sh tc-test-bot arm', # MIPS toolchain buildbot. 'linux-pnacl-x86_32-tests-mips': bash + ' buildbot/buildbot_toolchain_mips_trusted.sh', # Toolchain trybots. 'nacl-toolchain-precise64-newlib': bash + ' buildbot/buildbot_toolchain.sh linux', 'nacl-toolchain-mac-newlib': bash + ' buildbot/buildbot_toolchain.sh mac', 'nacl-toolchain-win7-newlib': 'buildbot\\buildbot_toolchain_win.bat', 'nacl-toolchain-precise64-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-mac-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-win7-newlib-arm': python + ' buildbot/buildbot_toolchain_build.py' ' toolchain_build' ' --trybot', 'nacl-toolchain-precise64-glibc': bash + ' buildbot/buildbot_linux-glibc-makefile.sh', 'nacl-toolchain-mac-glibc': bash + ' buildbot/buildbot_mac-glibc-makefile.sh', 'nacl-toolchain-win7-glibc': 'buildbot\\buildbot_windows-glibc-makefile.bat', # Pnacl toolchain trybots. 'nacl-toolchain-linux-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-linux-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-linux-pnacl-mips': echo + ' "TODO(mseaborn)"', 'nacl-toolchain-precise-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-precise-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-precise-pnacl-mips': echo + ' "TODO(mseaborn)"', 'nacl-toolchain-mac-pnacl-x86_32': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', 'nacl-toolchain-win7-pnacl-x86_64': python + ' buildbot/buildbot_pnacl_toolchain.py --trybot', } special_for_arm = [ 'win7_64', 'win7-64', 'lucid-64', 'lucid64', 'precise-64', 'precise64' ] for platform in [ 'vista', 'win7', 'win8', 'win', 'mac10.6', 'mac10.7', 'mac10.8', 'lucid', 'precise'] + special_for_arm: if platform in special_for_arm: arch_variants = ['arm'] else: arch_variants = ['', '32', '64', 'arm'] for arch in arch_variants: arch_flags = '' real_arch = arch arch_part = '-' + arch # Disable GYP build for win32 bots and arm cross-builders. In this case # "win" means Windows XP, not Vista, Windows 7, etc. # # Building via GYP always builds all toolchains by default, but the win32 # XP pnacl builds are pathologically slow (e.g. ~38 seconds per compile on # the nacl-win32_glibc_opt trybot). There are other builders that test # Windows builds via gyp, so the reduced test coverage should be slight. if arch == 'arm' or (platform == 'win' and arch == '32'): arch_flags += ' --no-gyp' if arch == '': arch_part = '' real_arch = '32' # Test with Breakpad tools only on basic Linux builds. if sys.platform.startswith('linux'): arch_flags += ' --use-breakpad-tools' for mode in ['dbg', 'opt']: for libc in ['newlib', 'glibc']: # Buildbots. for bare in ['', '-bare']: name = platform + arch_part + bare + '-' + libc + '-' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) # Trybots for arch_sep in ['', '-', '_']: name = 'nacl-' + platform + arch_sep + arch + '_' + libc + '_' + mode assert name not in BOT_ASSIGNMENT, name BOT_ASSIGNMENT[name] = ( python + ' buildbot/buildbot_standard.py ' + mode + ' ' + real_arch + ' ' + libc + arch_flags) def EscapeJson(data): return '"' + json.dumps(data).replace('"', r'\"') + '"' def Main(): builder = os.environ.get('BUILDBOT_BUILDERNAME') build_number = os.environ.get('BUILDBOT_BUILDNUMBER') slave_type = os.environ.get('BUILDBOT_SLAVE_TYPE') cmd = BOT_ASSIGNMENT.get(builder) if not cmd: sys.stderr.write('ERROR - unset/invalid builder name\n') sys.exit(1) env = os.environ.copy() # Don't write out .pyc files because in cases in which files move around or # the PYTHONPATH / sys.path change, old .pyc files can be mistakenly used. # This avoids the need for admin changes on the bots in this case. env['PYTHONDONTWRITEBYTECODE'] = '1' # Use .boto file from home-dir instead of buildbot supplied one. if 'AWS_CREDENTIAL_FILE' in env: del env['AWS_CREDENTIAL_FILE'] env['BOTO_CONFIG'] = os.path.expanduser('~/.boto') env['GSUTIL'] = '/b/build/third_party/gsutil/gsutil' # When running from cygwin, we sometimes want to use a native python. # The native python will use the depot_tools version by invoking python.bat. if pynacl.platform.IsWindows(): env['NATIVE_PYTHON'] = 'python.bat' else: env['NATIVE_PYTHON'] = 'python' if sys.platform == 'win32': # If the temp directory is not on the same drive as the working directory, # there can be random failures when cleaning up temp directories, so use # a directory on the current drive. Use __file__ here instead of os.getcwd() # because toolchain_main picks its working directories relative to __file__ filedrive, _ = os.path.splitdrive(__file__) tempdrive, _ = os.path.splitdrive(env['TEMP']) if tempdrive != filedrive: env['TEMP'] = filedrive + '\\temp' env['TMP'] = env['TEMP'] if not os.path.exists(env['TEMP']): os.mkdir(env['TEMP']) # Run through runtest.py to get upload of perf data. build_properties = { 'buildername': builder, 'mastername': 'client.nacl', 'buildnumber': str(build_number), } factory_properties = { 'perf_id': builder, 'show_perf_results': True, 'step_name': 'naclperf', # Seems unused, but is required. 'test_name': 'naclperf', # Really "Test Suite" } # Locate the buildbot build directory by relative path, as it's absolute # location varies by platform and configuration. buildbot_build_dir = os.path.join(* [os.pardir] * 4) runtest = os.path.join(buildbot_build_dir, 'scripts', 'slave', 'runtest.py') # For builds with an actual build number, require that the script is present # (i.e. that we're run from an actual buildbot). if build_number is not None and not os.path.exists(runtest): raise Exception('runtest.py script not found at: %s\n' % runtest) cmd_exe = cmd.split(' ')[0] cmd_exe_ext = os.path.splitext(cmd_exe)[1] # Do not wrap these types of builds with runtest.py: # - tryjobs # - commands beginning with 'echo ' # - batch files # - debug builders if not (slave_type == 'Trybot' or cmd_exe == echo or cmd_exe_ext == '.bat' or '-dbg' in builder): # Perf dashboards are now generated by output scraping that occurs in the # script runtest.py, which lives in the buildbot repository. # Non-trybot builds should be run through runtest, allowing it to upload # perf data if relevant. cmd = ' '.join([ python, runtest, '--build-dir=src/out', '--results-url=https://chromeperf.appspot.com', '--annotate=graphing', '--no-xvfb', # We provide our own xvfb invocation. '--factory-properties', EscapeJson(factory_properties), '--build-properties', EscapeJson(build_properties), cmd, ]) print "%s runs: %s\n" % (builder, cmd) retcode = subprocess.call(cmd, env=env, shell=True) sys.exit(retcode) if __name__ == '__main__': Main()
wilsonianb/nacl_contracts
buildbot/buildbot_selector.py
Python
bsd-3-clause
16,846
from contextlib import contextmanager from _pytest.python import FixtureRequest import mock from mock import Mock import pyramid.testing from webob.multidict import MultiDict import pyramid_swagger import pyramid_swagger.tween import pytest import simplejson from pyramid.config import Configurator from pyramid.interfaces import IRoutesMapper from pyramid.registry import Registry from pyramid.response import Response from pyramid.urldispatch import RoutesMapper from webtest import AppError from .request_test import test_app from pyramid_swagger.exceptions import ResponseValidationError from pyramid_swagger.ingest import compile_swagger_schema from pyramid_swagger.ingest import get_resource_listing from pyramid_swagger.tween import validation_tween_factory class CustomResponseValidationException(Exception): pass class EnhancedDummyRequest(pyramid.testing.DummyRequest): """ pyramid.testing.DummyRequest doesn't support MultiDicts like the real pyramid.request.Request so this is the next best thing. """ def __init__(self, **kw): super(EnhancedDummyRequest, self).__init__(**kw) self.GET = MultiDict(self.GET) # Make sure content_type attr exists is not passed in via **kw self.content_type = getattr(self, 'content_type', None) @contextmanager def validation_context(request, response=None): try: yield except Exception: raise CustomResponseValidationException validation_ctx_path = 'tests.acceptance.response_test.validation_context' def get_registry(settings): registry = Registry('testing') config = Configurator(registry=registry) if getattr(registry, 'settings', None) is None: config._set_settings(settings) registry.registerUtility(RoutesMapper(), IRoutesMapper) config.commit() return registry def get_swagger_schema(schema_dir='tests/sample_schemas/good_app/'): return compile_swagger_schema( schema_dir, get_resource_listing(schema_dir, False) ) def _validate_against_tween(request, response=None, **overrides): """ Acceptance testing helper for testing the validation tween with Swagger 1.2 responses. :param request: pytest fixture :param response: standard fixture by default """ def handler(request): return response or Response() settings = dict({ 'pyramid_swagger.swagger_versions': ['1.2'], 'pyramid_swagger.enable_swagger_spec_validation': False, 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/'}, **overrides ) settings['pyramid_swagger.schema12'] = get_swagger_schema() settings['pyramid_swagger.schema20'] = None registry = get_registry(settings) # Let's make request validation a no-op so we can focus our tests. with mock.patch.object(pyramid_swagger.tween, 'validate_request'): validation_tween_factory(handler, registry)(request) def test_response_validation_enabled_by_default(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. If response validation # occurs, we'll fail it. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def test_500_when_response_is_missing_required_field(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "'logging_info' is a required property" in str(excinfo.value) def test_200_when_response_is_void_with_none_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response( body=simplejson.dumps(None), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_when_response_is_void_with_empty_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response(body='{}') _validate_against_tween(request, response=response) def test_500_when_response_arg_is_wrong_type(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) response = Response( body=simplejson.dumps({ 'raw_response': 1.0, 'logging_info': {'foo': 'bar'} }), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "1.0 is not of type 'string'" in str(excinfo.value) def test_500_for_bad_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{"enum_value": "bad_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert "is not one of ['good_enum_value']" in str(excinfo.value) def test_200_for_good_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{"enum_value": "good_enum_value"}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_for_normal_response_validation(): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_response_validation': True} ) response = app.post_json('/sample', {'foo': 'test', 'bar': 'test'}) assert response.status_code == 200 def test_200_skip_validation_for_excluded_path(): # FIXME(#64): This test is broken and doesn't check anything. app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.exclude_paths': [r'^/sample/?']} ) response = app.get( '/sample/path_arg1/resource', params={'required_arg': 'test'} ) assert response.status_code == 200 def test_app_error_if_path_not_in_spec_and_path_validation_disabled(): """If path missing and validation is disabled we want to let something else handle the error. TestApp throws an AppError, but Pyramid would throw a HTTPNotFound exception. """ with pytest.raises(AppError): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_path_validation': False} ) assert app.get('/this/path/doesnt/exist') def test_response_validation_context(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(CustomResponseValidationException): _validate_against_tween( request, response=response, **{'pyramid_swagger.validation_context_path': validation_ctx_path} )
prat0318/pyramid_swagger
tests/acceptance/response_test.py
Python
bsd-3-clause
8,642
// Benchpress: A collection of micro-benchmarks. var allResults = [ ]; // ----------------------------------------------------------------------------- // F r a m e w o r k // ----------------------------------------------------------------------------- function Benchmark(string, run) { this.string = string; this.run = run; } // Run each benchmark for two seconds and count number of iterations. function time(benchmark) { var elapsed = 0; var start = new Date(); for (var n = 0; elapsed < 2000; n++) { benchmark.run(); elapsed = new Date() - start; } var usec = (elapsed * 1000) / n; allResults.push(usec); print('Time (' + benchmark.string + '): ' + Math.floor(usec) + ' us.'); } function error(string) { print(string); } // ----------------------------------------------------------------------------- // L o o p // ----------------------------------------------------------------------------- function loop() { var sum = 0; for (var i = 0; i < 200; i++) { for (var j = 0; j < 100; j++) { sum++; } } if (sum != 20000) error("Wrong result: " + sum + " should be: 20000"); } var Loop = new Benchmark("Loop", loop); // ----------------------------------------------------------------------------- // M a i n // ----------------------------------------------------------------------------- time(Loop); var logMean = 0; for (var i = 0; i < allResults.length; i++) logMean += Math.log(allResults[i]); logMean /= allResults.length; print("Geometric mean: " + Math.round(Math.pow(Math.E, logMean)) + " us.");
daejunpark/jsaf
benchmarks/v8_v1/units/loop.js
JavaScript
bsd-3-clause
1,571
#!/usr/bin/perl # start in the directory with all the files $argc = @ARGV; # get the number of arguments if ($argc == 0 ) { print "msl_Vic2ODL-PDDS-jpg.pl dir multi vic2odl_xsl odl2pds_xsl max \n"; print "prints a set of transcoder (jConvertIIO) commands to test .DAT and .VIC files \n"; print "Output goes to STDOUT. Redirect to a file to keep the output as a script or arg file.\n"; print "There are no command switches, just put the values on the command line. Order is important. \n"; print " dir - the input directory \n"; print " multi - {multi/single] create standalone java commands or a set to be executed from a file \n"; print "vic2odl_xsl - full path to the xsl script to convert vicar files to ODL (VicarToPDSmsl_Blob_ODL2.xsl)\n"; print "odl2pds_xsl - full path to the xsl script to convert ODL files to PDS (PDSToPDSmsl_Blob_ODL2PDS_4.xsl)\n"; print "max - the maximum number fo files to process. \n"; print " (Optional argument) Useful to limit the number of comands generated for a large input directory\n"; print " If the multi option is used, redirect the output to a file. Use this file as the input file for the \n"; print " command: java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt \n"; } $outdir = $ARGV[0]; $multi = $ARGV[1]; $vic2odl_xsl = $ARGV[2]; $odl2pds_xsl = $ARGV[3]; if ($argc > 4) { $max = $ARGV[4]; # maximum number of files used } else { $max = 1000; } # cd /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/clean_data # # cp *.VIC ../out_multi # cp *.VIC ../out_single # cd /Volumes/bigraid/MSL_data/Sample_EDRS/ # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 multi 11 > multi11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11 single 11 > single11.txt # ~/bin/msl_Vic2ODL-PDS-jpg.pl /Volumes/bigraid/MSL_data/Sample_EDRS/5-9-2011/out_single single 1 > single1.txt # capture output to a file. execute each # # sh single1.txt # sh single.txt # # java -Xmx256m jpl.mipl.io.jConvertIIO arg=multi.txt # time sh single.txt # # time java -Xmx256m jpl.mipl.io.jConvertIIO ARGFILE=multi.txt # 152.015u 30.504s 3:06.07 98.0% 0+0k 236+326io 918pf+0w # # time sh single100.txt # 617.869u 87.299s 15:35.90 75.3% 0+0k 1+1171io 3267pf+0w chdir $outdir; print "#!/bin/sh \n"; $cwd = `pwd`; print "# $cwd \n"; # $debug = " debug=true xml=true "; $debug = " "; if ($multi =~ /^m/) { $java = ""; } else { $java = "java -Xmx256m jpl.mipl.io.jConvertIIO "; } $ct = 0; while (<*.DAT>) { $file = $_; ($base,$ext) = split(/[.]/,$file); $pds = sprintf ( "%s.%s", $base, "LBL"); # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.DAT out=/Volumes/bigraid/MSL_data/Sample_EDRS/test-5-11-11/CC0_353400938EIN_F0000000001036288M1.lbl PDS_DETACHED_ONLY=true format=PDS PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $file, $outdir, $pds, $debug, $xsl); print "$cmd \n"; } $ct=0; while (<*.VIC>) { $file = $_; $vic = $file; ($base,$ext) = split(/[.]/,$file); $odl = sprintf ( "%s.%s", $base, "IMG"); $pds = sprintf ( "%s.%s", $base, "LBL"); $vic_jpg = sprintf ( "%s_vic.%s", $base, "jpg"); $odl_tif = sprintf ( "%s_odl.%s", $base, "tif"); # VIC to ODL # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/out_ODL/RRA_353184709EDR_T0000000001036288M1.ODL format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL1.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/VicarToPDSmsl_Blob_ODL2.xsl"; $xsl = $vic2odl_xsl; $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS ADD_BLOB=true RI EMBED PDS_LABEL_TYPE=ODL3 xsl=%s ", $java, $outdir, $vic, $outdir, $odl, $debug, $xsl); print "$cmd \n"; # system($cmd); # $cmd = sprintf("~/bin/getPdsLabel.pl %s/%s ", $outdir, $odl); # print "$cmd \n"; # ODL - PDS detached # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.DAT out=/Users/slevoe/MSL/Sample_EDRS/out-ODL-PDS_Libs/CC0_353400938EIN_F0000000001036288M1.PDS PDS_FILENAME_IN_LABEL=true xml=true debug=true PDS_DETACHED_ONLY=true format=pds PDS_LABEL_TYPE=PDS3 xsl=/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_2.xsl $xsl = "/eclipse_3.6_workspace/MSL_xsl/PDSToPDSmsl_Blob_ODL2PDS_4.xsl"; $xsl = $odl2pds_xsl; # other options: RI PDS_FILENAME_IN_LABEL=true $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=PDS PDS_DETACHED_ONLY=true PDS_LABEL_TYPE=PDS3 xsl=%s ", $java, $outdir, $odl, $outdir, $pds, $debug, $xsl); print "$cmd \n"; # ODL to tif # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.ODL out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg 2RGB format=jpg RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=tif RI OFORM=byte ", $java, $outdir, $odl, $outdir, $odl_tif, $debug); print "$cmd \n"; # Vicar to jpg # java -Xmx256m jpl.mipl.io.jConvertIIO inp=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.VIC out=/Users/slevoe/MSL/Sample_EDRS/RRA_353184709EDR_T0000000001036288M1.jpg format=tif RI OFORM=byte $cmd = sprintf("%s inp=%s/%s out=%s/%s %s format=jpg RI 2RGB OFORM=byte ", $java, $outdir, $vic, $outdir, $vic_jpg, $debug); print "$cmd \n\n"; $ct++; if($ct >= $max) { exit; } } #
marrocamp/nasa-VICAR
vos/java/jpl/mipl/io/xsl/test/msl_Vic2ODL-PDS-jpg.pl
Perl
bsd-3-clause
5,855
/* copyright(C) 2002 H.Kawai (under KL-01). */ #include <stdio.h> #include <stdlib.h> int GO_fputc(int c, GO_FILE *stream) { if (stream->p >= stream->p1) abort(); *stream->p++ = c; /* GOL_debuglog(1, &c); */ return (unsigned char) c; }
Oss9935/MakitOS
osproj/omake/tolsrc/go_0023s/go_lib/fputc.c
C
bsd-3-clause
244
import ghcnpy # Provide introduction ghcnpy.intro() # Print Latest Version ghcnpy.get_ghcnd_version() # Testing Search Capabilities print("\nTESTING SEARCH CAPABILITIES") ghcnpy.find_station("Asheville") # Testing Search Capabilities print("\nTESTING PULL CAPABILITIES") outfile=ghcnpy.get_data_station("USW00003812") print(outfile," has been downloaded")
jjrennie/GHCNpy
test.py
Python
bsd-3-clause
360
{% extends 'magicflatpages/base_content.html' %} {% load floppyforms %} {% block js_top %} {{ block.super }} {{ form.media }} {% endblock %} {% block navbar %} {% endblock navbar %} {% block footer_area %} {% endblock footer_area %} {% block content %} <div class="popup-content"> <div class="row"> <div class="col-sm-2"> <div class="side-fix-menus"> <ul class="nav nav-pills nav-stacked" id="nav-elements"> <li role="presentation" class="active"> <a href="#" id="goto-title">Page<br/><i class="fa fa-minus"></i></a> </li> </ul> </div> </div> <div class="col-lg-9"> <h1><small>Page {{ object.title }} details</h1> <form method='post' enctype="multipart/form-data">{% csrf_token %} {{ form }} <div class="bottom-fix-menu" align="center"> <h1> <input type="submit" class="btn btn-lg btn-success" value="Save" /> <a href="{% url 'magiccontent.windows_close' %}?dont_reload=1" class="btn btn-lg btn-danger" role="button" >Cancel</a> </h1> </div> </form> <br/><br/><br/><br/> </div> </div> </div> {% endblock content %} {% block post_content %}{% endblock post_content %} {% block extrajs %} <script type="text/javascript"> // hide the picture filters when there is no picture $(document).ready(function(){ $("#id_url").prop('readonly', true); }); </script> {% endblock extrajs %}
DjenieLabs/django-magicflatpages
magicflatpages/templates/flatpages/page_form.html
HTML
bsd-3-clause
1,501
// xml_do_read.h see license.txt for copyright and terms of use #ifndef XML_DO_READ_H #define XML_DO_READ_H class TranslationUnit; class StringTable; TranslationUnit *xmlDoRead(StringTable &strTable, char const *inputFname); #endif // XML_DO_READ_H
angavrilov/olmar
elsa/xml_do_read.h
C
bsd-3-clause
261
'use strict'; myApp.controller('editProfileController', ['$scope', '$state', 'loadingMaskService', 'CONSTANTS', '$uibModal', '$log', '$rootScope', '$http', function ($scope, $state, loadingMaskService, CONSTANTS, $uibModal, $log, $rootScope, $http) { var userInfo = JSON.parse(localStorage.getItem(CONSTANTS.LOCAL_STORAGE_KEY)); $scope.email = userInfo.email; $scope.date = userInfo.birthDate; $scope.firstName = userInfo.firstName; $scope.lastName = userInfo.lastName; $scope.relations = userInfo.relations; $scope.relationOptions = ['Мама', 'Отец', 'Брат']; $scope.submit = function () { if ($scope.editProfileForm.$valid && $scope.editProfileForm.$dirty) { // if form is valid var userInfo = { email: $scope.email, birthDate: $scope.date, firstName: $scope.firstName, lastName: $scope.lastName, relations: $scope.relations }; $http({ method: 'POST', url: '/editRelation', data: { email: userInfo.email, relations: $scope.relations } }).then(function successCallback(response) { localStorage.setItem(CONSTANTS.LOCAL_STORAGE_KEY, JSON.stringify(userInfo)); loadingMaskService.sendRequest(); $state.go('mainPageState.userProfile'); }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }; $rootScope.$on('relationsUpdated', function(event, relations){ $scope.relations = relations; }); $rootScope.$on('relationRemoved', function(event, relations){ $scope.relations = relations; }); $scope.removeRelation = function(index) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/removeRelationConfirm.tpl.html', controller: 'removeRelationController', resolve: { index: function () { return index } } }); } $scope.open = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/addARelation.tpl.html', controller: 'addRelationController' }); }; }]);
yslepianok/analysis_site
views/tests/app/pages/src/editProfilePage/src/editProfileController.js
JavaScript
bsd-3-clause
2,590
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Service * @subpackage StrikeIron * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Service\StrikeIron; use SoapHeader, SoapClient; /** * @category Zend * @package Zend_Service * @subpackage StrikeIron * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Base { /** * Configuration options * @param array */ protected $options = array( 'username' => null, 'password' => null, 'client' => null, 'options' => null, 'headers' => null, 'wsdl' => null, ); /** * Output headers returned by the last call to SOAPClient->_soapCall() * @param array */ protected $outputHeaders = array(); /** * Class constructor * * @param array $options Key/value pair options * @throws Exception\RuntimeException if soap extension is not loaded */ public function __construct($options = array()) { if (!extension_loaded('soap')) { throw new Exception\RuntimeException('SOAP extension is not enabled'); } $this->options = array_merge($this->options, $options); $this->initSoapHeaders(); $this->initSoapClient(); } /** * Proxy method calls to the SOAPClient instance, transforming method * calls and responses for convenience. * * @param string $method Method name * @param array $params Parameters for method * @return mixed Result * @throws Exception\RuntimeException if error occurs during soap call */ public function __call($method, $params) { // prepare method name and parameters for soap call list($method, $params) = $this->transformCall($method, $params); $params = isset($params[0]) ? array($params[0]) : array(); // make soap call, capturing the result and output headers try { $result = $this->options['client']->__soapCall( $method, $params, $this->options['options'], $this->options['headers'], $this->outputHeaders ); } catch (\Exception $e) { $message = get_class($e) . ': ' . $e->getMessage(); throw new Exception\RuntimeException($message, $e->getCode(), $e); } // transform/decorate the result and return it $result = $this->transformResult($result, $method, $params); return $result; } /** * Initialize the SOAPClient instance * * @return void */ protected function initSoapClient() { if (!isset($this->options['options'])) { $this->options['options'] = array(); } if (!isset($this->options['client'])) { $this->options['client'] = new SoapClient( $this->options['wsdl'], $this->options['options'] ); } } /** * Initialize the headers to pass to SOAPClient->_soapCall() * * @return void * @throws Exception\RuntimeException if invalid headers encountered */ protected function initSoapHeaders() { // validate headers and check if LicenseInfo was given $foundLicenseInfo = false; if (isset($this->options['headers'])) { if (! is_array($this->options['headers'])) { $this->options['headers'] = array($this->options['headers']); } foreach ($this->options['headers'] as $header) { if (!$header instanceof SoapHeader) { throw new Exception\RuntimeException('Header must be instance of SoapHeader'); } elseif ($header->name == 'LicenseInfo') { $foundLicenseInfo = true; break; } } } else { $this->options['headers'] = array(); } // add default LicenseInfo header if a custom one was not supplied if (!$foundLicenseInfo) { $this->options['headers'][] = new SoapHeader( 'http://ws.strikeiron.com', 'LicenseInfo', array( 'RegisteredUser' => array( 'UserID' => $this->options['username'], 'Password' => $this->options['password'], ), ) ); } } /** * Transform a method name or method parameters before sending them * to the remote service. This can be useful for inflection or other * transforms to give the method call a more PHP-like interface. * * @see __call() * @param string $method Method name called from PHP * @param mixed $param Parameters passed from PHP * @return array [$method, $params] for SOAPClient->_soapCall() */ protected function transformCall($method, $params) { return array(ucfirst($method), $params); } /** * Transform the result returned from a method before returning * it to the PHP caller. This can be useful for transforming * the SOAPClient returned result to be more PHP-like. * * The $method name and $params passed to the method are provided to * allow decisions to be made about how to transform the result based * on what was originally called. * * @see __call() * @param $result Raw result returned from SOAPClient_>__soapCall() * @param $method Method name that was passed to SOAPClient->_soapCall() * @param $params Method parameters that were passed to SOAPClient->_soapCall() * @return mixed Transformed result */ protected function transformResult($result, $method, $params) { $resultObjectName = "{$method}Result"; if (isset($result->$resultObjectName)) { $result = $result->$resultObjectName; } if (is_object($result)) { $result = new Decorator($result, $resultObjectName); } return $result; } /** * Get the WSDL URL for this service. * * @return string */ public function getWsdl() { return $this->options['wsdl']; } /** * Get the SOAP Client instance for this service. */ public function getSoapClient() { return $this->options['client']; } /** * Get the StrikeIron output headers returned with the last method response. * * @return array */ public function getLastOutputHeaders() { return $this->outputHeaders; } /** * Get the StrikeIron subscription information for this service. * If any service method was recently called, the subscription info * should have been returned in the SOAP headers so it is cached * and returned from the cache. Otherwise, the getRemainingHits() * method is called as a dummy to get the subscription info headers. * * @param boolean $now Force a call to getRemainingHits instead of cache? * @param string $queryMethod Method that will cause SubscriptionInfo header to be sent * @return Decorator Decorated subscription info * @throws Exception\RuntimeException if no subscription information headers present */ public function getSubscriptionInfo($now = false, $queryMethod = 'GetRemainingHits') { if ($now || empty($this->outputHeaders['SubscriptionInfo'])) { $this->$queryMethod(); } // capture subscription info if returned in output headers if (isset($this->outputHeaders['SubscriptionInfo'])) { $info = (object)$this->outputHeaders['SubscriptionInfo']; $subscriptionInfo = new Decorator($info, 'SubscriptionInfo'); } else { $msg = 'No SubscriptionInfo header found in last output headers'; throw new Exception\RuntimeException($msg); } return $subscriptionInfo; } }
dineshkummarc/zf2
library/Zend/Service/StrikeIron/Base.php
PHP
bsd-3-clause
8,807
<?php $deleteStyle = isset($this->existing) ? 'inline' : 'none' ?> <?php $addStyle = $deleteStyle == 'inline' ? 'none' : 'inline' ?> <div id="watch-controls"> </div> <h2><?php $this->o($this->notes[0]->title);?></h2> <?php $note = null; ?> <?php foreach ($this->notes as $note): ?> <div class="note"> <div class="note-header"> <form class="inline right" method="post" action="<?php echo build_url('note', 'delete')?>" onsubmit="return confirm('Are you sure?')"> <input type="hidden" value="<?php echo $note->id?>" name="id" /> <input title="Delete" type="image" src="<?php echo resource('images/delete.png')?>" /> </form> <h4><?php $this->o($note->title)?></h4> <span class="note-by">By <?php $this->o($note->userid.' on '.$note->created)?></span> </div> <div class="note-body"><?php $this->bbCode($note->note);?></div> </div> <?php endforeach; ?> <div class="note"> <form method="post" action="<?php echo build_url('note', 'add');?>"> <input type="hidden" value="<?php echo $note->attachedtotype?>" name="attachedtotype"/> <input type="hidden" value="<?php echo $note->attachedtoid?>" name="attachedtoid"/> <input type="hidden" value="<?php echo za()->getUser()->getUsername()?>" name="userid"/> <p> <label for="note-title">Title:</label> <input class="input" type="text" name="title" id="note-title" value="Re: <?php $this->o(str_replace('Re: ', '', $note->title))?>" /> </p> <p> <label for="note-note">Note:</label> <textarea name="note" rows="5" cols="45" id="note-note"></textarea> </p> <p> <input type="submit" class="abutton" value="Add Note" /> <a class="abutton" style="display: <?php echo $deleteStyle?>;" id="delete-watch" href="#" onclick="$.get('<?php echo build_url('note', 'deletewatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#delete-watch').hide();$('#add-watch').show(); }); return false;">Remove Watch</a> <a class="abutton" style="display: <?php echo $addStyle?>;" id="add-watch" href="#" onclick="$.get('<?php echo build_url('note', 'addwatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#add-watch').hide();$('#delete-watch').show(); }); return false;">Add Watch</a> </p> </form> </div>
nyeholt/relapse
views/note/thread-view.php
PHP
bsd-3-clause
2,359
/* * Copyright (c) 2011 Yahoo! Inc. All rights reserved. */ YUI.add('master', function(Y, NAME) { /** * The master module. * * @module master */ var DIMENSIONS = { device: 'smartphone', region: 'CA', skin : 'grey' }; /** * Constructor for the Controller class. * * @class Controller * @constructor */ Y.mojito.controllers[NAME] = { init: function(config) { this.config = config; }, /** * Method corresponding to the 'index' action. * * @param ac {Object} The ActionContext that provides access * to the Mojito API. */ index: function(ac) { var dims = ac.params.getFromUrl(), self = this, config = { view: 'index', children: { primary: { type: 'primary', action: 'index' }, secondary: { type: 'secondary', action: 'index' } } }; ac.composite.execute(config, function (data, meta) { data.buttons = self.createButtons(ac, dims); ac.done(data, meta); }); }, createButtons: function (ac, dims) { var buttons = [], className, label, url; Y.each(Y.Object.keys(DIMENSIONS), function (dim) { var params = Y.merge({}, dims); className = 'nav nav-' + dim + (dims[dim] ? ' active' : ''); params[dim] ? delete params[dim] : params[dim] = DIMENSIONS[dim]; url = ac.url.make('htmlframe', 'index', null, 'GET', params); label = dim.substring(0,1).toUpperCase() + dim.substring(1); buttons.push('<a href="'+url+'" class="'+className+'">'+label+'</a>'); }); return buttons.join('\n'); } }; }, '0.0.1', {requires: ['mojito', 'mojito-assets-addon']});
triptych/shaker
examples/demo/mojits/master/controller.common.js
JavaScript
bsd-3-clause
2,296
/** * \file PancakeNode.hpp * * * * \author eaburns * \date 18-01-2010 */ #include "search/Node.hpp" #include "pancake/PancakeTypes.hpp" #include "pancake/PancakeState.hpp" #if !defined(_PANCAKE_NODE_H_) #define _PANCAKE_NODE_H_ typedef Node<PancakeState14, PancakeCost> PancakeNode14; #endif // !_PANCAKE_NODE_H_
bradlarsen/switchback
src/pancake/PancakeNode.hpp
C++
bsd-3-clause
326
//----------------------------------------------------------------------------- //Cortex //Copyright (c) 2010-2015, Joshua Scoggins //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 Cortex 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 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 Joshua Scoggins 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. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.IO; using System.Linq; namespace Cortex.Operation { public class GraphVizLink : IGraphLink { private int from, to; private string label; public int From { get { return from; } } public int To { get { return to; } } public string Label { get { return label; } } public GraphVizLink(int from, int to, string label) { this.from = from; this.to = to; this.label = label; } public override string ToString() { if(label.Equals(string.Empty)) return string.Format("node{0} -> node{1};", From, To); else return string.Format("node{0} -> node{1} {2};", From, To, Label); } } public class GraphVizGraphBuilder : GraphBuilder<GraphVizLink> { public GraphVizGraphBuilder() : base() { } public override void Link(int i0, int i1, string label) { Add(new GraphVizLink(i0,i1,label)); } public override string ToString(string graphName) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("digraph {0}\n",graphName); sb.AppendLine("{"); foreach(var v in this) sb.AppendLine(v.ToString()); sb.AppendLine("}"); return sb.ToString(); } } }
DrItanium/Cortex
Operation/GraphVizSpecificBuilder.cs
C#
bsd-3-clause
3,083
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPluginActivator.h" #include "DicomEventHandler.h" #include <service/event/ctkEventConstants.h> #include <ctkDictionary.h> #include <mitkLogMacros.h> #include <mitkDataNode.h> #include <mitkIDataStorageService.h> #include <service/event/ctkEventAdmin.h> #include <ctkServiceReference.h> #include <mitkRenderingManager.h> #include <QVector> #include "mitkImage.h" #include <mitkContourModelSet.h> #include <mitkDICOMFileReaderSelector.h> #include <mitkDICOMDCMTKTagScanner.h> #include <mitkDICOMEnums.h> #include <mitkDICOMTagsOfInterestHelper.h> #include <mitkDICOMProperty.h> #include <mitkPropertyNameHelper.h> #include "mitkBaseDICOMReaderService.h" #include <mitkRTDoseReaderService.h> #include <mitkRTPlanReaderService.h> #include <mitkRTStructureSetReaderService.h> #include <mitkRTConstants.h> #include <mitkIsoDoseLevelCollections.h> #include <mitkIsoDoseLevelSetProperty.h> #include <mitkIsoDoseLevelVectorProperty.h> #include <mitkDoseImageVtkMapper2D.h> #include <mitkRTUIConstants.h> #include <mitkIsoLevelsGenerator.h> #include <mitkDoseNodeHelper.h> #include <vtkSmartPointer.h> #include <vtkMath.h> #include <mitkTransferFunction.h> #include <mitkTransferFunctionProperty.h> #include <mitkRenderingModeProperty.h> #include <mitkLocaleSwitch.h> #include <mitkIOUtil.h> #include <berryIPreferencesService.h> #include <berryIPreferences.h> #include <berryPlatform.h> #include <ImporterUtil.h> DicomEventHandler::DicomEventHandler() { } DicomEventHandler::~DicomEventHandler() { } void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent) { QStringList listOfFilesForSeries; listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList(); if (!listOfFilesForSeries.isEmpty()) { //for rt data, if the modality tag isn't defined or is "CT" the image is handled like before if(ctkEvent.containsProperty("Modality") && (ctkEvent.getProperty("Modality").toString().compare("RTDOSE",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTSTRUCT",Qt::CaseInsensitive) == 0 || ctkEvent.getProperty("Modality").toString().compare("RTPLAN", Qt::CaseInsensitive) == 0)) { QString modality = ctkEvent.getProperty("Modality").toString(); if(modality.compare("RTDOSE",Qt::CaseInsensitive) == 0) { auto doseReader = mitk::RTDoseReaderService(); doseReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = doseReader.Read(); if (!readerOutput.empty()){ mitk::Image::Pointer doseImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer doseImageNode = mitk::DataNode::New(); doseImageNode->SetData(doseImage); doseImageNode->SetName("RTDose"); if (doseImage != nullptr) { std::string sopUID; if (mitk::GetBackwardsCompatibleDICOMProperty(0x0008, 0x0016, "dicomseriesreader.SOPClassUID", doseImage->GetPropertyList(), sopUID)) { doseImageNode->SetName(sopUID); }; berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str()); if (prefNode.IsNull()) { mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode->ToString().toStdString(); } //set some specific colorwash and isoline properties bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(), true); //Set reference dose property double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE); mitk::ConfigureNodeAsDoseNode(doseImageNode, mitk::GenerateIsoLevels_Virtuos(), referenceDose, showColorWashGlobal); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(doseImageNode); mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } }//END DOSE } else if(modality.compare("RTSTRUCT",Qt::CaseInsensitive) == 0) { auto structReader = mitk::RTStructureSetReaderService(); structReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = structReader.Read(); if (readerOutput.empty()){ MITK_ERROR << "No structure sets were created" << endl; } else { std::vector<mitk::DataNode::Pointer> modelVector; ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); for (const auto& aStruct : readerOutput){ mitk::ContourModelSet::Pointer countourModelSet = dynamic_cast<mitk::ContourModelSet*>(aStruct.GetPointer()); mitk::DataNode::Pointer structNode = mitk::DataNode::New(); structNode->SetData(countourModelSet); structNode->SetProperty("name", aStruct->GetProperty("name")); structNode->SetProperty("color", aStruct->GetProperty("contour.color")); structNode->SetProperty("contour.color", aStruct->GetProperty("contour.color")); structNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2"))); structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3"))); dataStorage->Add(structNode); } mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage); } } else if (modality.compare("RTPLAN", Qt::CaseInsensitive) == 0) { auto planReader = mitk::RTPlanReaderService(); planReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front())); std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = planReader.Read(); if (!readerOutput.empty()){ //there is no image, only the properties are interesting mitk::Image::Pointer planDummyImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer()); mitk::DataNode::Pointer planImageNode = mitk::DataNode::New(); planImageNode->SetData(planDummyImage); planImageNode->SetName("RTPlan"); ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); dataStorage->Add(planImageNode); } } } else { mitk::StringList seriesToLoad; QStringListIterator it(listOfFilesForSeries); while (it.hasNext()) { seriesToLoad.push_back(ImporterUtil::getUTF8String(it.next())); } //Get Reference for default data storage. ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>(); mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference); mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage(); std::vector<mitk::BaseData::Pointer> baseDatas = mitk::IOUtil::Load(seriesToLoad.front()); for (const auto &data : baseDatas) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(data); std::string nodeName = mitk::DataNode::NO_NAME_VALUE(); auto nameDataProp = data->GetProperty("name"); if (nameDataProp.IsNotNull()) { //if data has a name property set by reader, use this name nodeName = nameDataProp->GetValueAsString(); } else { //reader didn't specify a name, generate one. nodeName = mitk::GenerateNameFromDICOMProperties(node); } node->SetName(nodeName); dataStorage->Add(node); } } } else { MITK_INFO << "There are no files for the current series"; } } void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& /*ctkEvent*/) { } void DicomEventHandler::SubscribeSlots() { ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>(); if (ref) { ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref); ctkDictionary properties; properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD"; eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties); properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED"; eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties); } }
fmilano/mitk
Plugins/org.mitk.gui.qt.dicom/src/internal/DicomEventHandler.cpp
C++
bsd-3-clause
11,194
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="ApiGen 2.8.0" /> <meta name="robots" content="noindex" /> <title>File widgets/fineuploader/WhFineUploader.php | YiiWheels</title> <script type="text/javascript" src="resources/combined.js?1965618976"></script> <script type="text/javascript" src="elementlist.js?53054354"></script> <link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?260161822" /> <link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2015443609" /> </head> <body> <div id="navigation" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a href="index.html" class="brand">YiiWheels</a> <div class="nav-collapse"> <ul class="nav"> <li> <a href="package-YiiWheels.widgets.fileuploader.html" title="Summary of YiiWheels\widgets\fileuploader"><span>Package</span></a> </li> <li> <a href="class-WhFineUploader.html" title="Summary of WhFineUploader"><span>Class</span></a> </li> <li class="divider-vertical"></li> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> </div> </div> </div> </div> <div id="left"> <div id="menu"> <form id="search" class="form-search"> <input type="hidden" name="cx" value="" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" class="search-query" placeholder="Search" /> </form> <div id="groups"> <h3>Packages</h3> <ul> <li><a href="package-None.html">None</a> </li> <li><a href="package-yiiwheels.html">yiiwheels<span></span></a> <ul> <li><a href="package-yiiwheels.behaviors.html">behaviors</a> </li> <li><a href="package-yiiwheels.widgets.html">widgets</a> </li> <li class="active"><a href="package-YiiWheels.widgets.html">widgets<span></span></a> <ul> <li><a href="package-YiiWheels.widgets.ace.html">ace</a> </li> <li><a href="package-YiiWheels.widgets.box.html">box</a> </li> <li><a href="package-YiiWheels.widgets.datepicker.html">datepicker</a> </li> <li><a href="package-YiiWheels.widgets.daterangepicker.html">daterangepicker</a> </li> <li><a href="package-YiiWheels.widgets.datetimepicker.html">datetimepicker</a> </li> <li><a href="package-YiiWheels.widgets.detail.html">detail</a> </li> <li><a href="package-YiiWheels.widgets.fileupload.html">fileupload</a> </li> <li class="active"><a href="package-YiiWheels.widgets.fileuploader.html">fileuploader</a> </li> <li><a href="package-YiiWheels.widgets.gallery.html">gallery</a> </li> <li><a href="package-YiiWheels.widgets.google.html">google</a> </li> <li><a href="package-YiiWheels.widgets.grid.html">grid<span></span></a> <ul> <li><a href="package-yiiwheels.widgets.grid.behaviors.html">behaviors</a> </li> <li><a href="package-YiiWheels.widgets.grid.operations.html">operations</a> </li> </ul></li> <li><a href="package-YiiWheels.widgets.highcharts.html">highcharts</a> </li> <li><a href="package-YiiWheels.widgets.maskInput.html">maskInput</a> </li> <li><a href="package-YiiWheels.widgets.maskmoney.html">maskmoney</a> </li> <li><a href="package-YiiWheels.widgets.modal.html">modal</a> </li> <li><a href="package-YiiWheels.widgets.multiselect.html">multiselect</a> </li> <li><a href="package-YiiWheels.widgets.rangeslider.html">rangeslider</a> </li> <li><a href="package-YiiWheels.widgets.redactor.html">redactor</a> </li> <li><a href="package-YiiWheels.widgets.select2.html">select2</a> </li> <li><a href="package-YiiWheels.widgets.sparklines.html">sparklines</a> </li> <li><a href="package-YiiWheels.widgets.switch.html">switch</a> </li> <li><a href="package-YiiWheels.widgets.timeago.html">timeago</a> </li> <li><a href="package-YiiWheels.widgets.timepicker.html">timepicker</a> </li> <li><a href="package-YiiWheels.widgets.toggle.html">toggle</a> </li> <li><a href="package-YiiWheels.widgets.typeahead.html">typeahead</a> </li> </ul></li></ul></li> </ul> </div> <div id="elements"> <h3>Classes</h3> <ul> <li class="active"><a href="class-WhFineUploader.html">WhFineUploader</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <pre id="source"><code><span id="1" class="l"><a class="l" href="#1"> 1 </a><span class="xlang">&lt;?php</span> </span><span id="2" class="l"><a class="l" href="#2"> 2 </a><span class="php-comment">/** </span></span><span id="3" class="l"><a class="l" href="#3"> 3 </a><span class="php-comment"> * WhFineUploader widget class </span></span><span id="4" class="l"><a class="l" href="#4"> 4 </a><span class="php-comment"> * Inspired by https://github.com/anggiaj/EFineUploader </span></span><span id="5" class="l"><a class="l" href="#5"> 5 </a><span class="php-comment"> * @author Antonio Ramirez &lt;[email protected]&gt; </span></span><span id="6" class="l"><a class="l" href="#6"> 6 </a><span class="php-comment"> * @copyright Copyright &amp;copy; 2amigos.us 2013- </span></span><span id="7" class="l"><a class="l" href="#7"> 7 </a><span class="php-comment"> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License </span></span><span id="8" class="l"><a class="l" href="#8"> 8 </a><span class="php-comment"> * @package YiiWheels.widgets.fileuploader </span></span><span id="9" class="l"><a class="l" href="#9"> 9 </a><span class="php-comment"> * @uses YiiStrap.helpers.TbArray </span></span><span id="10" class="l"><a class="l" href="#10"> 10 </a><span class="php-comment"> */</span> </span><span id="11" class="l"><a class="l" href="#11"> 11 </a>Yii::import(<span class="php-quote">'bootstrap.helpers.TbArray'</span>); </span><span id="12" class="l"><a class="l" href="#12"> 12 </a> </span><span id="13" class="l"><a class="l" href="#13"> 13 </a><span class="php-keyword1">class</span> <a id="WhFineUploader" href="#WhFineUploader">WhFineUploader</a> <span class="php-keyword1">extends</span> CInputWidget </span><span id="14" class="l"><a class="l" href="#14"> 14 </a>{ </span><span id="15" class="l"><a class="l" href="#15"> 15 </a> <span class="php-comment">/** </span></span><span id="16" class="l"><a class="l" href="#16"> 16 </a><span class="php-comment"> * @var string upload action url </span></span><span id="17" class="l"><a class="l" href="#17"> 17 </a><span class="php-comment"> */</span> </span><span id="18" class="l"><a class="l" href="#18"> 18 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$uploadAction" href="#$uploadAction">$uploadAction</a></span>; </span><span id="19" class="l"><a class="l" href="#19"> 19 </a> </span><span id="20" class="l"><a class="l" href="#20"> 20 </a> <span class="php-comment">/** </span></span><span id="21" class="l"><a class="l" href="#21"> 21 </a><span class="php-comment"> * @var string the HTML tag to render the uploader to </span></span><span id="22" class="l"><a class="l" href="#22"> 22 </a><span class="php-comment"> */</span> </span><span id="23" class="l"><a class="l" href="#23"> 23 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$tagName" href="#$tagName">$tagName</a></span> = <span class="php-quote">'div'</span>; </span><span id="24" class="l"><a class="l" href="#24"> 24 </a> </span><span id="25" class="l"><a class="l" href="#25"> 25 </a> <span class="php-comment">/** </span></span><span id="26" class="l"><a class="l" href="#26"> 26 </a><span class="php-comment"> * @var string text to display if javascript is disabled </span></span><span id="27" class="l"><a class="l" href="#27"> 27 </a><span class="php-comment"> */</span> </span><span id="28" class="l"><a class="l" href="#28"> 28 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$noScriptText" href="#$noScriptText">$noScriptText</a></span>; </span><span id="29" class="l"><a class="l" href="#29"> 29 </a> </span><span id="30" class="l"><a class="l" href="#30"> 30 </a> <span class="php-comment">/** </span></span><span id="31" class="l"><a class="l" href="#31"> 31 </a><span class="php-comment"> * @var array the plugin options </span></span><span id="32" class="l"><a class="l" href="#32"> 32 </a><span class="php-comment"> */</span> </span><span id="33" class="l"><a class="l" href="#33"> 33 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$pluginOptions" href="#$pluginOptions">$pluginOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="34" class="l"><a class="l" href="#34"> 34 </a> </span><span id="35" class="l"><a class="l" href="#35"> 35 </a> <span class="php-comment">/** </span></span><span id="36" class="l"><a class="l" href="#36"> 36 </a><span class="php-comment"> * @var array the events </span></span><span id="37" class="l"><a class="l" href="#37"> 37 </a><span class="php-comment"> */</span> </span><span id="38" class="l"><a class="l" href="#38"> 38 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$events" href="#$events">$events</a></span> = <span class="php-keyword1">array</span>(); </span><span id="39" class="l"><a class="l" href="#39"> 39 </a> </span><span id="40" class="l"><a class="l" href="#40"> 40 </a> <span class="php-comment">/** </span></span><span id="41" class="l"><a class="l" href="#41"> 41 </a><span class="php-comment"> * @var string which scenario we get the validation from </span></span><span id="42" class="l"><a class="l" href="#42"> 42 </a><span class="php-comment"> */</span> </span><span id="43" class="l"><a class="l" href="#43"> 43 </a> <span class="php-keyword1">public</span> <span class="php-var"><a id="$scenario" href="#$scenario">$scenario</a></span>; </span><span id="44" class="l"><a class="l" href="#44"> 44 </a> </span><span id="45" class="l"><a class="l" href="#45"> 45 </a> <span class="php-comment">/** </span></span><span id="46" class="l"><a class="l" href="#46"> 46 </a><span class="php-comment"> * @var array d </span></span><span id="47" class="l"><a class="l" href="#47"> 47 </a><span class="php-comment"> */</span> </span><span id="48" class="l"><a class="l" href="#48"> 48 </a> <span class="php-keyword1">protected</span> <span class="php-var"><a id="$defaultOptions" href="#$defaultOptions">$defaultOptions</a></span> = <span class="php-keyword1">array</span>(); </span><span id="49" class="l"><a class="l" href="#49"> 49 </a> </span><span id="50" class="l"><a class="l" href="#50"> 50 </a> <span class="php-comment">/** </span></span><span id="51" class="l"><a class="l" href="#51"> 51 </a><span class="php-comment"> * @throws CException </span></span><span id="52" class="l"><a class="l" href="#52"> 52 </a><span class="php-comment"> */</span> </span><span id="53" class="l"><a class="l" href="#53"> 53 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_init" href="#_init">init</a>() </span><span id="54" class="l"><a class="l" href="#54"> 54 </a> { </span><span id="55" class="l"><a class="l" href="#55"> 55 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;uploadAction === <span class="php-keyword1">null</span>) { </span><span id="56" class="l"><a class="l" href="#56"> 56 </a> <span class="php-keyword1">throw</span> <span class="php-keyword1">new</span> CException(Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'&quot;uploadAction&quot; attribute cannot be blank'</span>)); </span><span id="57" class="l"><a class="l" href="#57"> 57 </a> } </span><span id="58" class="l"><a class="l" href="#58"> 58 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;noScriptText === <span class="php-keyword1">null</span>) { </span><span id="59" class="l"><a class="l" href="#59"> 59 </a> <span class="php-var">$this</span>-&gt;noScriptText = Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">&quot;Please enable JavaScript to use file uploader.&quot;</span>); </span><span id="60" class="l"><a class="l" href="#60"> 60 </a> } </span><span id="61" class="l"><a class="l" href="#61"> 61 </a> </span><span id="62" class="l"><a class="l" href="#62"> 62 </a> <span class="php-var">$this</span>-&gt;attachBehavior(<span class="php-quote">'ywplugin'</span>, <span class="php-keyword1">array</span>(<span class="php-quote">'class'</span> =&gt; <span class="php-quote">'yiiwheels.behaviors.WhPlugin'</span>)); </span><span id="63" class="l"><a class="l" href="#63"> 63 </a> </span><span id="64" class="l"><a class="l" href="#64"> 64 </a> <span class="php-var">$this</span>-&gt;initDefaultOptions(); </span><span id="65" class="l"><a class="l" href="#65"> 65 </a> } </span><span id="66" class="l"><a class="l" href="#66"> 66 </a> </span><span id="67" class="l"><a class="l" href="#67"> 67 </a> <span class="php-comment">/** </span></span><span id="68" class="l"><a class="l" href="#68"> 68 </a><span class="php-comment"> * Widget's run method </span></span><span id="69" class="l"><a class="l" href="#69"> 69 </a><span class="php-comment"> */</span> </span><span id="70" class="l"><a class="l" href="#70"> 70 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_run" href="#_run">run</a>() </span><span id="71" class="l"><a class="l" href="#71"> 71 </a> { </span><span id="72" class="l"><a class="l" href="#72"> 72 </a> <span class="php-var">$this</span>-&gt;renderTag(); </span><span id="73" class="l"><a class="l" href="#73"> 73 </a> <span class="php-var">$this</span>-&gt;registerClientScript(); </span><span id="74" class="l"><a class="l" href="#74"> 74 </a> } </span><span id="75" class="l"><a class="l" href="#75"> 75 </a> </span><span id="76" class="l"><a class="l" href="#76"> 76 </a> <span class="php-comment">/** </span></span><span id="77" class="l"><a class="l" href="#77"> 77 </a><span class="php-comment"> * Renders the tag where the button is going to be rendered </span></span><span id="78" class="l"><a class="l" href="#78"> 78 </a><span class="php-comment"> */</span> </span><span id="79" class="l"><a class="l" href="#79"> 79 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_renderTag" href="#_renderTag">renderTag</a>() </span><span id="80" class="l"><a class="l" href="#80"> 80 </a> { </span><span id="81" class="l"><a class="l" href="#81"> 81 </a> <span class="php-keyword1">echo</span> CHtml::tag(<span class="php-var">$this</span>-&gt;tagName, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-quote">'&lt;noscript&gt;'</span> . <span class="php-var">$this</span>-&gt;noScriptText . <span class="php-quote">'&lt;/noscript&gt;'</span>, <span class="php-keyword1">true</span>); </span><span id="82" class="l"><a class="l" href="#82"> 82 </a> } </span><span id="83" class="l"><a class="l" href="#83"> 83 </a> </span><span id="84" class="l"><a class="l" href="#84"> 84 </a> <span class="php-comment">/** </span></span><span id="85" class="l"><a class="l" href="#85"> 85 </a><span class="php-comment"> * Registers required client script for finuploader </span></span><span id="86" class="l"><a class="l" href="#86"> 86 </a><span class="php-comment"> */</span> </span><span id="87" class="l"><a class="l" href="#87"> 87 </a> <span class="php-keyword1">public</span> <span class="php-keyword1">function</span> <a id="_registerClientScript" href="#_registerClientScript">registerClientScript</a>() </span><span id="88" class="l"><a class="l" href="#88"> 88 </a> { </span><span id="89" class="l"><a class="l" href="#89"> 89 </a> <span class="php-comment">/* publish assets dir */</span> </span><span id="90" class="l"><a class="l" href="#90"> 90 </a> <span class="php-var">$path</span> = <span class="php-keyword2">dirname</span>(__FILE__) . DIRECTORY_SEPARATOR . <span class="php-quote">'assets'</span>; </span><span id="91" class="l"><a class="l" href="#91"> 91 </a> <span class="php-var">$assetsUrl</span> = <span class="php-var">$this</span>-&gt;getAssetsUrl(<span class="php-var">$path</span>); </span><span id="92" class="l"><a class="l" href="#92"> 92 </a> </span><span id="93" class="l"><a class="l" href="#93"> 93 </a> <span class="php-comment">/* @var $cs CClientScript */</span> </span><span id="94" class="l"><a class="l" href="#94"> 94 </a> <span class="php-var">$cs</span> = Yii::app()-&gt;getClientScript(); </span><span id="95" class="l"><a class="l" href="#95"> 95 </a> </span><span id="96" class="l"><a class="l" href="#96"> 96 </a> <span class="php-var">$script</span> = YII_DEBUG ? <span class="php-quote">'jquery.fineuploader-3.2.js'</span> : <span class="php-quote">'jquery.fineuploader-3.2.min.js'</span>; </span><span id="97" class="l"><a class="l" href="#97"> 97 </a> </span><span id="98" class="l"><a class="l" href="#98"> 98 </a> <span class="php-var">$cs</span>-&gt;registerCssFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/css/fineuploader.css'</span>); </span><span id="99" class="l"><a class="l" href="#99"> 99 </a> <span class="php-var">$cs</span>-&gt;registerScriptFile(<span class="php-var">$assetsUrl</span> . <span class="php-quote">'/js/'</span> . <span class="php-var">$script</span>); </span><span id="100" class="l"><a class="l" href="#100">100 </a> </span><span id="101" class="l"><a class="l" href="#101">101 </a> <span class="php-comment">/* initialize plugin */</span> </span><span id="102" class="l"><a class="l" href="#102">102 </a> <span class="php-var">$selector</span> = <span class="php-quote">'#'</span> . TbArray::getValue(<span class="php-quote">'id'</span>, <span class="php-var">$this</span>-&gt;htmlOptions, <span class="php-var">$this</span>-&gt;getId()); </span><span id="103" class="l"><a class="l" href="#103">103 </a> </span><span id="104" class="l"><a class="l" href="#104">104 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerPlugin( </span><span id="105" class="l"><a class="l" href="#105">105 </a> <span class="php-quote">'fineUploader'</span>, </span><span id="106" class="l"><a class="l" href="#106">106 </a> <span class="php-var">$selector</span>, </span><span id="107" class="l"><a class="l" href="#107">107 </a> CMap::mergeArray(<span class="php-var">$this</span>-&gt;defaultOptions, <span class="php-var">$this</span>-&gt;pluginOptions) </span><span id="108" class="l"><a class="l" href="#108">108 </a> ); </span><span id="109" class="l"><a class="l" href="#109">109 </a> <span class="php-var">$this</span>-&gt;getApi()-&gt;registerEvents(<span class="php-var">$selector</span>, <span class="php-var">$this</span>-&gt;events); </span><span id="110" class="l"><a class="l" href="#110">110 </a> } </span><span id="111" class="l"><a class="l" href="#111">111 </a> </span><span id="112" class="l"><a class="l" href="#112">112 </a> <span class="php-comment">/** </span></span><span id="113" class="l"><a class="l" href="#113">113 </a><span class="php-comment"> * Sets up default options for the plugin </span></span><span id="114" class="l"><a class="l" href="#114">114 </a><span class="php-comment"> * - thanks https://github.com/anggiaj </span></span><span id="115" class="l"><a class="l" href="#115">115 </a><span class="php-comment"> */</span> </span><span id="116" class="l"><a class="l" href="#116">116 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_initDefaultOptions" href="#_initDefaultOptions">initDefaultOptions</a>() </span><span id="117" class="l"><a class="l" href="#117">117 </a> { </span><span id="118" class="l"><a class="l" href="#118">118 </a> <span class="php-keyword1">list</span>(<span class="php-var">$name</span>, <span class="php-var">$id</span>) = <span class="php-var">$this</span>-&gt;resolveNameID(); </span><span id="119" class="l"><a class="l" href="#119">119 </a> </span><span id="120" class="l"><a class="l" href="#120">120 </a> TbArray::defaultValue(<span class="php-quote">'id'</span>, <span class="php-var">$id</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="121" class="l"><a class="l" href="#121">121 </a> TbArray::defaultValue(<span class="php-quote">'name'</span>, <span class="php-var">$name</span>, <span class="php-var">$this</span>-&gt;htmlOptions); </span><span id="122" class="l"><a class="l" href="#122">122 </a> </span><span id="123" class="l"><a class="l" href="#123">123 </a> </span><span id="124" class="l"><a class="l" href="#124">124 </a> <span class="php-var">$this</span>-&gt;defaultOptions = <span class="php-keyword1">array</span>( </span><span id="125" class="l"><a class="l" href="#125">125 </a> <span class="php-quote">'request'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="126" class="l"><a class="l" href="#126">126 </a> <span class="php-quote">'endpoint'</span> =&gt; <span class="php-var">$this</span>-&gt;uploadAction, </span><span id="127" class="l"><a class="l" href="#127">127 </a> <span class="php-quote">'inputName'</span> =&gt; <span class="php-var">$name</span>, </span><span id="128" class="l"><a class="l" href="#128">128 </a> ), </span><span id="129" class="l"><a class="l" href="#129">129 </a> <span class="php-quote">'validation'</span> =&gt; <span class="php-var">$this</span>-&gt;getValidator(), </span><span id="130" class="l"><a class="l" href="#130">130 </a> <span class="php-quote">'messages'</span> =&gt; <span class="php-keyword1">array</span>( </span><span id="131" class="l"><a class="l" href="#131">131 </a> <span class="php-quote">'typeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} has an invalid extension. Valid extension(s): {extensions}.'</span>), </span><span id="132" class="l"><a class="l" href="#132">132 </a> <span class="php-quote">'sizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too large, maximum file size is {sizeLimit}.'</span>), </span><span id="133" class="l"><a class="l" href="#133">133 </a> <span class="php-quote">'minSizeError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is too small, minimum file size is {minSizeLimit}.'</span>), </span><span id="134" class="l"><a class="l" href="#134">134 </a> <span class="php-quote">'emptyError:'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'{file} is empty, please select files again without it.'</span>), </span><span id="135" class="l"><a class="l" href="#135">135 </a> <span class="php-quote">'noFilesError'</span> =&gt; Yii::t(<span class="php-quote">'zii'</span>, <span class="php-quote">'No files to upload.'</span>), </span><span id="136" class="l"><a class="l" href="#136">136 </a> <span class="php-quote">'onLeave'</span> =&gt; Yii::t( </span><span id="137" class="l"><a class="l" href="#137">137 </a> <span class="php-quote">'zii'</span>, </span><span id="138" class="l"><a class="l" href="#138">138 </a> <span class="php-quote">'The files are being uploaded, if you leave now the upload will be cancelled.'</span> </span><span id="139" class="l"><a class="l" href="#139">139 </a> ) </span><span id="140" class="l"><a class="l" href="#140">140 </a> ), </span><span id="141" class="l"><a class="l" href="#141">141 </a> ); </span><span id="142" class="l"><a class="l" href="#142">142 </a> } </span><span id="143" class="l"><a class="l" href="#143">143 </a> </span><span id="144" class="l"><a class="l" href="#144">144 </a> <span class="php-comment">/** </span></span><span id="145" class="l"><a class="l" href="#145">145 </a><span class="php-comment"> * @return array </span></span><span id="146" class="l"><a class="l" href="#146">146 </a><span class="php-comment"> */</span> </span><span id="147" class="l"><a class="l" href="#147">147 </a> <span class="php-keyword1">protected</span> <span class="php-keyword1">function</span> <a id="_getValidator" href="#_getValidator">getValidator</a>() </span><span id="148" class="l"><a class="l" href="#148">148 </a> { </span><span id="149" class="l"><a class="l" href="#149">149 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>(); </span><span id="150" class="l"><a class="l" href="#150">150 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;hasModel()) { </span><span id="151" class="l"><a class="l" href="#151">151 </a> <span class="php-keyword1">if</span> (<span class="php-var">$this</span>-&gt;scenario !== <span class="php-keyword1">null</span>) { </span><span id="152" class="l"><a class="l" href="#152">152 </a> <span class="php-var">$originalScenario</span> = <span class="php-var">$this</span>-&gt;model-&gt;getScenario(); </span><span id="153" class="l"><a class="l" href="#153">153 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$this</span>-&gt;scenario); </span><span id="154" class="l"><a class="l" href="#154">154 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="155" class="l"><a class="l" href="#155">155 </a> <span class="php-var">$this</span>-&gt;model-&gt;setScenario(<span class="php-var">$originalScenario</span>); </span><span id="156" class="l"><a class="l" href="#156">156 </a> </span><span id="157" class="l"><a class="l" href="#157">157 </a> } <span class="php-keyword1">else</span> { </span><span id="158" class="l"><a class="l" href="#158">158 </a> <span class="php-var">$validators</span> = <span class="php-var">$this</span>-&gt;model-&gt;getValidators(<span class="php-var">$this</span>-&gt;attribute); </span><span id="159" class="l"><a class="l" href="#159">159 </a> } </span><span id="160" class="l"><a class="l" href="#160">160 </a> </span><span id="161" class="l"><a class="l" href="#161">161 </a> <span class="php-comment">// we are just looking for the first founded CFileValidator</span> </span><span id="162" class="l"><a class="l" href="#162">162 </a> <span class="php-keyword1">foreach</span> (<span class="php-var">$validators</span> <span class="php-keyword1">as</span> <span class="php-var">$validator</span>) { </span><span id="163" class="l"><a class="l" href="#163">163 </a> <span class="php-keyword1">if</span> (<span class="php-keyword2">is_a</span>(<span class="php-var">$validator</span>, <span class="php-quote">'CFileValidator'</span>)) { </span><span id="164" class="l"><a class="l" href="#164">164 </a> <span class="php-var">$ret</span> = <span class="php-keyword1">array</span>( </span><span id="165" class="l"><a class="l" href="#165">165 </a> <span class="php-quote">'allowedExtensions'</span> =&gt; <span class="php-keyword2">explode</span>(<span class="php-quote">','</span>, <span class="php-keyword2">str_replace</span>(<span class="php-quote">' '</span>, <span class="php-quote">''</span>, <span class="php-var">$validator</span>-&gt;types)), </span><span id="166" class="l"><a class="l" href="#166">166 </a> <span class="php-quote">'sizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;maxSize, </span><span id="167" class="l"><a class="l" href="#167">167 </a> <span class="php-quote">'minSizeLimit'</span> =&gt; <span class="php-var">$validator</span>-&gt;minSize, </span><span id="168" class="l"><a class="l" href="#168">168 </a> ); </span><span id="169" class="l"><a class="l" href="#169">169 </a> <span class="php-keyword1">break</span>; </span><span id="170" class="l"><a class="l" href="#170">170 </a> } </span><span id="171" class="l"><a class="l" href="#171">171 </a> } </span><span id="172" class="l"><a class="l" href="#172">172 </a> } </span><span id="173" class="l"><a class="l" href="#173">173 </a> <span class="php-keyword1">return</span> <span class="php-var">$ret</span>; </span><span id="174" class="l"><a class="l" href="#174">174 </a> } </span><span id="175" class="l"><a class="l" href="#175">175 </a></span>}</code></pre> </div> <div id="footer"> YiiWheels API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a> </div> </div> </body> </html>
2amigos/yiiwheels-docs
www/api/source-class-WhFineUploader.html
HTML
bsd-3-clause
29,497
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // godoc: Go Documentation Server // Web server tree: // // http://godoc/ main landing page // http://godoc/doc/ serve from $GOROOT/doc - spec, mem, etc. // http://godoc/src/ serve files from $GOROOT/src; .go gets pretty-printed // http://godoc/cmd/ serve documentation about commands // http://godoc/pkg/ serve documentation about packages // (idea is if you say import "compress/zlib", you go to // http://godoc/pkg/compress/zlib) // // Command-line interface: // // godoc packagepath [name ...] // // godoc compress/zlib // - prints doc for package compress/zlib // godoc crypto/block Cipher NewCMAC // - prints doc for Cipher and NewCMAC in package crypto/block // +build !appengine package main import ( "archive/zip" _ "expvar" // to serve /debug/vars "flag" "fmt" "go/build" "log" "net/http" "net/http/httptest" _ "net/http/pprof" // to serve /debug/pprof/* "net/url" "os" "path/filepath" "regexp" "runtime" "strings" "golang.org/x/tools/godoc" "golang.org/x/tools/godoc/analysis" "golang.org/x/tools/godoc/static" "golang.org/x/tools/godoc/vfs" "golang.org/x/tools/godoc/vfs/gatefs" "golang.org/x/tools/godoc/vfs/mapfs" "golang.org/x/tools/godoc/vfs/zipfs" ) const defaultAddr = ":6060" // default webserver address var ( // file system to serve // (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico) zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty") // file-based index writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files") analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform (supported: type, pointer). See http://golang.org/lib/godoc/analysis/help.html`) // network httpAddr = flag.String("http", "", "HTTP service address (e.g., '"+defaultAddr+"')") serverAddr = flag.String("server", "", "webserver address for command line searches") // layout control html = flag.Bool("html", false, "print HTML in command-line mode") srcMode = flag.Bool("src", false, "print (exported) source in command-line mode") allMode = flag.Bool("all", false, "include unexported identifiers in command-line mode") urlFlag = flag.String("url", "", "print HTML for named URL") // command-line searches query = flag.Bool("q", false, "arguments are considered search queries") verbose = flag.Bool("v", false, "verbose mode") // file system roots // TODO(gri) consider the invariant that goroot always end in '/' goroot = flag.String("goroot", runtime.GOROOT(), "Go root directory") // layout control tabWidth = flag.Int("tabwidth", 4, "tab width") showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings") templateDir = flag.String("templates", "", "load templates/JS/CSS from disk in this directory") showPlayground = flag.Bool("play", false, "enable playground in web interface") showExamples = flag.Bool("ex", false, "show examples in command line mode") declLinks = flag.Bool("links", true, "link identifiers to their declarations") // search index indexEnabled = flag.Bool("index", false, "enable search index") indexFiles = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order") indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup") maxResults = flag.Int("maxresults", 10000, "maximum number of full text search results shown") indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle") // source code notes notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show") ) func usage() { fmt.Fprintf(os.Stderr, "usage: godoc package [name ...]\n"+ " godoc -http="+defaultAddr+"\n") flag.PrintDefaults() os.Exit(2) } func loggingHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { log.Printf("%s\t%s", req.RemoteAddr, req.URL) h.ServeHTTP(w, req) }) } func handleURLFlag() { // Try up to 10 fetches, following redirects. urlstr := *urlFlag for i := 0; i < 10; i++ { // Prepare request. u, err := url.Parse(urlstr) if err != nil { log.Fatal(err) } req := &http.Request{ URL: u, } // Invoke default HTTP handler to serve request // to our buffering httpWriter. w := httptest.NewRecorder() http.DefaultServeMux.ServeHTTP(w, req) // Return data, error, or follow redirect. switch w.Code { case 200: // ok os.Stdout.Write(w.Body.Bytes()) return case 301, 302, 303, 307: // redirect redirect := w.HeaderMap.Get("Location") if redirect == "" { log.Fatalf("HTTP %d without Location header", w.Code) } urlstr = redirect default: log.Fatalf("HTTP error %d", w.Code) } } log.Fatalf("too many redirects") } func initCorpus(corpus *godoc.Corpus) { err := corpus.Init() if err != nil { log.Fatal(err) } } func main() { flag.Usage = usage flag.Parse() if certInit != nil { certInit() } playEnabled = *showPlayground // Check usage: server and no args. if (*httpAddr != "" || *urlFlag != "") && (flag.NArg() > 0) { fmt.Fprintln(os.Stderr, "can't use -http with args.") usage() } // Check usage: command line args or index creation mode. if (*httpAddr != "" || *urlFlag != "") != (flag.NArg() == 0) && !*writeIndex { fmt.Fprintln(os.Stderr, "missing args.") usage() } var fsGate chan bool fsGate = make(chan bool, 20) // Determine file system to use. if *zipfile == "" { // use file system of underlying OS rootfs := gatefs.New(vfs.OS(*goroot), fsGate) fs.Bind("/", rootfs, "/", vfs.BindReplace) } else { // use file system specified via .zip file (path separator must be '/') rc, err := zip.OpenReader(*zipfile) if err != nil { log.Fatalf("%s: %s\n", *zipfile, err) } defer rc.Close() // be nice (e.g., -writeIndex mode) fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace) } if *templateDir != "" { fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore) } else { fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace) } // Bind $GOPATH trees into Go root. for _, p := range filepath.SplitList(build.Default.GOPATH) { fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter) } httpMode := *httpAddr != "" var typeAnalysis, pointerAnalysis bool if *analysisFlag != "" { for _, a := range strings.Split(*analysisFlag, ",") { switch a { case "type": typeAnalysis = true case "pointer": pointerAnalysis = true default: log.Fatalf("unknown analysis: %s", a) } } } corpus := godoc.NewCorpus(fs) corpus.Verbose = *verbose corpus.MaxResults = *maxResults corpus.IndexEnabled = *indexEnabled && httpMode if *maxResults == 0 { corpus.IndexFullText = false } corpus.IndexFiles = *indexFiles corpus.IndexDirectory = indexDirectoryDefault corpus.IndexThrottle = *indexThrottle corpus.IndexInterval = *indexInterval if *writeIndex { corpus.IndexThrottle = 1.0 corpus.IndexEnabled = true } if *writeIndex || httpMode || *urlFlag != "" { if httpMode { go initCorpus(corpus) } else { initCorpus(corpus) } } pres = godoc.NewPresentation(corpus) pres.TabWidth = *tabWidth pres.ShowTimestamps = *showTimestamps pres.ShowPlayground = *showPlayground pres.ShowExamples = *showExamples pres.DeclLinks = *declLinks pres.SrcMode = *srcMode pres.HTMLMode = *html pres.AllMode = *allMode if *notesRx != "" { pres.NotesRx = regexp.MustCompile(*notesRx) } readTemplates(pres, httpMode || *urlFlag != "") registerHandlers(pres) if *writeIndex { // Write search index and exit. if *indexFiles == "" { log.Fatal("no index file specified") } log.Println("initialize file systems") *verbose = true // want to see what happens corpus.UpdateIndex() log.Println("writing index file", *indexFiles) f, err := os.Create(*indexFiles) if err != nil { log.Fatal(err) } index, _ := corpus.CurrentIndex() _, err = index.WriteTo(f) if err != nil { log.Fatal(err) } log.Println("done") return } // Print content that would be served at the URL *urlFlag. if *urlFlag != "" { handleURLFlag() return } if httpMode { // HTTP server mode. var handler http.Handler = http.DefaultServeMux if *verbose { log.Printf("Go Documentation Server") log.Printf("version = %s", runtime.Version()) log.Printf("address = %s", *httpAddr) log.Printf("goroot = %s", *goroot) log.Printf("tabwidth = %d", *tabWidth) switch { case !*indexEnabled: log.Print("search index disabled") case *maxResults > 0: log.Printf("full text index enabled (maxresults = %d)", *maxResults) default: log.Print("identifier search index enabled") } fs.Fprint(os.Stderr) handler = loggingHandler(handler) } // Initialize search index. if *indexEnabled { go corpus.RunIndexer() } // Start type/pointer analysis. if typeAnalysis || pointerAnalysis { go analysis.Run(pointerAnalysis, &corpus.Analysis) } if runHTTPS != nil { go func() { if err := runHTTPS(handler); err != nil { log.Fatalf("ListenAndServe TLS: %v", err) } }() } // Start http server. if *verbose { log.Println("starting HTTP server") } if wrapHTTPMux != nil { handler = wrapHTTPMux(handler) } if err := http.ListenAndServe(*httpAddr, handler); err != nil { log.Fatalf("ListenAndServe %s: %v", *httpAddr, err) } return } if *query { handleRemoteSearch() return } if err := godoc.CommandLine(os.Stdout, fs, pres, flag.Args()); err != nil { log.Print(err) } } // Hooks that are set non-nil in autocert.go if the "autocert" build tag // is used. var ( certInit func() runHTTPS func(http.Handler) error wrapHTTPMux func(http.Handler) http.Handler )
myitcv/react
_vendor/src/golang.org/x/tools/cmd/godoc/main.go
GO
bsd-3-clause
10,263
<!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>QGeoCodingManager &mdash; PyQt 5.5.1 Reference Guide</title> <link rel="stylesheet" href="../_static/classic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '5.5.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/logo_tn.ico"/> <link rel="top" title="PyQt 5.5.1 Reference Guide" href="../index.html" /> <link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" /> <link rel="next" title="QGeoCodingManagerEngine" href="qgeocodingmanagerengine.html" /> <link rel="prev" title="QGeoCodeReply" href="qgeocodereply.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qgeocodingmanagerengine.html" title="QGeoCodingManagerEngine" accesskey="N">next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="qgeocodingmanager"> <h1>QGeoCodingManager<a class="headerlink" href="#qgeocodingmanager" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="PyQt5.QtLocation.QGeoCodingManager"> <em class="property">class </em><code class="descclassname">PyQt5.QtLocation.</code><code class="descname">QGeoCodingManager</code><a class="headerlink" href="#PyQt5.QtLocation.QGeoCodingManager" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="http://doc.qt.io/qt-5/qgeocodingmanager.html">C++ documentation</a></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/logo.png" alt="Logo"/> </a></p> <h4>Previous topic</h4> <p class="topless"><a href="qgeocodereply.html" title="previous chapter">QGeoCodeReply</a></p> <h4>Next topic</h4> <p class="topless"><a href="qgeocodingmanagerengine.html" title="next chapter">QGeoCodingManagerEngine</a></p> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qgeocodingmanagerengine.html" title="QGeoCodingManagerEngine" >next</a> |</li> <li class="right" > <a href="qgeocodereply.html" title="QGeoCodeReply" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2015 Riverbank Computing Limited. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1. </div> </body> </html>
lnerit/ktailFSM
build/lib.linux-x86_64-2.7/PyQt-gpl-5.5.1/doc/html/api/qgeocodingmanager.html
HTML
bsd-3-clause
5,422
{-# LANGUAGE OverloadedStrings #-} module WildBind.SeqSpec (main,spec) where import Control.Applicative ((<*>)) import Control.Monad (forM_) import Control.Monad.IO.Class (liftIO) import qualified Control.Monad.Trans.State as State import Data.Monoid ((<>)) import Data.IORef (modifyIORef, newIORef, readIORef) import Test.Hspec import WildBind.Binding ( binds, on, run, as, boundActions, actDescription, boundInputs, Binding, justBefore ) import WildBind.Description (ActionDescription) import WildBind.Seq ( prefix, toSeq, fromSeq, withPrefix, withCancel, reviseSeq ) import WildBind.ForTest ( SampleInput(..), SampleState(..), evalStateEmpty, execAll, boundDescs, curBoundInputs, curBoundDescs, curBoundDesc, checkBoundInputs, checkBoundDescs, checkBoundDesc, withRefChecker ) main :: IO () main = hspec spec spec :: Spec spec = do spec_prefix spec_SeqBinding spec_reviseSeq spec_prefix :: Spec spec_prefix = describe "prefix" $ do let base_b = binds $ do on SIa `as` "a" `run` return () on SIb `as` "b" `run` return () specify "no prefix" $ do let b = prefix [] [] base_b boundDescs b (SS "") `shouldMatchList` [ (SIa, "a"), (SIb, "b") ] specify "one prefix" $ evalStateEmpty $ do State.put $ prefix [] [SIc] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "two prefixes" $ evalStateEmpty $ do State.put $ prefix [] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] specify "cancel binding" $ evalStateEmpty $ do State.put $ prefix [SIa] [SIc, SIb] base_b checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] -- there is no cancel binding at the top level. checkBoundInputs (SS "") [SIa, SIb] checkBoundDesc (SS "") SIa "cancel" execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] -- cancel binding should be weak and overridden. execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIb] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] spec_SeqBinding :: Spec spec_SeqBinding = describe "SeqBinding" $ do let b_a = binds $ on SIa `as` "a" `run` return () b_b = binds $ on SIb `as` "b" `run` return () describe "withPrefix" $ do it "should allow nesting" $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIb] $ withPrefix [SIc] $ withPrefix [SIa] $ toSeq (b_a <> b_b) checkBoundInputs (SS "") [SIb] execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIa, "a"), (SIb, "b")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIb] describe "mappend" $ do it "should be able to combine SeqBindings with different prefixes." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIc] $ ( (withPrefix [SIa, SIc] $ toSeq $ b_a) <> (withPrefix [SIa] $ toSeq $ b_b) ) checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc, SIb] checkBoundDesc (SS "") SIb "b" execAll (SS "") [SIb] checkBoundInputs (SS "") [SIc] execAll (SS "") [SIc, SIa] checkBoundInputs (SS "") [SIc, SIb] execAll (SS "") [SIc] checkBoundDescs (SS "") [(SIa, "a")] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIc] describe "withCancel" $ do it "should weakly add 'cancel' binding when at least one prefix is kept in the state." $ evalStateEmpty $ do State.put $ fromSeq $ withPrefix [SIa, SIc] $ withCancel [SIa, SIb, SIc] $ ( toSeq b_a <> (withPrefix [SIc] $ toSeq b_b) ) let checkPrefixOne = do checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIb, SIc] forM_ [SIa, SIb] $ \c -> checkBoundDesc (SS "") c "cancel" checkPrefixOne execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc] checkBoundInputs (SS "") [SIa, SIb, SIc] checkBoundDesc (SS "") SIa "a" checkBoundDesc (SS "") SIb "cancel" execAll (SS "") [SIa] checkPrefixOne execAll (SS "") [SIc, SIb] checkPrefixOne execAll (SS "") [SIc, SIc] checkBoundDescs (SS "") [(SIa, "cancel"), (SIb, "b"), (SIc, "cancel")] execAll (SS "") [SIb] checkPrefixOne spec_reviseSeq :: Spec spec_reviseSeq = describe "reviseSeq" $ do it "should allow access to prefix keys input so far" $ evalStateEmpty $ withRefChecker [] $ \out checkOut -> do act_out <- liftIO $ newIORef ("" :: String) let sb = withCancel [SIa] $ withPrefix [SIa, SIb, SIc] $ toSeq $ base_b base_b = binds $ on SIb `as` "B" `run` modifyIORef act_out (++ "B executed") rev ps _ _ = justBefore $ modifyIORef out (++ [ps]) State.put $ fromSeq $ reviseSeq rev sb execAll (SS "") [SIa, SIa] checkOut [[], [SIa]] execAll (SS "") [SIa, SIb, SIc] checkOut [[], [SIa], [], [SIa], [SIa, SIb]] liftIO $ readIORef act_out `shouldReturn` "" execAll (SS "") [SIb] checkOut [[], [SIa], [], [SIa], [SIa, SIb], [SIa, SIb, SIc]] liftIO $ readIORef act_out `shouldReturn` "B executed" it "should allow unbinding" $ evalStateEmpty $ do let sb = withPrefix [SIa] ( toSeq ba <> (withPrefix [SIb] $ toSeq bab) <> (withPrefix [SIa] $ toSeq baa) ) ba = binds $ on SIc `as` "c on a" `run` return () bab = binds $ on SIc `as` "c on ab" `run` return () baa = binds $ do on SIc `as` "c on aa" `run` return () on SIb `as` "b on aa" `run` return () rev ps _ i act = if (ps == [SIa] && i == SIb) || (ps == [SIa,SIa] && i == SIc) then Nothing else Just act State.put $ fromSeq $ reviseSeq rev sb checkBoundInputs (SS "") [SIa] execAll (SS "") [SIa] checkBoundInputs (SS "") [SIa, SIc] -- SIb should be canceled execAll (SS "") [SIa] checkBoundDescs (SS "") [(SIb, "b on aa")] -- SIc should be canceled execAll (SS "") [SIb] checkBoundInputs (SS "") [SIa]
debug-ito/wild-bind
wild-bind/test/WildBind/SeqSpec.hs
Haskell
bsd-3-clause
7,072
Foursquare Archiver =================== Archive your Foursquare checkin data locally. This is a Python script for saving the json data from Foursuare's `checkins` resource https://developer.foursquare.com/docs/users/checkins . If you want to generate a heatmap of checkins, see [`csv.py`](./csv.py) and http://crccheck.github.io/foursquare-archiver/ Getting started --------------- In a virtualenv, install requirements: make install Get yourself a Foursquare Oauth token. See https://developer.foursquare.com/docs/explore Set the `FOURSQUARE_OAUTH_TOKEN` environment variable export FOURSQUARE_OAUTH_TOKEN=AAAABBBBBCCCCDDDD Usage ----- Run `main.py`. A `data` directory will be created if it does not already exist. ./main.py ### With Docker You can also run this via Docker with something like: docker run --rm -e FOURSQUARE_OAUTH_TOKEN=AAAABBBBBCCCCDDDD -v /tmp/data:/app/data:rw crccheck/foursquare-archiver --data=/app/data
crccheck/foursquare-archiver
README.md
Markdown
bsd-3-clause
962
.filebrowser table td { font-size: 10px; } .filebrowser table a { font-size: 11px; } .filebrowser thead th.sorted a { padding-right: 13px; } .filebrowser td { padding: 9px 10px 7px 10px !important; } .filebrowser td.fb_icon { padding: 6px 5px 5px 5px !important; } table a.fb_deletelink, table a.fb_renamelink, table a.fb_selectlink, table a.fb_makethumblink, table a.fb_imagegeneratorlink { cursor: pointer; display: block; padding: 0; margin: 0; width: 23px; height: 17px; background-color: transparent; background-position: 0 center; background-repeat: no-repeat; } table .fb_deletelink:link, table .fb_deletelink:visited { width: 15px; background-image: url('../img/filebrowser_icon_delete.gif'); } table .fb_deletelink:hover, table .fb_deletelink:active { background-image: url('../img/filebrowser_icon_delete_hover.gif'); } table .fb_renamelink:link, table .fb_renamelink:visited { width: 14px; background-image: url('../img/filebrowser_icon_rename.gif'); } table .fb_renamelink:hover, table .fb_renamelink:active { background-image: url('../img/filebrowser_icon_rename_hover.gif'); } table .fb_selectlink:link, table .fb_selectlink:visited { background-image: url('../img/filebrowser_icon_select.gif'); } table .fb_selectlink:hover, table .fb_selectlink:active { background-image: url('../img/filebrowser_icon_select_hover.gif'); } table .fb_makethumblink:link, table .fb_makethumblink:visited { width: 50px; height: 29px; background-image: url('../img/filebrowser_icon_makethumb.gif'); } table .fb_makethumblink:hover, table .fb_makethumblink:active { background-image: url('../img/filebrowser_icon_makethumb_hover.gif'); } table .fb_imagegeneratorlink:link, table .fb_imagegeneratorlink:visited { background-image: url('../img/filebrowser_icon_imagegenerator.gif'); } table .fb_imagegeneratorlink:hover, table .fb_imagegeneratorlink:active { background-image: url('../img/filebrowser_icon_imagegenerator_hover.gif'); } /* Object Tools Basics (For Filebrowser without Grappelli) ----------------------------------------------------------------------- */ .object-tools { position:relative; float:right; font-weight:bold; font-family:Arial,Helvetica,sans-serif; text-transform: none; margin-top: -23px; margin-bottom:-10px; padding:0; } .form-row .object-tools { margin-top:5px; margin-bottom:5px; float:none; } .object-tools li { display:block; float:left; color: #ccc; font-size: 12px !important; line-height: 12px !important; padding: 0; background: none !important; } .object-tools li:hover { background:none !important; } .object-tools a { display: block; float: left; margin: -3px 0 0 15px; padding: 3px 0 2px 22px !important; font-size: 12px !important; line-height: 12px !important; background-color: #fff !important; background-position: 0 0 !important; background-repeat: no-repeat; } .object-tools a:link, .object-tools a:visited { color: #659DC2 !important; } .object-tools a:hover, .object-tools a:active { color: #555 !important; } /* Object Tools - Links ----------------------------------------------------------------------- */ .object-tools .fb_makedirectorylink:link, .object-tools .fb_makedirectorylink:visited { padding-left: 28px !important; background-image: url('../img/filebrowser_object-tools_icon_makedirectory.gif') !important; } .object-tools .fb_makedirectorylink:hover, .object-tools .fb_makedirectorylink:active { background-image: url('../img/filebrowser_object-tools_icon_makedirectory_hover.gif') !important; } .object-tools .fb_multipleuploadlink:link, .object-tools .fb_multipleuploadlink:visited { padding-left: 24px !important; background-image: url('../img/filebrowser_object-tools_icon_multipleupload.gif') !important; } .object-tools .fb_multipleuploadlink:hover, .object-tools .fb_multipleuploadlink:active { background-image: url('../img/filebrowser_object-tools_icon_multipleupload_hover.gif') !important; } .object-tools .fb_imagegeneratorlink:link, .object-tools .fb_imagegeneratorlink:visited { padding-left: 26px !important; background-image: url('../img/filebrowser_object-tools_icon_imagegenerator.gif') !important; } .object-tools .fb_imagegeneratorlink:hover, .object-tools .fb_imagegeneratorlink:active { background-image: url('../img/filebrowser_object-tools_icon_imagegenerator_hover.gif') !important; } .object-tools .fb_makethumbslink:link, .object-tools .fb_makethumbslink:visited { padding-left: 28px !important; background-image: url('../img/filebrowser_object-tools_icon_makethumb.gif') !important; } .object-tools .fb_makethumbslink:hover, .object-tools .fb_makethumbslink:active { background-image: url('../img/filebrowser_object-tools_icon_makethumb_hover.gif') !important; }
caiges/populous
populous/filebrowser/media/filebrowser/css/filebrowser.css
CSS
bsd-3-clause
4,776
<?php return array( 'Status\\V1\\Rpc\\Ping\\Controller' => array( 'GET' => array( 'description' => 'Ping the API for availability and receive a timestamp for acknowledgement.', 'request' => null, 'response' => '{ "ack": "Acknowledge the request with a timestamp" }', ), 'description' => 'Ping the API for availability.', ), 'Status\\V1\\Rest\\Status\\Controller' => array( 'collection' => array( 'GET' => array( 'description' => 'Retrieve a paginated list of status messages.', 'request' => null, 'response' => null, ), 'POST' => array( 'description' => 'Create a new status messages.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate lists of status messages.', ), 'entity' => array( 'GET' => array( 'description' => 'Retrieve a status message.', 'request' => null, 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PATCH' => array( 'description' => 'Update a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'PUT' => array( 'description' => 'Replace a status message.', 'request' => '{ "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', 'response' => '{ "_links": { "self": { "href": "/status[/:status_id]" } } "message": "A status message of no more than 140 characters.", "user": "The user submitting the status message.", "timestamp": "The timestamp when the status message was last modified." }', ), 'DELETE' => array( 'description' => 'Delete a status message.', 'request' => null, 'response' => null, ), 'description' => 'Manipulate and retrieve individual status messages.', ), 'description' => 'Create, manipulate, and retrieve status messages.', ), );
baptistecosta/apigility
module/Status/config/documentation.config.php
PHP
bsd-3-clause
3,099
#include <pulsar/testing/CppTester.hpp> #include <pulsar/system/Atom.hpp> using namespace pulsar; TEST_SIMPLE(TestAtom){ CppTester tester("Testing the Atom class"); Atom H=create_atom({0.0,0.0,0.0},1); Atom H2=create_atom({0.0,0.0,0.0},1,1); tester.test_equal("create_atom works",H,H2); tester.test_equal("correct Z",1,H.Z); tester.test_equal("correct isotope",1,H.isotope); tester.test_equal("correct mass",1.007975,H.mass); tester.test_equal("correct isotope mass",1.0078250322,H.isotope_mass); tester.test_equal("correct charge",0,H.charge); tester.test_equal("correct multiplicity",2,H.multiplicity); tester.test_equal("correct nelectrons",1,H.nelectrons); tester.test_equal("correct covalent radius",0.5858150988919267,H.cov_radius); tester.test_equal("correct vDW radius",2.267671350549394,H.vdw_radius); Atom H3(H2); tester.test_equal("copy constructor works",H,H3); Atom H4(std::move(H3)); tester.test_equal("move constructor works",H,H4); Atom D=create_atom({0.0,0.0,0.0},1,2); tester.test_equal("Isotopes work",2,D.isotope); tester.test_equal("Isotopes are different",true,D!=H); D=H4; tester.test_equal("assignment works",D,H); Atom U=create_atom({0.0,0.0,0.0},92); U=std::move(H4); tester.test_equal("move assignment works",U,H); tester.test_equal("hash works",H.my_hash(),U.my_hash()); tester.test_equal("hash works 1",H.my_hash(),H2.my_hash()); tester.test_equal("hash works 2",H.my_hash(),D.my_hash()); Atom GH=make_ghost_atom(H2); tester.test_equal("ghost works",true,is_ghost_atom(GH)); Atom q=make_point_charge(H2,3.3),q2=make_point_charge(H2.get_coords(),3.3); tester.test_equal("point charges work",true,is_point_charge(q)); tester.test_equal("point charges work 2",true,is_point_charge(q2)); tester.test_equal("is same point charge",q,q2); Atom Dm=make_dummy_atom(H),Dm2=make_dummy_atom(H.get_coords()); tester.test_equal("is dummy atom",true,is_dummy_atom(Dm)); tester.test_equal("is dummy atom 2",true,is_dummy_atom(Dm2)); tester.test_equal("is same dummy atom",Dm,Dm2); tester.print_results(); return tester.nfailed(); }
pulsar-chem/Pulsar-Core
test/system/TestAtom.cpp
C++
bsd-3-clause
2,239
<?php /** * Created by PhpStorm. * User: bill * Date: 13.04.15 * Time: 17:13 */ namespace app\tests\codeception\unit\modules\mobile\models; use app\modules\mobile\models\Trip; use app\tests\codeception\unit\fixtures\TripFixture; use Codeception\Specify; use yii\codeception\TestCase; use MongoDate; class TripTest extends TestCase{ use Specify; /** * @var \UnitTester */ protected $tester; public function fixtures() { return [ 'reports' => [ 'class' => TripFixture::className(), ], ]; } public function testGetStatus() { $this->specify("Status must be correct", function($duration, $possession, $complete, $expected) { $model = new Trip(); $model['duration'] = $duration; $model['numberPossession'] = $possession; $model['complete'] = $complete; expect($model->getStatus())->equals($expected); },[ 'examples' => [ [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('07.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('11.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_COMPLETE ], [ 'duration' => ['to' => new MongoDate(strtotime('08.03.2015'))], 'possession' => ['to' => new MongoDate(strtotime('12.03.2015'))], 'complete' => true, 'expected' => Trip::STATUS_EXPIRED ], [ 'duration' => ['to' => new MongoDate()], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_INCOMPLETE ], [ 'duration' => ['to' => new MongoDate(time()-Trip::TIME_TO_RETURN_NUMBER - 1)], 'possession' => ['to' => null], 'complete' => false, 'expected' => Trip::STATUS_EXPIRED ], ] ]); } }
shubnikofff/mobiles
tests/codeception/unit/modules/mobile/models/TripTest.php
PHP
bsd-3-clause
2,492
<?php class ReCopyWidget extends CWidget { public $targetClass='clone'; //Target CSS class target for duplicate public $limit=0; //The number of allowed copies. Default: 0 is unlimited public $addButtonId; // Add button id. Set id differently if this widget is called multiple times per page. public $addButtonLabel='Add more'; //Add button text. public $addButtonCssClass=''; //Add button CSS class. public $removeButtonLabel='Remove'; //Remove button text public $removeButtonCssClass='recopy-remove'; //Remove button CSS class. public $excludeSelector; //A jQuery selector used to exclude an element and its children public $copyClass; //A class to attach to each copy public $clearInputs; //Boolean Option to clear each copies text input fields or textarea private $_assetsUrl; /** * Initializes the widgets */ public function init() { parent::init(); if ($this->_assetsUrl === null) { $assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $this->_assetsUrl = Yii::app()->assetManager->publish($assetsDir); } $this->addButtonId=trim($this->addButtonId); if(empty($this->addButtonId)) $this->addButtonId='recopy-add'; if($this->limit) $this->limit= (is_numeric($this->limit) && $this->limit > 0)? (int)ceil($this->limit):0; } /** * Execute the widgets */ public function run() { if($this->limit==1) return ; Yii::app()->clientScript ->registerScriptFile($this->_assetsUrl . '/reCopy.js', CClientScript::POS_HEAD) ->registerScript(__CLASS__.$this->addButtonId, ' $(function(){ var removeLink = \' <a class="'.$this->removeButtonCssClass.'" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">'.$this->removeButtonLabel.'</a>\'; $("a#'.$this->addButtonId.'").relCopy({'.implode(', ', array_filter(array( empty($this->excludeSelector)?'':'excludeSelector: "'.$this->excludeSelector.'"', empty($this->limit)? '': 'limit: '.$this->limit, empty($this->copyClass)? '': 'copyClass: "'.$this->copyClass.'"', $this->clearInputs===true? 'clearInputs: true':'', $this->clearInputs===false? 'clearInputs: false':'', 'append: removeLink', ))).'}); }); ', CClientScript::POS_END); echo CHtml::link($this->addButtonLabel, '#', array( 'id'=>$this->addButtonId, 'rel'=>'.'.$this->targetClass, 'class'=>$this->addButtonCssClass) ); } }//end class
elorian/crm.inreserve.kz
protected/extensions/recopy/ReCopyWidget.php
PHP
bsd-3-clause
2,946