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
/*************************************************************************************************** * Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/ #pragma once #include "cutlass/cutlass.h" #include "cutlass/coord.h" namespace cutlass { namespace reference { namespace device { namespace kernel { /////////////////////////////////////////////////////////////////////////////////////////////////// /// Defines several helpers namespace detail { /// Helper to perform for-each operation template <typename Func, int Rank, int RankRemaining> struct TensorForEachHelper { /// Constructor for general rank __inline__ __device__ TensorForEachHelper(Func &func, Coord<Rank> const &size, Coord<Rank> &coord, int64_t index) { int64_t product = 1; CUTLASS_PRAGMA_UNROLL for (int i = Rank - RankRemaining; i < Rank; ++i) { product *= size[i]; } coord[Rank - 1 - RankRemaining] = index / product; int64_t remaining = index % product; TensorForEachHelper<Func, Rank, RankRemaining-1>(func, size, coord, remaining); } }; /// Helper to perform for-each operation template <typename Func, int Rank> struct TensorForEachHelper<Func, Rank, 0> { /// Constructor for fastest chaning rank __inline__ __device__ TensorForEachHelper(Func &func, Coord<Rank> const &size, Coord<Rank> &coord, int64_t index) { coord[Rank - 1] = index; if (coord < size) { func(coord); } } }; } // namespace detail /////////////////////////////////////////////////////////////////////////////////////////////////// /// Helper to perform for-each operation template <typename Func, int Rank, typename Params> __global__ void TensorForEach(Coord<Rank> size, Params params = Params()) { Func func(params); int64_t index = threadIdx.x + blockIdx.x * blockDim.x; int64_t max_index = 1; CUTLASS_PRAGMA_UNROLL for (int i = 0; i < Rank; ++i) { max_index *= size[i]; } CUTLASS_PRAGMA_NO_UNROLL while (index < max_index) { Coord<Rank> coord; detail::TensorForEachHelper<Func, Rank, Rank - 1>(func, size, coord, index); index += blockDim.x * gridDim.x; } } /////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace kernel } // namespace device } // namespace reference } // namespace cutlass
tgrogers/gpgpu-sim_simulations
benchmarks/src/cuda/cutlass-bench/tools/util/reference/device/kernel/tensor_foreach.h
C
bsd-2-clause
3,961
# Detect first time generation if("${CMAKE_INSTALL_PREFIX}" STREQUAL "") set(CGUL_FIRST_GENERATION ON) else() set(CGUL_FIRST_GENERATION OFF) endif() # Allow the installation to go under a different name set(CGUL_OUTPUT_NAME "CGUL" CACHE STRING "The name to install CGUL under.")
Zethes/CGUL
cmake/CGUL.cmake
CMake
bsd-2-clause
288
class ApacheArrow < Formula desc "Columnar in-memory analytics layer designed to accelerate big data" homepage "https://arrow.apache.org/" url "https://www.apache.org/dyn/closer.cgi?path=arrow/arrow-0.15.1/apache-arrow-0.15.1.tar.gz" sha256 "9a2c58c72310eafebb4997244cbeeb8c26696320d0ae3eb3e8512f75ef856fc9" revision 3 head "https://github.com/apache/arrow.git" bottle do cellar :any sha256 "51c5df916c795016199c9ccb96970cc6f7f2c5a2382aff716f106fd22e9ffe1a" => :catalina sha256 "378e4e77e56c549db1676ed865b02ac18b2e03f68d2205b46af4b6ff243b2d48" => :mojave sha256 "dc8780d6c8ad035d830c70917e4be9830aa01fc88b4a4a90cb07136bbaac56d2" => :high_sierra end depends_on "autoconf" => :build depends_on "cmake" => :build depends_on "boost" depends_on "brotli" depends_on "double-conversion" depends_on "flatbuffers" depends_on "glog" depends_on "grpc" depends_on "lz4" depends_on "numpy" depends_on "[email protected]" depends_on "protobuf" depends_on "python" depends_on "rapidjson" depends_on "snappy" depends_on "thrift" depends_on "zstd" def install ENV.cxx11 args = %W[ -DARROW_FLIGHT=ON -DARROW_ORC=ON -DARROW_PARQUET=ON -DARROW_PLASMA=ON -DARROW_PROTOBUF_USE_SHARED=ON -DARROW_PYTHON=ON -DARROW_JEMALLOC=OFF -DARROW_INSTALL_NAME_RPATH=OFF -DPYTHON_EXECUTABLE=#{Formula["python"].bin/"python3"} ] mkdir "build" cd "build" do system "cmake", "../cpp", *std_cmake_args, *args system "make" system "make", "install" end end test do (testpath/"test.cpp").write <<~EOS #include "arrow/api.h" int main(void) { arrow::int64(); return 0; } EOS system ENV.cxx, "test.cpp", "-std=c++11", "-I#{include}", "-L#{lib}", "-larrow", "-o", "test" system "./test" end end
LinuxbrewTestBot/homebrew-core
Formula/apache-arrow.rb
Ruby
bsd-2-clause
1,869
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Identifies type of object. This is a shorter version of EntityType that omits the specific and extra fields. /// </summary> [Serializable] [XmlRoot] public partial class ObjectType { /// <summary> /// Kind of entity /// </summary> private byte _entityKind; /// <summary> /// Domain of entity (air, surface, subsurface, space, etc) /// </summary> private byte _domain; /// <summary> /// country to which the design of the entity is attributed /// </summary> private ushort _country; /// <summary> /// category of entity /// </summary> private byte _category; /// <summary> /// subcategory of entity /// </summary> private byte _subcategory; /// <summary> /// Initializes a new instance of the <see cref="ObjectType"/> class. /// </summary> public ObjectType() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(ObjectType left, ObjectType right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(ObjectType left, ObjectType right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 1; // this._entityKind marshalSize += 1; // this._domain marshalSize += 2; // this._country marshalSize += 1; // this._category marshalSize += 1; // this._subcategory return marshalSize; } /// <summary> /// Gets or sets the Kind of entity /// </summary> [XmlElement(Type = typeof(byte), ElementName = "entityKind")] public byte EntityKind { get { return this._entityKind; } set { this._entityKind = value; } } /// <summary> /// Gets or sets the Domain of entity (air, surface, subsurface, space, etc) /// </summary> [XmlElement(Type = typeof(byte), ElementName = "domain")] public byte Domain { get { return this._domain; } set { this._domain = value; } } /// <summary> /// Gets or sets the country to which the design of the entity is attributed /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "country")] public ushort Country { get { return this._country; } set { this._country = value; } } /// <summary> /// Gets or sets the category of entity /// </summary> [XmlElement(Type = typeof(byte), ElementName = "category")] public byte Category { get { return this._category; } set { this._category = value; } } /// <summary> /// Gets or sets the subcategory of entity /// </summary> [XmlElement(Type = typeof(byte), ElementName = "subcategory")] public byte Subcategory { get { return this._subcategory; } set { this._subcategory = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedByte((byte)this._entityKind); dos.WriteUnsignedByte((byte)this._domain); dos.WriteUnsignedShort((ushort)this._country); dos.WriteUnsignedByte((byte)this._category); dos.WriteUnsignedByte((byte)this._subcategory); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._entityKind = dis.ReadUnsignedByte(); this._domain = dis.ReadUnsignedByte(); this._country = dis.ReadUnsignedShort(); this._category = dis.ReadUnsignedByte(); this._subcategory = dis.ReadUnsignedByte(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<ObjectType>"); try { sb.AppendLine("<entityKind type=\"byte\">" + this._entityKind.ToString(CultureInfo.InvariantCulture) + "</entityKind>"); sb.AppendLine("<domain type=\"byte\">" + this._domain.ToString(CultureInfo.InvariantCulture) + "</domain>"); sb.AppendLine("<country type=\"ushort\">" + this._country.ToString(CultureInfo.InvariantCulture) + "</country>"); sb.AppendLine("<category type=\"byte\">" + this._category.ToString(CultureInfo.InvariantCulture) + "</category>"); sb.AppendLine("<subcategory type=\"byte\">" + this._subcategory.ToString(CultureInfo.InvariantCulture) + "</subcategory>"); sb.AppendLine("</ObjectType>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as ObjectType; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(ObjectType obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._entityKind != obj._entityKind) { ivarsEqual = false; } if (this._domain != obj._domain) { ivarsEqual = false; } if (this._country != obj._country) { ivarsEqual = false; } if (this._category != obj._category) { ivarsEqual = false; } if (this._subcategory != obj._subcategory) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._entityKind.GetHashCode(); result = GenerateHash(result) ^ this._domain.GetHashCode(); result = GenerateHash(result) ^ this._country.GetHashCode(); result = GenerateHash(result) ^ this._category.GetHashCode(); result = GenerateHash(result) ^ this._subcategory.GetHashCode(); return result; } } }
mcgredonps/Unity_DIS
Assets/Plugins/DIS/Dis1998/Generated/ObjectType.cs
C#
bsd-2-clause
15,073
/*********************************************************************** visTrack: Copyright (C) 2013 - James Steven Supancic III This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #include "Semaphore.hpp" #include "params.hpp" #include "ThreadCompat.hpp" namespace deformable_depth { Semaphore_LIFO active_worker_thread(params::cpu_count()); /// SECTION: LIFO Semaphore Semaphore_LIFO::Semaphore_LIFO(int init) : S(init) { } void Semaphore_LIFO::V() { lock_guard<mutex> lock(exclusion); S++; // atomic SGtZero.notify_all(); } void Semaphore_LIFO::P() { unique_lock<mutex> lock(exclusion); #ifdef DD_CXX11 lifo.push_back(std::this_thread::get_id()); while(S <= 0 || lifo.back() != std::this_thread::get_id()) #else lifo.push_back(this_thread::get_id()); while(S <= 0 || lifo.back() != this_thread::get_id()) #endif SGtZero.wait(lock); lifo.pop_back(); // we have the mutex // go S--; } void Semaphore_LIFO::set(int val) { S = val; } /// SECTION: Regular Semaphore Semaphore::Semaphore(int init) { S = init; } void Semaphore::V() { lock_guard<mutex> lock(exclusion); // we have the lock S++; SGtZero.notify_one(); // lock released automatically upon return. } void Semaphore::P() { // wait until we can go unique_lock<mutex> lock(exclusion); while(S <= 0) SGtZero.wait(lock); // we have the mutex // go S--; // mutex is released in unique_lock dtor. } void Semaphore::set(int val) { S = val; } }
jsupancic/AStar_Dual_Tree_HandPose
System/Semaphore.cpp
C++
bsd-2-clause
2,136
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <DevToolsCore/PBXIndexingEngine.h> @class JKClassLibrary, NSMutableData, NSString; @interface PBXJavaClassFileEngine : PBXIndexingEngine { BOOL _stopped; NSMutableData *bufData; char *buf; JKClassLibrary *classLibrary; NSString *libraryName; } + (void)addClassesFromPackage:(id)arg1 inLibrary:(id)arg2 includeInnerClasses:(BOOL)arg3 intoMutableArray:(id)arg4; + (id)fileListForFrameworkOrLibrary:(id)arg1; + (id)fileListForFrameworkOrLibrary:(id)arg1 rootPackage:(id)arg2 includeInnerClasses:(BOOL)arg3; + (id)indexableFileTypes; - (const char *)convertedName:(id)arg1; - (void)dealloc; - (void)indexFileAtAbsolutePath:(id)arg1 withSettings:(id)arg2; - (id)initWithProjectIndex:(id)arg1; - (void)openClassLibrary:(id)arg1; - (BOOL)parseClassFile:(id)arg1; - (void)releaseCachedData; - (void)stopIndexing; @end
larsxschneider/Xcode-Scripting-Interface
Source/Libraries/DevToolsCoreHeader/DevToolsCore/PBXJavaClassFileEngine.h
C
bsd-2-clause
985
// +build freebsd package xattr import ( "syscall" "unsafe" ) const ( EXTATTR_NAMESPACE_USER = 1 // ENOATTR is not exported by the syscall package on Linux, because it is // an alias for ENODATA. We export it here so it is available on all // our supported platforms. ENOATTR = syscall.ENOATTR ) func getxattr(path string, name string, data []byte) (int, error) { return sysGet(syscall.SYS_EXTATTR_GET_FILE, path, name, data) } func lgetxattr(path string, name string, data []byte) (int, error) { return sysGet(syscall.SYS_EXTATTR_GET_LINK, path, name, data) } // sysGet is called by getxattr and lgetxattr with the appropriate syscall // number. This works because syscalls have the same signature and return // values. func sysGet(syscallNum uintptr, path string, name string, data []byte) (int, error) { ptr, nbytes := bytePtrFromSlice(data) /* ssize_t extattr_get_file( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); ssize_t extattr_get_link( const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); */ r0, _, err := syscall.Syscall6(syscallNum, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), EXTATTR_NAMESPACE_USER, uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), uintptr(unsafe.Pointer(ptr)), uintptr(nbytes), 0) if err != syscall.Errno(0) { return int(r0), err } return int(r0), nil } func setxattr(path string, name string, data []byte, flags int) error { return sysSet(syscall.SYS_EXTATTR_SET_FILE, path, name, data) } func lsetxattr(path string, name string, data []byte, flags int) error { return sysSet(syscall.SYS_EXTATTR_SET_LINK, path, name, data) } // sysSet is called by setxattr and lsetxattr with the appropriate syscall // number. This works because syscalls have the same signature and return // values. func sysSet(syscallNum uintptr, path string, name string, data []byte) error { ptr, nbytes := bytePtrFromSlice(data) /* ssize_t extattr_set_file( const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes ); ssize_t extattr_set_link( const char *path, int attrnamespace, const char *attrname, const void *data, size_t nbytes ); */ r0, _, err := syscall.Syscall6(syscallNum, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), EXTATTR_NAMESPACE_USER, uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), uintptr(unsafe.Pointer(ptr)), uintptr(nbytes), 0) if err != syscall.Errno(0) { return err } if int(r0) != nbytes { return syscall.E2BIG } return nil } func removexattr(path string, name string) error { return sysRemove(syscall.SYS_EXTATTR_DELETE_FILE, path, name) } func lremovexattr(path string, name string) error { return sysRemove(syscall.SYS_EXTATTR_DELETE_LINK, path, name) } // sysSet is called by removexattr and lremovexattr with the appropriate syscall // number. This works because syscalls have the same signature and return // values. func sysRemove(syscallNum uintptr, path string, name string) error { /* int extattr_delete_file( const char *path, int attrnamespace, const char *attrname ); int extattr_delete_link( const char *path, int attrnamespace, const char *attrname ); */ _, _, err := syscall.Syscall(syscallNum, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), EXTATTR_NAMESPACE_USER, uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), ) if err != syscall.Errno(0) { return err } return nil } func listxattr(path string, data []byte) (int, error) { return sysList(syscall.SYS_EXTATTR_LIST_FILE, path, data) } func llistxattr(path string, data []byte) (int, error) { return sysList(syscall.SYS_EXTATTR_LIST_LINK, path, data) } // sysSet is called by listxattr and llistxattr with the appropriate syscall // number. This works because syscalls have the same signature and return // values. func sysList(syscallNum uintptr, path string, data []byte) (int, error) { ptr, nbytes := bytePtrFromSlice(data) /* ssize_t extattr_list_file( const char *path, int attrnamespace, void *data, size_t nbytes ); ssize_t extattr_list_link( const char *path, int attrnamespace, void *data, size_t nbytes ); */ r0, _, err := syscall.Syscall6(syscallNum, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), EXTATTR_NAMESPACE_USER, uintptr(unsafe.Pointer(ptr)), uintptr(nbytes), 0, 0) if err != syscall.Errno(0) { return int(r0), err } return int(r0), nil } // stringsFromByteSlice converts a sequence of attributes to a []string. // On FreeBSD, each entry consists of a single byte containing the length // of the attribute name, followed by the attribute name. // The name is _not_ terminated by NULL. func stringsFromByteSlice(buf []byte) (result []string) { index := 0 for index < len(buf) { next := index + 1 + int(buf[index]) result = append(result, string(buf[index+1:next])) index = next } return }
kurin/restic
vendor/github.com/pkg/xattr/xattr_freebsd.go
GO
bsd-2-clause
4,999
/* Task switching */ @keyframes taskCurrentZoomOut { 0% { transform: scale(1.0); } 100% { transform: scale(0.8); } } @-webkit-keyframes taskCurrentZoomOut { 0% { -webkit-transform: scale(1.0); } 100% { -webkit-transform: scale(0.8); } } @keyframes taskCurrentZoomIn { 0% { transform: scale(0.8); } 100% { transform: scale(1.0); } } @-webkit-keyframes taskCurrentZoomIn { 0% { -webkit-transform: scale(0.8); } 100% { -webkit-transform: scale(1.0); } } @keyframes taskCurrentToLeft { 0% { transform: scale(0.8) translateX(0); z-index: 12; } 100% { transform: scale(0.6) translateX(-105%); z-index: 10; } } @-webkit-keyframes taskCurrentToLeft { 0% { -webkit-transform: scale(0.8) translateX(0); z-index: 12; } 100% { -webkit-transform: scale(0.6) translateX(-105%); z-index: 10; } } @keyframes taskLeftOut { 0% { transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { transform: scale(0.6) translateX(-133%); z-index: 8; } } @-webkit-keyframes taskLeftOut { 0% { -webkit-transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { -webkit-transform: scale(0.6) translateX(-133%); z-index: 8; } } @keyframes taskRightZoomOut { 0% { transform: scale(0.6) translateX(133%); } 100% { transform: scale(0.6) translateX(105%); } } @-webkit-keyframes taskRightZoomOut { 0% { -webkit-transform: scale(0.6) translateX(133%); } 100% { -webkit-transform: scale(0.6) translateX(105%); } } @keyframes taskRightToCurrent { 0% { transform: scale(0.6) translateX(105%); z-index: 10; } 100% { transform: scale(0.8) translateX(0); z-index: 12; } } @-webkit-keyframes taskRightToCurrent { 0% { -webkit-transform: scale(0.6) translateX(105%); z-index: 10; } 100% { -webkit-transform: scale(0.8) translateX(0); z-index: 12; } } @keyframes taskRightZoomIn { 0% { transform: scale(0.6) translateX(105%); z-index: 10; } 100% { transform: scale(1) translateX(0); z-index: 12; } } @-webkit-keyframes taskRightZoomIn { 0% { -webkit-transform: scale(0.6) translateX(105%); z-index: 10; } 100% { -webkit-transform: scale(1) translateX(0); z-index: 12; } } @keyframes taskInFromLeft { 0% { transform: scale(0.6) translateX(-105%); } 100% { transform: scale(1.0) translateX(-105%); } } @-webkit-keyframes taskInFromLeft { 0% { -webkit-transform: scale(0.6) translateX(-105%); } 100% { -webkit-transform: scale(1.0) translateX(-105%); } } @keyframes taskRightApp { 0% { transform: scale(0.6) translateX(140%); } 100% { transform: scale(0.6) translateX(105%); } } @-webkit-keyframes taskRightApp { 0% { -webkit-transform: scale(0.6) translateX(140%); } 100% { -webkit-transform: scale(0.6) translateX(105%); } } @keyframes taskLeftApp { 0% { transform: scale(0.6) translateX(-140%); } 100% { transform: scale(0.6) translateX(-105%); } } @-webkit-keyframes taskLeftApp { 0% { -webkit-transform: scale(0.6) translateX(-140%); } 100% { -webkit-transform: scale(0.6) translateX(-105%); } } @keyframes taskLeftToCurrent { 0% { transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { transform: scale(0.8) translateX(0); z-index: 12; } } @-webkit-keyframes taskLeftToCurrent { 0% { -webkit-transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { -webkit-transform: scale(0.8) translateX(0); z-index: 12; } } @keyframes taskDelete { 0% { transform: scale(0.8) translateY(0); z-index: 12; } 100% { transform: scale(0.8) translateY(-133%); z-index: 14; } } @-webkit-keyframes taskDelete { 0% { -webkit-transform: scale(0.8) translateY(0); z-index: 12; } 100% { -webkit-transform: scale(0.8) translateY(-133%); z-index: 14; } } /* Overlay */ @keyframes hideOverlay { 0% { background-color: rgba(0,0,0,0.7); } 100% { background-color: rgba(0,0,0,0); } } @-webkit-keyframes hideOverlay { 0% { background: rgba(0,0,0,0.7); } 100% { background: rgba(0,0,0,0); } } @keyframes showOverlay { 0% { background-color: rgba(0,0,0,0); } 100% { background-color: rgba(0,0,0,0.7); } } @-webkit-keyframes showOverlay { 0% { background: rgba(0,0,0,0); } 100% { background: rgba(0,0,0,0.7); } } @keyframes showCallOverlay { 0% { background-color: rgba(0,0,0,0.45); } 100% { background-color: rgba(0,0,0,0.7); } } @-webkit-keyframes showCallOverlay { 0% { background: rgba(0,0,0,0.45); } 100% { background: rgba(0,0,0,0.7); } } /* Open/close apps */ @keyframes openApp { 0% { transform: scale(0.1); opacity: 0; } 100% { transform: scale(1.0); opacity: 1; } } @-webkit-keyframes openApp { 0% { -webkit-transform: scale(0.1); opacity: 0; } 100% { -webkit-transform: scale(1.0); opacity: 1; } } @keyframes openAppIcons { 0% { transform: scale(1.0); } 100% { transform: scale(1.8); } } @-webkit-keyframes openAppIcons { 0% { -webkit-transform: scale(1.0); } 100% { -webkit-transform: scale(1.8); } } @keyframes closeApp { 0% { transform: scale(1.0); opacity: 1; } 100% { transform: scale(0.1); opacity: 0; } } @-webkit-keyframes closeApp { 0% { -webkit-transform: scale(1.0); opacity: 1; } 100% { -webkit-transform: scale(0.1); opacity: 0; } } @keyframes closeAppIcons { 0% { transform: scale(1.8); } 100% { transform: scale(1.0); } } @-webkit-keyframes closeAppIcons { 0% { -webkit-transform: scale(1.8); } 100% { -webkit-transform: scale(1.0); } } /* App invokes app */ @keyframes invokingApp { 0% { transform: scale(1.0); } 50% { transform: scale(0.8) translateX(0); z-index: 12; } 100% { transform: scale(0.6) translateX(105%); z-index: 10; } } @-webkit-keyframes invokingApp { 0% { -webkit-transform: scale(1.0); } 50% { -webkit-transform: scale(0.8) translateX(0); z-index: 12; } 100% { -webkit-transform: scale(0.6) translateX(105%); z-index: 10; } } @keyframes invokedApp { 0% { transform: scale(0.6) translateX(-133%); } 50% { transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { transform: scale(1.0) translateX(0); z-index: 12; } } @-webkit-keyframes invokedApp { 0% { -webkit-transform: scale(0.6) translateX(-133%); } 50% { -webkit-transform: scale(0.6) translateX(-105%); z-index: 10; } 100% { -webkit-transform: scale(1.0) translateX(0); z-index: 12; } } /* Go deeper */ @keyframes rightToCurrent { 0% { transform: translateX(100%); display: block} 100% { transform: translateX(0); display: block } } @-webkit-keyframes rightToCurrent { 0% { -webkit-transform: translateX(100%); } 100% { -webkit-transform: translateX(0); } } @keyframes currentToLeft { 0% { transform: translateX(0); } 99% { display: block; } 100% { transform: translateX(-100%); display: none } } @-webkit-keyframes currentToLeft { 0% { -webkit-transform: translateX(0); } 100% { -webkit-transform: translateX(-100%); } } @keyframes currentToRight { 0% { transform: translateX(0); } 99% { display: block; } 100% { transform: translateX(100%); display: none } } @-webkit-keyframes currentToRight { 0% { -webkit-transform: translateX(0); } 100% { -webkit-transform: translateX(100%); } } @keyframes leftToCurrent { 0% { transform: translateX(-100%); display: block } 100% { transform: translateX(0); display: block } } @-webkit-keyframes leftToCurrent { 0% { -webkit-transform: translateX(-100%); } 100% { -webkit-transform: translateX(0); } } @keyframes headerCurrentToLeft { 0% { transform: translateX(0); } 100% { transform: translateX(-20%); } } @-webkit-keyframes headerCurrentToLeft { 0% { -webkit-transform: translateX(0); } 100% { -webkit-transform: translateX(-20%); } } @keyframes headerLeftToCurrent { 0% { transform: translateX(-20%); } 100% { transform: translateX(0); } } @-webkit-keyframes headerLeftToCurrent { 0% { -webkit-transform: translateX(-20%); } 100% { -webkit-transform: translateX(0); } } /* Make call */ @keyframes moveLeftOut { 0% { transform: translateX(0); } 100% { transform: translateX(-100%); } } @-webkit-keyframes moveLeftOut { 0% { -webkit-transform: translateX(0); } 100% { -webkit-transform: translateX(-100%); } } @keyframes moveLeftIn { 0% { transform: translateX(100%); } 100% { transform: translateX(0); } } @-webkit-keyframes moveLeftIn { 0% { -webkit-transform: translateX(100%); } 100% { -webkit-transform: translateX(0); } } @keyframes moveRightOut { 0% { transform: translateX(0); } 100% { transform: translateX(100%); } } @-webkit-keyframes moveRightOut { 0% { -webkit-transform: translateX(0); } 100% { -webkit-transform: translateX(100%); } } @keyframes moveRightIn { 0% { transform: translateX(-100%); } 100% { transform: translateX(0); } } @-webkit-keyframes moveRightIn { 0% { -webkit-transform: translateX(-50%); } 100% { -webkit-transform: translateX(0); } } @keyframes callNameDown { 0% { transform: translateY(-10rem); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } @-webkit-keyframes callNameDown { 0% { -webkit-transform: translateY(-10rem); opacity: 0; } 100% { -webkit-transform: translateY(0); opacity: 1; } } @keyframes callNameUp { 0% { transform: translateY(0); opacity: 1; } 100% { transform: translateY(-10rem); opacity: 0; } } @-webkit-keyframes callNameUp { 0% { -webkit-transform: translateY(0); opacity: 1; } 100% { -webkit-transform: translateY(-10rem); opacity: 0; } } @keyframes callPadUp { 0% { transform: translateY(16.2rem); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } @-webkit-keyframes callPadUp { 0% { -webkit-transform: translateY(16.2rem); opacity: 0; } 100% { -webkit-transform: translateY(0); opacity: 1; } } @keyframes callPadDown { 0% { transform: translateY(0); opacity: 1; } 100% { transform: translateY(16.2rem); opacity: 0; } } @-webkit-keyframes callPadDown { 0% { -webkit-transform: translateY(0); opacity: 1; } 100% { -webkit-transform: translateY(16.2rem); opacity: 0; } } @keyframes callAnswerUp { 0% { transform: translateY(6.5rem); opacity: 0; } 100% { transform: translateY(0); opacity: 1; } } @-webkit-keyframes callAnswerUp { 0% { -webkit-transform: translateY(6.5rem); opacity: 0; } 100% { -webkit-transform: translateY(0); opacity: 1; } } @keyframes callAnswerDown { 0% { transform: translateY(0); opacity: 1; } 100% { transform: translateY(6.5rem); opacity: 0; } } @-webkit-keyframes callAnswerDown { 0% { -webkit-transform: translateY(0); opacity: 1; } 100% { -webkit-transform: translateY(6.5rem); opacity: 0; } } /* Generic */ @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } @-webkit-keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; } } @-webkit-keyframes fadeOut { 0% { opacity: 1; } 100% { opacity: 0; } } @keyframes show { 0% { transform: translateY(100%); } 100% { transform: translateY(0); } } @-webkit-keyframes show { 0% { -webkit-transform: translateY(100%); } 100% { -webkit-transform: translateY(0); } } @keyframes hide { 0% { transform: translateY(0); } 100% { transform: translateY(100%); } } @-webkit-keyframes hide { 0% { -webkit-transform: translateY(0); } 100% { -webkit-transform: translateY(100%); } } /* Building Blocks */ /* Status */ section[role="status"] { animation: hide .3s forwards; -webkit-animation: hide .3s forwards; } section[role="status"].onviewport { animation: show .3s forwards; -webkit-animation: show .3s forwards; }
geomaster/beoprevoz
app/styles/transitions.css
CSS
bsd-2-clause
12,070
#include <ORM/backends/MySql/MySqlQuery.hpp> #include <ORM/backends/MySql/MySqlDB.hpp> //#include <cppconn/exception.h> #include <sstream> #include <iomanip> #include <cstring> #include <cassert> namespace orm { MySqlQuery::MySqlQuery(DB& db,const std::string& query) : Query(db,query), _dbRes(nullptr), _currentRes(nullptr), _numFieldsRes(0), _preparedStatement(nullptr) { //remove all ';' at the end auto s = query.size() -1; while(query[s] == ';') { --s; } if(s != query.size() - 1) { _query = query.substr(0,s + 1); } }; MySqlQuery::~MySqlQuery() { if(_prepared and _preparedStatement) { mysql_stmt_close(_preparedStatement); _preparedStatement = nullptr; } if(_dbRes) { mysql_free_result(_dbRes); } for(MYSQL_BIND& param : _preparedParams) { switch(param.buffer_type) { case MYSQL_TYPE_TINY : { delete reinterpret_cast<bool*>(param.buffer); }break; case MYSQL_TYPE_LONG : { if(param.is_unsigned) delete reinterpret_cast<unsigned int*>(param.buffer); else delete reinterpret_cast<int*>(param.buffer); }break; case MYSQL_TYPE_LONGLONG : { if(param.is_unsigned) delete reinterpret_cast<long long unsigned int*>(param.buffer); else delete reinterpret_cast<long long int*>(param.buffer); }break; case MYSQL_TYPE_FLOAT: { delete reinterpret_cast<float*>(param.buffer); }break; case MYSQL_TYPE_DOUBLE: { delete reinterpret_cast<double*>(param.buffer); }break; case MYSQL_TYPE_STRING: { delete[] reinterpret_cast<char*>(param.buffer); }break; default: { std::cerr<<ORM_COLOUR_RED<<"??? MySqlQuery::~MySqlQuery() : Type "<<param.buffer_type<<" not bind"<<ORM_COLOUR_NONE<<std::endl; assert(false && "This case should never apear"); }break; } } //#error prepared_results }; int MySqlQuery::_count()const { if(_prepared) { return mysql_stmt_num_rows(_preparedStatement); } return mysql_num_rows(_dbRes); }; template<typename T> void _unpack_value(T& value,const char* buffer) { std::stringstream(buffer) >> value; } template<> void _unpack_value(std::string& value,const char* buffer) { value = buffer; } template<typename T> bool MySqlQuery::_getValue(T& value,const int& column)const { bool res = true; if(_prepared) { assert(column < int(_preparedResults.size())); if(*_preparedResults[column].is_null) { value = T(); res = false; } else { int real_len = _preparedResultsBuffer[column].real_len; _preparedResultsBuffer[column].buffer[real_len + 1] = '\0'; _unpack_value<T>(value,_preparedResultsBuffer[column].buffer.data()); } } else { _unpack_value<T>(value,_currentRes[column]); } return res; } bool MySqlQuery::_get(bool& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(int& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_getPk(int& value, const int& column)const { bool res = _getValue(value,column); if(not res) { value = -1; } return res; } bool MySqlQuery::_get(unsigned int& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(long long int& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(long long unsigned int& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(float& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(double& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(long double& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(std::string& value,const int& column)const { return _getValue(value,column); }; bool MySqlQuery::_get(struct tm& value,const int& column)const { bool res; std::string str; res = _get(str,column); if(res) { int year,mon,day,hour,min,sec; res = ::sscanf(str.c_str(),"%4d-%2d-%2d %2d:%2d:%2d",&year,&mon,&day,&hour,&min,&sec) == 6; if (res) { value.tm_year = year; value.tm_mon = mon; value.tm_mday = day; value.tm_hour = hour; value.tm_min = min; value.tm_sec = sec; } } return res; } bool MySqlQuery::_next() { int res = true; if(_prepared) { if(_numFieldsRes > 0) { res = mysql_stmt_fetch(_preparedStatement); if(res == 1) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::next() Error : "<<mysql_stmt_errno(_preparedStatement)<<" : "<< mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; } else if (res == MYSQL_NO_DATA) { //std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::next() MYSQL_NO_DATA : "<<mysql_stmt_error(prepared_statement)<<ORM_COLOUR_NONE<<std::endl; } else if (res == MYSQL_DATA_TRUNCATED) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::next() MYSQL_DATA_TRUNCATED : "<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; } res = not res; } } else { if(_dbRes) { _currentRes = mysql_fetch_row(_dbRes); } res = (_currentRes != nullptr); } return res; } bool MySqlQuery::_set(const bool& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_TINY; _preparedParams[column].buffer = new bool(value); _preparedParams[column].buffer_length = sizeof(bool); return true; }; bool MySqlQuery::_set(const int& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_LONG; _preparedParams[column].buffer = new int(value); _preparedParams[column].buffer_length = sizeof(int); return true; }; bool MySqlQuery::_set(const unsigned int& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_LONG; _preparedParams[column].buffer = new unsigned int(value); _preparedParams[column].buffer_length = sizeof(unsigned int); _preparedParams[column].is_unsigned = true; return true; }; bool MySqlQuery::_set(const long long int& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_LONGLONG; _preparedParams[column].buffer = new long long int(value); _preparedParams[column].buffer_length = sizeof(long long int); return true; }; bool MySqlQuery::_set(const long long unsigned int& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_LONGLONG; _preparedParams[column].buffer = new long long unsigned int(value); _preparedParams[column].buffer_length = sizeof(long long unsigned int); _preparedParams[column].is_unsigned = true; return true; }; bool MySqlQuery::_set(const float& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_FLOAT; _preparedParams[column].buffer = new float(value); _preparedParams[column].buffer_length = sizeof(float); return true; }; bool MySqlQuery::_set(const double& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_DOUBLE; _preparedParams[column].buffer = new double(value); _preparedParams[column].buffer_length = sizeof(double); return true; }; bool MySqlQuery::_set(const long double& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_DOUBLE; _preparedParams[column].buffer = new double(value); _preparedParams[column].buffer_length = sizeof(double); return true; }; bool MySqlQuery::_set(const std::string& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); const long unsigned int size = value.size(); char* buffer = new char[size+1]; memcpy(buffer,value.c_str(),size+1); _preparedParams[column].buffer_type = MYSQL_TYPE_STRING; _preparedParams[column].buffer = buffer; _preparedParams[column].buffer_length = size; //_preparedParams[column].is_null_value = (size == 0); return true; }; bool MySqlQuery::_set(const struct tm& value, const unsigned int& column) { if(not _prepared) { return false; } std::stringstream stream; stream<<std::setfill('0') <<std::setw(4)<<value.tm_year <<"-"<<std::setw(2)<<value.tm_mon <<"-"<<std::setw(2)<<value.tm_mday <<" " <<std::setw(2)<<value.tm_hour <<":"<<std::setw(2)<<value.tm_min <<":"<<std::setw(2)<<value.tm_sec; return _set(stream.str(),column); } bool MySqlQuery::_setNull(const int& value,const unsigned int& column) { if(not _prepared) { return false; } _resizePreparedParams(column); _preparedParams[column].buffer_type = MYSQL_TYPE_LONG; _preparedParams[column].buffer = new int(value); _preparedParams[column].buffer_length = sizeof(int); _preparedParams[column].is_null_value = true; return true; }; void MySqlQuery::_executeQuery() { if(_prepared) { { MYSQL* con = dynamic_cast<MySqlDB*>(&_db)->_dbConn; _preparedStatement = mysql_stmt_init(con); if(_preparedStatement == nullptr) { std::cerr<<"MySqlQuery::executeQuery() mysql_stmt_init(): Could not create the statement. Error message : "<< mysql_error(con) <<std::endl; return; } } if(mysql_stmt_prepare(_preparedStatement,_query.c_str(),_query.size() + 1)) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() mysql_stmt_prepare() : Could not execute the query. Error message:"<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } for(unsigned int i=0;i<_preparedParams.size();++i) { _preparedParamsBuffer[i].real_len = _preparedParams[i].buffer_length; _preparedParamsBuffer[i].is_null = _preparedParams[i].is_null_value; _preparedParams[i].length = &_preparedParamsBuffer[i].real_len; _preparedParams[i].is_null = &(_preparedParamsBuffer[i].is_null); } if(mysql_stmt_bind_param(_preparedStatement,_preparedParams.data())) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() mysql_stmt_bind_param() "<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } _dbRes = mysql_stmt_result_metadata(_preparedStatement); if(_dbRes == nullptr) { _numFieldsRes = 0; //std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() mysql_stmt_result_metadata() : db_res == nullptr. Error: "<<mysql_stmt_error(prepared_statement)<<ORM_COLOUR_NONE<<std::endl; //return; } else {//for results length my_bool arg = 1; if(mysql_stmt_attr_set(_preparedStatement,STMT_ATTR_UPDATE_MAX_LENGTH,&arg)) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() mysql_stmt_attr_set Error:"<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } } if(mysql_stmt_execute(_preparedStatement)) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() : mysql_stmt_execute(), failed. Error messuge: "<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } if(_dbRes) { if (mysql_stmt_store_result(_preparedStatement)) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() : mysql_stmt_store_result(), failed. Error messuge: "<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } _numFieldsRes = mysql_num_fields(_dbRes); if(!_initResults()) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() _initResults() : Could not execute prepare the results"<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } if(mysql_stmt_bind_result(_preparedStatement,_preparedResults.data())) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() mysql_stmt_bind_result() : "<<mysql_stmt_error(_preparedStatement)<<ORM_COLOUR_NONE<<std::endl; return; } } } else { MYSQL* con = dynamic_cast<MySqlDB*>(&_db)->_dbConn; if(mysql_query(con,_query.c_str())) { std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() : Could not execute the query. Error message:"<<mysql_error(con)<<ORM_COLOUR_NONE<<std::endl; return; } _dbRes = mysql_store_result(con); if(_dbRes == nullptr) { if(mysql_errno(con)) // mysql_store_result() returned nothing; should it have? { // query should return data // (it was a SELECT) std::cerr<<ORM_COLOUR_RED<<"MySqlQuery::executeQuery() : Could not get query results. Error message:"<<mysql_error(con)<<ORM_COLOUR_NONE<<std::endl; } return; } //num_fields_res = mysql_num_fields(db_res); } } bool MySqlQuery::_initResults() { _preparedResults.clear(); _preparedResults.resize(_numFieldsRes); std::memset(_preparedResults.data(), 0, sizeof(MYSQL_BIND)*_numFieldsRes); _preparedResultsBuffer.clear(); _preparedResultsBuffer.resize(_numFieldsRes); for(int i = 0;i< _numFieldsRes;++i) { MYSQL_FIELD* field = &(_dbRes->fields[i]); int len = field->max_length; len = len>0?len:1; _preparedResultsBuffer[i].buffer.resize(len + 1,'\0'); _preparedResults[i].buffer_type = MYSQL_TYPE_STRING; _preparedResults[i].buffer = &(_preparedResultsBuffer[i].buffer[0]); _preparedResults[i].buffer_length = len; _preparedResults[i].is_null = &_preparedResultsBuffer[i].is_null; _preparedResults[i].length = &(_preparedResultsBuffer[i].real_len); } return true; } void MySqlQuery::_resizePreparedParams(unsigned int s) { unsigned int size = _preparedParams.size(); if(size < ++s) { MYSQL_BIND n; memset(&n,0,sizeof(MYSQL_BIND)); _preparedParams.resize(s,n); ResultData data; data.is_null = false; data.real_len = 0; _preparedParamsBuffer.resize(s,data); } } };
Krozark/cpp-ORM
src/ORM/backends/MySql/MySqlQuery.cpp
C++
bsd-2-clause
18,110
/* * Copyright (C) 2009-2010 Francisco Jerez. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include "nouveau_driver.h" #include "nouveau_context.h" #include "nouveau_gldefs.h" #include "nouveau_util.h" #include "nv10_3d.xml.h" #include "nv10_driver.h" void nv10_emit_clip_plane(struct gl_context *ctx, int emit) { } static inline unsigned get_material_bitmask(unsigned m) { unsigned ret = 0; if (m & MAT_BIT_FRONT_EMISSION) ret |= NV10_3D_COLOR_MATERIAL_EMISSION; if (m & MAT_BIT_FRONT_AMBIENT) ret |= NV10_3D_COLOR_MATERIAL_AMBIENT; if (m & MAT_BIT_FRONT_DIFFUSE) ret |= NV10_3D_COLOR_MATERIAL_DIFFUSE; if (m & MAT_BIT_FRONT_SPECULAR) ret |= NV10_3D_COLOR_MATERIAL_SPECULAR; return ret; } void nv10_emit_color_material(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); unsigned mask = get_material_bitmask(ctx->Light.ColorMaterialBitmask); BEGIN_RING(chan, celsius, NV10_3D_COLOR_MATERIAL, 1); OUT_RING(chan, ctx->Light.ColorMaterialEnabled ? mask : 0); } static unsigned get_fog_mode(unsigned mode) { switch (mode) { case GL_LINEAR: return NV10_3D_FOG_MODE_LINEAR; case GL_EXP: return NV10_3D_FOG_MODE_EXP; case GL_EXP2: return NV10_3D_FOG_MODE_EXP2; default: assert(0); } } static unsigned get_fog_source(unsigned source, unsigned distance_mode) { switch (source) { case GL_FOG_COORDINATE_EXT: return NV10_3D_FOG_COORD_FOG; case GL_FRAGMENT_DEPTH_EXT: switch (distance_mode) { case GL_EYE_PLANE_ABSOLUTE_NV: return NV10_3D_FOG_COORD_DIST_ORTHOGONAL_ABS; case GL_EYE_PLANE: return NV10_3D_FOG_COORD_DIST_ORTHOGONAL; case GL_EYE_RADIAL_NV: return NV10_3D_FOG_COORD_DIST_RADIAL; default: assert(0); } default: assert(0); } } void nv10_get_fog_coeff(struct gl_context *ctx, float k[3]) { struct gl_fog_attrib *f = &ctx->Fog; switch (f->Mode) { case GL_LINEAR: k[0] = 2 + f->Start / (f->End - f->Start); k[1] = -1 / (f->End - f->Start); break; case GL_EXP: k[0] = 1.5; k[1] = -0.09 * f->Density; break; case GL_EXP2: k[0] = 1.5; k[1] = -0.21 * f->Density; break; default: assert(0); } k[2] = 0; } void nv10_emit_fog(struct gl_context *ctx, int emit) { struct nouveau_context *nctx = to_nouveau_context(ctx); struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); struct gl_fog_attrib *f = &ctx->Fog; unsigned source = nctx->fallback == HWTNL ? f->FogCoordinateSource : GL_FOG_COORDINATE_EXT; float k[3]; nv10_get_fog_coeff(ctx, k); BEGIN_RING(chan, celsius, NV10_3D_FOG_MODE, 4); OUT_RING(chan, get_fog_mode(f->Mode)); OUT_RING(chan, get_fog_source(source, f->FogDistanceMode)); OUT_RINGb(chan, f->Enabled); OUT_RING(chan, pack_rgba_f(MESA_FORMAT_RGBA8888_REV, f->Color)); BEGIN_RING(chan, celsius, NV10_3D_FOG_COEFF(0), 3); OUT_RINGp(chan, k, 3); context_dirty(ctx, FRAG); } static inline unsigned get_light_mode(struct gl_light *l) { if (l->Enabled) { if (l->_Flags & LIGHT_SPOT) return NV10_3D_ENABLED_LIGHTS_0_DIRECTIONAL; else if (l->_Flags & LIGHT_POSITIONAL) return NV10_3D_ENABLED_LIGHTS_0_POSITIONAL; else return NV10_3D_ENABLED_LIGHTS_0_NONPOSITIONAL; } else { return NV10_3D_ENABLED_LIGHTS_0_DISABLED; } } void nv10_emit_light_enable(struct gl_context *ctx, int emit) { struct nouveau_context *nctx = to_nouveau_context(ctx); struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); uint32_t en_lights = 0; int i; if (nctx->fallback != HWTNL) { BEGIN_RING(chan, celsius, NV10_3D_LIGHTING_ENABLE, 1); OUT_RING(chan, 0); return; } for (i = 0; i < MAX_LIGHTS; i++) en_lights |= get_light_mode(&ctx->Light.Light[i]) << 2 * i; BEGIN_RING(chan, celsius, NV10_3D_ENABLED_LIGHTS, 1); OUT_RING(chan, en_lights); BEGIN_RING(chan, celsius, NV10_3D_LIGHTING_ENABLE, 1); OUT_RINGb(chan, ctx->Light.Enabled); BEGIN_RING(chan, celsius, NV10_3D_NORMALIZE_ENABLE, 1); OUT_RINGb(chan, ctx->Transform.Normalize); } void nv10_emit_light_model(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); struct gl_lightmodel *m = &ctx->Light.Model; BEGIN_RING(chan, celsius, NV10_3D_SEPARATE_SPECULAR_ENABLE, 1); OUT_RINGb(chan, m->ColorControl == GL_SEPARATE_SPECULAR_COLOR); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_MODEL, 1); OUT_RING(chan, ((m->LocalViewer ? NV10_3D_LIGHT_MODEL_LOCAL_VIEWER : 0) | (_mesa_need_secondary_color(ctx) ? NV10_3D_LIGHT_MODEL_SEPARATE_SPECULAR : 0) | (!ctx->Light.Enabled && ctx->Fog.ColorSumEnabled ? NV10_3D_LIGHT_MODEL_VERTEX_SPECULAR : 0))); } static float get_shine(const float p[], float x) { const int n = 15; const float *y = &p[1]; float f = (n - 1) * (1 - 1 / (1 + p[0] * x)) / (1 - 1 / (1 + p[0] * 1024)); int i = f; /* Linear interpolation in f-space (Faster and somewhat more * accurate than x-space). */ if (x == 0) return y[0]; else if (i > n - 2) return y[n - 1]; else return y[i] + (y[i + 1] - y[i]) * (f - i); } static const float nv10_spot_params[2][16] = { { 0.02, -3.80e-05, -1.77, -2.41, -2.71, -2.88, -2.98, -3.06, -3.11, -3.17, -3.23, -3.28, -3.37, -3.47, -3.83, -5.11 }, { 0.02, -0.01, 1.77, 2.39, 2.70, 2.87, 2.98, 3.06, 3.10, 3.16, 3.23, 3.27, 3.37, 3.47, 3.83, 5.11 }, }; void nv10_get_spot_coeff(struct gl_light *l, float k[7]) { float e = l->SpotExponent; float a0, b0, a1, a2, b2, a3; if (e > 0) a0 = -1 - 5.36e-3 / sqrt(e); else a0 = -1; b0 = 1 / (1 + 0.273 * e); a1 = get_shine(nv10_spot_params[0], e); a2 = get_shine(nv10_spot_params[1], e); b2 = 1 / (1 + 0.273 * e); a3 = 0.9 + 0.278 * e; if (l->SpotCutoff > 0) { float cutoff = MAX2(a3, 1 / (1 - l->_CosCutoff)); k[0] = MAX2(0, a0 + b0 * cutoff); k[1] = a1; k[2] = a2 + b2 * cutoff; k[3] = - cutoff * l->_NormSpotDirection[0]; k[4] = - cutoff * l->_NormSpotDirection[1]; k[5] = - cutoff * l->_NormSpotDirection[2]; k[6] = 1 - cutoff; } else { k[0] = b0; k[1] = a1; k[2] = a2 + b2; k[3] = - l->_NormSpotDirection[0]; k[4] = - l->_NormSpotDirection[1]; k[5] = - l->_NormSpotDirection[2]; k[6] = -1; } } void nv10_emit_light_source(struct gl_context *ctx, int emit) { const int i = emit - NOUVEAU_STATE_LIGHT_SOURCE0; struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); struct gl_light *l = &ctx->Light.Light[i]; if (l->_Flags & LIGHT_POSITIONAL) { BEGIN_RING(chan, celsius, NV10_3D_LIGHT_POSITION_X(i), 3); OUT_RINGp(chan, l->_Position, 3); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_ATTENUATION_CONSTANT(i), 3); OUT_RINGf(chan, l->ConstantAttenuation); OUT_RINGf(chan, l->LinearAttenuation); OUT_RINGf(chan, l->QuadraticAttenuation); } else { BEGIN_RING(chan, celsius, NV10_3D_LIGHT_DIRECTION_X(i), 3); OUT_RINGp(chan, l->_VP_inf_norm, 3); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_HALF_VECTOR_X(i), 3); OUT_RINGp(chan, l->_h_inf_norm, 3); } if (l->_Flags & LIGHT_SPOT) { float k[7]; nv10_get_spot_coeff(l, k); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_SPOT_CUTOFF(i, 0), 7); OUT_RINGp(chan, k, 7); } } #define USE_COLOR_MATERIAL(attr) \ (ctx->Light.ColorMaterialEnabled && \ ctx->Light.ColorMaterialBitmask & (1 << MAT_ATTRIB_FRONT_##attr)) void nv10_emit_material_ambient(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); float (*mat)[4] = ctx->Light.Material.Attrib; float c_scene[3], c_factor[3]; struct gl_light *l; if (USE_COLOR_MATERIAL(AMBIENT)) { COPY_3V(c_scene, ctx->Light.Model.Ambient); COPY_3V(c_factor, mat[MAT_ATTRIB_FRONT_EMISSION]); } else if (USE_COLOR_MATERIAL(EMISSION)) { SCALE_3V(c_scene, mat[MAT_ATTRIB_FRONT_AMBIENT], ctx->Light.Model.Ambient); ZERO_3V(c_factor); } else { COPY_3V(c_scene, ctx->Light._BaseColor[0]); ZERO_3V(c_factor); } BEGIN_RING(chan, celsius, NV10_3D_LIGHT_MODEL_AMBIENT_R, 3); OUT_RINGp(chan, c_scene, 3); if (ctx->Light.ColorMaterialEnabled) { BEGIN_RING(chan, celsius, NV10_3D_MATERIAL_FACTOR_R, 3); OUT_RINGp(chan, c_factor, 3); } foreach(l, &ctx->Light.EnabledList) { const int i = l - ctx->Light.Light; float *c_light = (USE_COLOR_MATERIAL(AMBIENT) ? l->Ambient : l->_MatAmbient[0]); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_AMBIENT_R(i), 3); OUT_RINGp(chan, c_light, 3); } } void nv10_emit_material_diffuse(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); GLfloat (*mat)[4] = ctx->Light.Material.Attrib; struct gl_light *l; BEGIN_RING(chan, celsius, NV10_3D_MATERIAL_FACTOR_A, 1); OUT_RINGf(chan, mat[MAT_ATTRIB_FRONT_DIFFUSE][3]); foreach(l, &ctx->Light.EnabledList) { const int i = l - ctx->Light.Light; float *c_light = (USE_COLOR_MATERIAL(DIFFUSE) ? l->Diffuse : l->_MatDiffuse[0]); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_DIFFUSE_R(i), 3); OUT_RINGp(chan, c_light, 3); } } void nv10_emit_material_specular(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); struct gl_light *l; foreach(l, &ctx->Light.EnabledList) { const int i = l - ctx->Light.Light; float *c_light = (USE_COLOR_MATERIAL(SPECULAR) ? l->Specular : l->_MatSpecular[0]); BEGIN_RING(chan, celsius, NV10_3D_LIGHT_SPECULAR_R(i), 3); OUT_RINGp(chan, c_light, 3); } } static const float nv10_shininess_param[6][16] = { { 0.70, 0.00, 0.06, 0.06, 0.05, 0.04, 0.02, 0.00, -0.06, -0.13, -0.24, -0.36, -0.51, -0.66, -0.82, -1.00 }, { 0.01, 1.00, -2.29, -2.77, -2.96, -3.06, -3.12, -3.18, -3.24, -3.29, -3.36, -3.43, -3.51, -3.75, -4.33, -5.11 }, { 0.02, 0.00, 2.28, 2.75, 2.94, 3.04, 3.1, 3.15, 3.18, 3.22, 3.27, 3.32, 3.39, 3.48, 3.84, 5.11 }, { 0.70, 0.00, 0.05, 0.06, 0.06, 0.06, 0.05, 0.04, 0.02, 0.01, -0.03, -0.12, -0.25, -0.43, -0.68, -0.99 }, { 0.01, 1.00, -1.61, -2.35, -2.67, -2.84, -2.96, -3.05, -3.08, -3.14, -3.2, -3.26, -3.32, -3.42, -3.54, -4.21 }, { 0.01, 0.00, 2.25, 2.73, 2.92, 3.03, 3.09, 3.15, 3.16, 3.21, 3.25, 3.29, 3.35, 3.43, 3.56, 4.22 }, }; void nv10_get_shininess_coeff(float s, float k[6]) { int i; for (i = 0; i < 6; i++) k[i] = get_shine(nv10_shininess_param[i], s); } void nv10_emit_material_shininess(struct gl_context *ctx, int emit) { struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); float (*mat)[4] = ctx->Light.Material.Attrib; float k[6]; nv10_get_shininess_coeff( CLAMP(mat[MAT_ATTRIB_FRONT_SHININESS][0], 0, 1024), k); BEGIN_RING(chan, celsius, NV10_3D_MATERIAL_SHININESS(0), 6); OUT_RINGp(chan, k, 6); } void nv10_emit_modelview(struct gl_context *ctx, int emit) { struct nouveau_context *nctx = to_nouveau_context(ctx); struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); GLmatrix *m = ctx->ModelviewMatrixStack.Top; if (nctx->fallback != HWTNL) return; if (ctx->Light._NeedEyeCoords || ctx->Fog.Enabled || (ctx->Texture._GenFlags & TEXGEN_NEED_EYE_COORD)) { BEGIN_RING(chan, celsius, NV10_3D_MODELVIEW_MATRIX(0, 0), 16); OUT_RINGm(chan, m->m); } if (ctx->Light.Enabled || (ctx->Texture._GenFlags & TEXGEN_NEED_EYE_COORD)) { int i, j; BEGIN_RING(chan, celsius, NV10_3D_INVERSE_MODELVIEW_MATRIX(0, 0), 12); for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) OUT_RINGf(chan, m->inv[4*i + j]); } } void nv10_emit_point_parameter(struct gl_context *ctx, int emit) { } void nv10_emit_projection(struct gl_context *ctx, int emit) { struct nouveau_context *nctx = to_nouveau_context(ctx); struct nouveau_channel *chan = context_chan(ctx); struct nouveau_grobj *celsius = context_eng3d(ctx); GLmatrix m; _math_matrix_ctr(&m); get_viewport_scale(ctx, m.m); if (nv10_use_viewport_zclear(ctx)) m.m[MAT_SZ] /= 8; if (nctx->fallback == HWTNL) _math_matrix_mul_matrix(&m, &m, &ctx->_ModelProjectMatrix); BEGIN_RING(chan, celsius, NV10_3D_PROJECTION_MATRIX(0), 16); OUT_RINGm(chan, m.m); _math_matrix_dtr(&m); }
gzorin/RSXGL
extsrc/mesa/src/mesa/drivers/dri/nouveau/nv10_state_tnl.c
C
bsd-2-clause
13,418
<?php namespace GearmanManager\Bridge; use \GearmanManager\GearmanManager; /** * Implements the worker portions of the pecl/gearman library * * @author Brian Moon <[email protected]> * @copyright 1997-Present Brian Moon * @package GearmanManager * */ if (!class_exists("GearmanManager")) { require dirname(__FILE__)."/../GearmanManager.php"; } /** * Implements the worker portions of the pecl/gearman library */ class GearmanPeclManager extends GearmanManager { /** * Starts a worker for the PECL library * * @param array $worker_list List of worker functions to add * @param array $timeouts list of worker timeouts to pass to server * @return void * */ protected function start_lib_worker($worker_list, $timeouts = array()) { $thisWorker = new \GearmanWorker(); $thisWorker->addOptions(GEARMAN_WORKER_NON_BLOCKING); $thisWorker->setTimeout(5000); foreach ($this->servers as $s) { $this->log("Adding server $s", GearmanManager::LOG_LEVEL_WORKER_INFO); // see: https://bugs.php.net/bug.php?id=63041 try { $thisWorker->addServers($s); } catch (\GearmanException $e) { if ($e->getMessage() !== 'Failed to set exception option') { throw $e; } } } foreach ($worker_list as $w) { $timeout = (isset($timeouts[$w]) ? $timeouts[$w] : null); $this->log("Adding job $w ; timeout: " . $timeout, GearmanManager::LOG_LEVEL_WORKER_INFO); $thisWorker->addFunction($w, array($this, "do_job"), $this, $timeout); } $start = time(); while (!$this->stop_work) { if (@$thisWorker->work() || $thisWorker->returnCode() == GEARMAN_IO_WAIT || $thisWorker->returnCode() == GEARMAN_NO_JOBS) { if ($thisWorker->returnCode() == GEARMAN_SUCCESS) continue; if (!@$thisWorker->wait()) { if ($thisWorker->returnCode() == GEARMAN_NO_ACTIVE_FDS) { sleep(5); } } } /** * Check the running time of the current child. If it has * been too long, stop working. */ if ($this->max_run_time > 0 && time() - $start > $this->max_run_time) { $this->log("Been running too long, exiting", GearmanManager::LOG_LEVEL_WORKER_INFO); $this->stop_work = true; } if (!empty($this->config["max_runs_per_worker"]) && $this->job_execution_count >= $this->config["max_runs_per_worker"]) { $this->log("Ran $this->job_execution_count jobs which is over the maximum({$this->config['max_runs_per_worker']}), exiting", GearmanManager::LOG_LEVEL_WORKER_INFO); $this->stop_work = true; } } $thisWorker->unregisterAll(); } /** * Wrapper function handler for all registered functions * This allows us to do some nice logging when jobs are started/finished */ public function do_job($job) { static $objects; if ($objects===null) $objects = array(); $w = $job->workload(); $h = $job->handle(); $job_name = $job->functionName(); if ($this->prefix) { $func = $this->prefix.$job_name; } else { $func = $job_name; } if (empty($objects[$job_name]) && !function_exists($func) && !class_exists($func, false)) { if (!isset($this->functions[$job_name])) { $this->log("Function $func is not a registered job name"); return; } require_once $this->functions[$job_name]["path"]; if (class_exists($func) && method_exists($func, "run")) { $this->log("Creating a $func object", GearmanManager::LOG_LEVEL_WORKER_INFO); $ns_func = "\\$func"; $objects[$job_name] = new $ns_func(); } elseif (!function_exists($func)) { $this->log("Function $func not found"); return; } } $this->log("($h) Starting Job: $job_name", GearmanManager::LOG_LEVEL_WORKER_INFO); $this->log("($h) Workload: $w", GearmanManager::LOG_LEVEL_DEBUG); $log = array(); /** * Run the real function here */ if (isset($objects[$job_name])) { $this->log("($h) Calling object for $job_name.", GearmanManager::LOG_LEVEL_DEBUG); $result = $objects[$job_name]->run($job, $log); } elseif (function_exists($func)) { $this->log("($h) Calling function for $job_name.", GearmanManager::LOG_LEVEL_DEBUG); $result = $func($job, $log); } else { $this->log("($h) FAILED to find a function or class for $job_name.", GearmanManager::LOG_LEVEL_INFO); } if (!empty($log)) { foreach ($log as $l) { if (!is_scalar($l)) { $l = explode("\n", trim(print_r($l, true))); } elseif (strlen($l) > 256) { $l = substr($l, 0, 256)."...(truncated)"; } if (is_array($l)) { foreach ($l as $ln) { $this->log("($h) $ln", GearmanManager::LOG_LEVEL_WORKER_INFO); } } else { $this->log("($h) $l", GearmanManager::LOG_LEVEL_WORKER_INFO); } } } $result_log = $result; if (!is_scalar($result_log)) { $result_log = explode("\n", trim(print_r($result_log, true))); } elseif (strlen($result_log) > 256) { $result_log = substr($result_log, 0, 256)."...(truncated)"; } if (is_array($result_log)) { foreach ($result_log as $ln) { $this->log("($h) $ln", GearmanManager::LOG_LEVEL_DEBUG); } } else { $this->log("($h) $result_log", GearmanManager::LOG_LEVEL_DEBUG); } /** * Workaround for PECL bug #17114 * http://pecl.php.net/bugs/bug.php?id=17114 */ $type = gettype($result); settype($result, $type); $this->job_execution_count++; return $result; } /** * Validates the PECL compatible worker files/functions */ protected function validate_lib_workers() { foreach ($this->functions as $func => $props) { require_once $props["path"]; $real_func = $this->prefix.$func; if (!function_exists($real_func) && (!class_exists($real_func) || !method_exists($real_func, "run"))) { $this->log("Function $real_func not found in ".$props["path"]); posix_kill($this->pid, SIGUSR2); exit(); } } } }
lvbaosong/GearmanManager
src/GearmanManager/Bridge/GearmanPeclManager.php
PHP
bsd-2-clause
7,100
#include <stdlib.h> #include <stdio.h> #include "snprintf/snprintf.h" #include <string.h> #include <limits.h> #include <math.h> #include "51Degrees.h" /* ********************************************************************* * This Source Code Form is copyright of 51Degrees Mobile Experts Limited. * Copyright � 2014 51Degrees Mobile Experts Limited, 5 Charlotte Close, * Caversham, Reading, Berkshire, United Kingdom RG4 7BY * * This Source Code Form is the subject of the following patent * applications, owned by 51Degrees Mobile Experts Limited of 5 Charlotte * Close, Caversham, Reading, Berkshire, United Kingdom RG4 7BY: * European Patent Application No. 13192291.6; and * United States Patent Application Nos. 14/085,223 and 14/085,301. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. * * If a copy of the MPL was not distributed with this file, You can obtain * one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, v. 2.0. ********************************************************************** */ /** * PROBLEM MEHODS */ /* Change snprintf to the Microsoft version */ #ifdef _MSC_FULL_VER #define snprintf _snprintf #endif /** * DATA STRUCTURES USED ONLY BY FUNCTIONS IN THIS FILE */ /* Ranges used when performing a numeric match */ const fiftyoneDegreesRANGE RANGES[] = { { 0, 10 }, { 10, 100 }, { 100, 1000 }, { 1000, 10000 }, { 10000, SHRT_MAX } }; #define RANGES_COUNT sizeof(RANGES) / sizeof(fiftyoneDegreesRANGE) const int16_t POWERS[] = { 1, 10, 100, 1000, 10000 }; #define POWERS_COUNT sizeof(POWERS) / sizeof(int32_t) /** * DATA FILE READ METHODS */ fiftyoneDegreesDataSetInitStatus readStrings(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->strings = (const byte*)malloc(dataSet->header.strings.length + 1); if (dataSet->strings == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->strings), dataSet->header.strings.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readComponents(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->components = (const fiftyoneDegreesComponent*)malloc(dataSet->header.components.length); if (dataSet->components == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->components), dataSet->header.components.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readMaps(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->maps = (const fiftyoneDegreesMap*)malloc(dataSet->header.maps.length); if (dataSet->maps == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->maps), dataSet->header.maps.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readProperties(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->properties = (const fiftyoneDegreesProperty*)malloc(dataSet->header.properties.length); if (dataSet->properties == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->properties), dataSet->header.properties.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readValues(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->values = (const fiftyoneDegreesValue*)malloc(dataSet->header.values.length); if (dataSet->values == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->values), dataSet->header.values.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readProfiles(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->profiles = (const byte*)malloc(dataSet->header.profiles.length); if (dataSet->profiles == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->profiles), dataSet->header.profiles.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readSignatures(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->signatures = (const byte*)malloc(dataSet->header.signatures.length); if (dataSet->signatures == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->signatures), dataSet->header.signatures.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readRankedSignatureIndexes(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->rankedSignatureIndexes = (const int32_t*)malloc(dataSet->header.rankedSignatureIndexes.length); if (dataSet->rankedSignatureIndexes == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->rankedSignatureIndexes), dataSet->header.rankedSignatureIndexes.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readNodes(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->nodes = (const byte*)malloc(dataSet->header.nodes.length); if (dataSet->nodes == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->nodes), dataSet->header.nodes.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readRootNodes(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { int32_t index; int32_t* rootNodeOffsets; rootNodeOffsets = (int32_t*)malloc(dataSet->header.rootNodes.length); if (rootNodeOffsets == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } dataSet->rootNodes = (const fiftyoneDegreesNode**)malloc(dataSet->header.rootNodes.count * sizeof(fiftyoneDegreesNode*)); if (dataSet->rootNodes == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)rootNodeOffsets, dataSet->header.rootNodes.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } for(index = 0; index < dataSet->header.rootNodes.count; index++) { *(dataSet->rootNodes + index) = (fiftyoneDegreesNode*)(dataSet->nodes + *(rootNodeOffsets + index)); } free(rootNodeOffsets); return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readProfileOffsets(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { dataSet->profileOffsets = (const fiftyoneDegreesProfileOffset*)malloc(dataSet->header.profileOffsets.length); if (dataSet->profileOffsets == NULL) { return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY; } if (fread((void*)(dataSet->profileOffsets), dataSet->header.profileOffsets.length, 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } return DATA_SET_INIT_STATUS_SUCCESS; } fiftyoneDegreesDataSetInitStatus readDataSet(FILE *inputFilePtr, fiftyoneDegreesDataSet *dataSet) { fiftyoneDegreesDataSetInitStatus status = DATA_SET_INIT_STATUS_SUCCESS; /* Read the data set header */ if (fread((void*)&(dataSet->header), sizeof(fiftyoneDegreesDataSetHeader), 1, inputFilePtr) != 1) { return DATA_SET_INIT_STATUS_CORRUPT_DATA; } /* Check the version of the data file */ if (dataSet->header.versionMajor != 3 || dataSet->header.versionMinor != 1) { return DATA_SET_INIT_STATUS_INCORRECT_VERSION; } /* Read the entity lists */ status = readStrings(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readComponents(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readMaps(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readProperties(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readValues(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readProfiles(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readSignatures(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readRankedSignatureIndexes(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readNodes(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readRootNodes(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; status = readProfileOffsets(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) return status; /* Set some of the constant fields */ ((fiftyoneDegreesDataSet*)dataSet)->sizeOfSignature = ((dataSet->header.signatureNodesCount + dataSet->header.signatureProfilesCount) * sizeof(int32_t)); ((fiftyoneDegreesDataSet*)dataSet)->signatureStartOfNodes = (dataSet->header.signatureProfilesCount * sizeof(int32_t)); return DATA_SET_INIT_STATUS_SUCCESS; } /** * METHODS TO RETURN ELEMENTS OF THE DATA SET */ /** * Returns a component pointer from the index provided * @param dataSet pointer to the data set * @return pointer to the component */ const fiftyoneDegreesComponent* getComponent(fiftyoneDegreesDataSet *dataSet, int32_t componentIndex) { return dataSet->components + componentIndex; } /** * Returns a pointer to the ascii string at the byte offset provided * @param dataSet pointer to the data set * @param offset to the ascii string required * @return a pointer to the AsciiString at the offset */ const fiftyoneDegreesAsciiString* fiftyoneDegreesGetString(const fiftyoneDegreesDataSet *dataSet, int32_t offset) { return (const fiftyoneDegreesAsciiString*)(dataSet->strings + offset); } /** * Returns a pointer to the profile at the index provided * @param dataSet pointer to the data set * @param index of the profile required * @return pointer to the profile at the index */ fiftyoneDegreesProfile* getProfileByIndex(fiftyoneDegreesDataSet *dataSet, int32_t index) { return (fiftyoneDegreesProfile*)dataSet->profiles + (dataSet->profileOffsets + index)->offset; } /** * Gets the index of the property provided from the dataset * @param dataSet pointer to the data set containing the property * @param property pointer to the property * @return the index of the property */ int32_t getPropertyIndex(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesProperty *property) { return property - dataSet->properties; } /** * Returns the property associated with the name. * @param dataSet pointer containing the property required * @param name string of the property required * @return pointer to the property, or NULL if not found. */ const fiftyoneDegreesProperty* fiftyoneDegreesGetPropertyByName(fiftyoneDegreesDataSet *dataSet, char* name) { int32_t index; const fiftyoneDegreesProperty *property; for(index = 0; index < dataSet->header.properties.count; index++) { property = dataSet->properties + index; if (strcmp(fiftyoneDegreesGetPropertyName(dataSet, property), name) == 0) return property; } return NULL; } /** * Returns the name of the value provided. * @param dataSet pointer to the data set containing the value * @param value pointer whose name is required * @return pointer to the char string of the name */ const char* fiftyoneDegreesGetValueName(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesValue *value) { return (char*)(&fiftyoneDegreesGetString(dataSet, value->nameOffset)->firstByte); } /** * Returns the name of the property provided. * @param dataSet pointer to the data set containing the property * @param property pointer whose name is required * @return pointer to the char string of the name */ const char* fiftyoneDegreesGetPropertyName(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesProperty *property) { return (const char*)&(fiftyoneDegreesGetString(dataSet, property->nameOffset)->firstByte); } /** * Returns the first numeric index for the node provided. * @param node pointer to the node whose numeric indexes are required * @return pointer to the first numeric index for the node */ const fiftyoneDegreesNodeNumericIndex* getFirstNumericIndexForNode(const fiftyoneDegreesNode *node) { return (const fiftyoneDegreesNodeNumericIndex*)(((byte*)node) + (sizeof(fiftyoneDegreesNode) + (node->childrenCount * sizeof(fiftyoneDegreesNodeIndex)))); } /** * Returns the node associated with the node index * @param dataSet pointer to the data set * @param nodeIndex pointer associated with the node required */ const fiftyoneDegreesNode* getNodeFromNodeIndex(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNodeIndex *nodeIndex) { return (const fiftyoneDegreesNode*)(dataSet->nodes + nodeIndex->relatedNodeOffset); } /** * Returns a pointer to the first node index associated with the node provided * @param node whose first node index is needed * @return the first node index of the node */ const fiftyoneDegreesNodeIndex* getNodeIndexesForNode(const fiftyoneDegreesNode* node) { return (fiftyoneDegreesNodeIndex*)(((byte*)node) + sizeof(fiftyoneDegreesNode)); } /** * Returns true if the node is a complete one * @param node pointer to be checked * @return true if the node is complete, otherwise false */ fiftyoneDegreesBool getIsNodeComplete(const fiftyoneDegreesNode* node) { return node->nextCharacterPosition != SHRT_MIN; } /** * Returns the node pointer at the offset provided. * @param dataSet pointer to the data set * @param offset to the node required * @return pointer to the node at the offset */ const fiftyoneDegreesNode* getNodeByOffset(const fiftyoneDegreesDataSet *dataSet, int32_t offset) { return (const fiftyoneDegreesNode*)(dataSet->nodes + offset); } /** * Returns the root node associated with the node provided * @param dataSet pointer to the data set * @param node pointer whose root node is required * @return node pointer to the root node */ const fiftyoneDegreesNode* getRootNode(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNode *node) { if (node->parentOffset >= 0) { return getRootNode(dataSet, getNodeByOffset(dataSet, node->parentOffset)); } return node; } /** * Returns the length of the signature based on the node offsets * associated with the signature. * @param dataSet pointer to the data set * @param nodeOffsets pointer to the first node offset for the signature * @return the number of characters the signature contains */ int32_t getSignatureLengthFromNodeOffsets(const fiftyoneDegreesDataSet *dataSet, int32_t nodeOffset) { const fiftyoneDegreesNode *node = getNodeByOffset(dataSet, nodeOffset); return getRootNode(dataSet, node)->position + 1; } /** * Returns the characters associated with the node by looking them up in the * strings table. * @param dataSet pointer to the data set * @param node pointer for the node whose characters are required * @return pointer to the ascii string associated with the node */ const fiftyoneDegreesAsciiString* getNodeCharacters(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNode *node) { return fiftyoneDegreesGetString(dataSet, node->characterStringOffset); } /** * Returns the characters associated with a node index. This is either * performed using the strings table, or if short by converting the value * of the node index to a character array. The results are returned in the * string structure passed into the method. * @param ws pointer to the workset being used for matching * @param nodeIndex pointer of the node index being tested * @param string pointer to return the string */ void getCharactersForNodeIndex(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNodeIndex *nodeIndex, fiftyoneDegreesString *string) { int16_t index; const fiftyoneDegreesAsciiString *asciiString; if (nodeIndex->isString != 0) { asciiString = fiftyoneDegreesGetString(ws->dataSet, nodeIndex->value.integer); /* Set the length of the byte array removing the null terminator */ string->length = (int16_t)(asciiString->length - 1); string->value = (byte*)&(asciiString->firstByte); } else { for(index = 0; index < 4; index++) { if (nodeIndex->value.characters[index] == 0) break; } string->length = index; string->value = (byte*)&(nodeIndex->value.characters); } } /** * Returns the signature at the index provided. * @param dataSet pointer to the data set * @param index of the signature required * @return pointer to the signature at the index */ const byte* getSignatureByIndex(const fiftyoneDegreesDataSet *dataSet, int32_t index) { return dataSet->signatures + (dataSet->sizeOfSignature * index); } /** * Returns the signature at the ranked index provided. * @param dataSet pointer to the data set * @param ranked index of the signature required * @return pointer to the signature at the ranked index */ const byte* getSignatureByRankedIndex(const fiftyoneDegreesDataSet *dataSet, int32_t index) { return getSignatureByIndex(dataSet, dataSet->rankedSignatureIndexes[index]); } /** * Returns the number of node offsets associated with the signature. * @param dataSet pointer to the data set * @param nodeOffsets pointer to the node offsets associated with the signature * @return the number of nodes associated with the signature */ int32_t getSignatureNodeOffsetsCount(const fiftyoneDegreesDataSet *dataSet, int32_t *nodeOffsets) { int32_t count = 0; while (*(nodeOffsets + count) >= 0 && count < dataSet->header.signatureNodesCount) count++; return count; } /** * Returns the offset associated with the node pointer provided. * @param dataSet pointer to the data set * @return the integer offset to the node in the data structure */ int32_t getNodeOffsetFromNode(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNode *node) { return (byte*)node - (byte*)(dataSet->nodes); } /** * Returns an integer pointer to the node offsets associated with the * signature. * @param dataSet pointer to the data set * @param signature pointer to the signature whose node offsets are required * @return pointer to the first integer in the node offsets associated with * the signature */ int32_t* getNodeOffsetsFromSignature(const fiftyoneDegreesDataSet *dataSet, const byte *signature) { return (int32_t*)(signature + dataSet->signatureStartOfNodes); } /** * Returns an integer pointer to the profile offsets associated with the * signature. * @param signature pointer to the signature whose profile offsets are required * @return pointer to the first integer in the profile offsets associated with * the signature */ int32_t* getProfileOffsetsFromSignature(const byte *signature) { return (int32_t*)signature; } /** * Returns a pointer to the first signature index of the node * @param node pointer whose first signature index is required * @return a pointer to the first signature index */ int32_t* getFirstRankedSignatureIndexForNode(const fiftyoneDegreesNode *node) { return (int32_t*)(((byte*)node) + sizeof(fiftyoneDegreesNode) + (node->childrenCount * sizeof(fiftyoneDegreesNodeIndex)) + (node->numericChildrenCount * sizeof(fiftyoneDegreesNodeNumericIndex))); } /** * Returns a pointer to the first signature index of the node * @param node pointer whose first signature index is required * @return a pointer to the first signature index */ int32_t* getFirstSignatureIndexForNode(const fiftyoneDegreesNode *node) { return (int32_t*)(((byte*)node) + sizeof(fiftyoneDegreesNode) + (node->childrenCount * sizeof(fiftyoneDegreesNodeIndex)) + (node->numericChildrenCount * sizeof(fiftyoneDegreesNodeNumericIndex))); } /** * LINKED LIST METHODS */ /** * Adds the signature index to the linked list with a frequency of 1. * @param linkedList pointer to the linked list * @param signatureIndex to be added to the end of the list */ void linkedListAdd(fiftyoneDegreesLinkedSignatureList *linkedList, int32_t rankedSignatureIndex) { fiftyoneDegreesLinkedSignatureListItem *newSignature = (fiftyoneDegreesLinkedSignatureListItem*)(linkedList->items) + linkedList->count; newSignature->rankedSignatureIndex = rankedSignatureIndex; newSignature->frequency = 1; newSignature->next = NULL; newSignature->previous = linkedList->last; if (linkedList->first == NULL) linkedList->first = newSignature; if (linkedList->last != NULL) linkedList->last->next = newSignature; linkedList->last = newSignature; (linkedList->count)++; } /** * Builds the initial linked list using a single node. * @param ws pointer to the workset used for the match * @param node pointer to the node whose signature indexes will be used to * build the initial linked list. */ void buildInitialList(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { int32_t index; int32_t *firstSignatureIndex = getFirstRankedSignatureIndexForNode(node); for (index = 0; index < node->signatureCount; index++) { linkedListAdd(&(ws->linkedSignatureList), *(firstSignatureIndex + index)); } } /** * Adds the signature index before the item provided. * @param linkedList pointer to the linked list to be altered * @param item that the signature index should be added before */ void linkedListAddBefore(fiftyoneDegreesLinkedSignatureList *linkedList, fiftyoneDegreesLinkedSignatureListItem *item, int32_t rankedSignatureIndex) { fiftyoneDegreesLinkedSignatureListItem *newSignature = (fiftyoneDegreesLinkedSignatureListItem*)(linkedList->items + linkedList->count); newSignature->rankedSignatureIndex = rankedSignatureIndex; newSignature->frequency = 1; newSignature->next = item; newSignature->previous = item->previous; if (newSignature->previous != NULL) { newSignature->previous->next = newSignature; } item->previous = newSignature; if (item == linkedList->first) linkedList->first = newSignature; linkedList->count++; } /** * Removes the item specified from the linked list. * @param linkedList pointer to the linked list to be altered * @param item to be removed from the list */ void linkedListRemove(fiftyoneDegreesLinkedSignatureList *linkedList, fiftyoneDegreesLinkedSignatureListItem *item) { if (item->previous != NULL) item->previous->next = item->next; if (item->next != NULL) item->next->previous = item->previous; if (item == linkedList->first) linkedList->first = item->next; if (item == linkedList->last) linkedList->last = item->previous; linkedList->count--; } /** * DATASET SETUP */ /** * Destroys the data set releasing all memory available. * @param dataSet pointer to the data set being destroyed */ void fiftyoneDegreesDestroy(const fiftyoneDegreesDataSet *dataSet) { free((void*)(dataSet->requiredProperties)); free((void*)(dataSet->strings)); free((void*)(dataSet->components)); free((void*)(dataSet->maps)); free((void*)(dataSet->properties)); free((void*)(dataSet->values)); free((void*)(dataSet->profiles)); free((void*)(dataSet->signatures)); free((void*)(dataSet->nodes)); free((void*)(dataSet->rootNodes)); free((void*)(dataSet->profileOffsets)); } /** * Adds all properties in the data set to the required properties list. * @param dataSet pointer to the data set */ void setAllProperties(fiftyoneDegreesDataSet *dataSet) { int32_t index; dataSet->requiredPropertyCount = dataSet->header.properties.count; dataSet->requiredProperties = (const fiftyoneDegreesProperty**)malloc(dataSet->requiredPropertyCount * sizeof(fiftyoneDegreesProperty*)); for(index = 0; index < dataSet->requiredPropertyCount; index++) { *(dataSet->requiredProperties + index) = dataSet->properties + index; } } /** * Adds the properties in the array of properties to the list * of required properties from a match. * @param dataSet pointer to the data set * @param properties array of properties to be returned * @param count number of elements in the properties array */ void setProperties(fiftyoneDegreesDataSet *dataSet, char** properties, int32_t count) { int32_t index, propertyIndex, requiredPropertyLength; char *requiredPropertyName; const fiftyoneDegreesAsciiString *propertyName; // Allocate memory for this number of properties. dataSet->requiredPropertyCount = 0; dataSet->requiredProperties = (const fiftyoneDegreesProperty**)malloc(count * sizeof(const fiftyoneDegreesProperty*)); // Add the properties to the list of required properties. for(propertyIndex = 0; propertyIndex < count; propertyIndex++) { requiredPropertyName = *(properties + propertyIndex); requiredPropertyLength = strlen(requiredPropertyName); for(index = 0; index < dataSet->header.properties.count; index++) { propertyName = fiftyoneDegreesGetString(dataSet, (dataSet->properties + index)->nameOffset); if (requiredPropertyLength == propertyName->length - 1 && memcmp(requiredPropertyName, &propertyName->firstByte, requiredPropertyLength) == 0) { *(dataSet->requiredProperties + dataSet->requiredPropertyCount) = (dataSet->properties + index); dataSet->requiredPropertyCount++; break; } } } } /** * Gets the number of separators in the char array * @param input char array containing separated values * @return number of separators */ int32_t getSeparatorCount(char* input) { int32_t index = 0, count = 0; if (input != NULL) { while(*(input + index) != 0) { if (*(input + index) == ',' || *(input + index) == '|' || *(input + index) == ' ' || *(input + index) == '\t') count++; index++; } return count + 1; } return 0; } /** * Initialises the data set passed to the method with the data from * the file provided. If required properties is provided the data set * will only return those listed and separated by comma, pipe, space * or tab. * @param fileName of the data source to use for initialisation * @param dataSet pointer to the data set * @param requiredProperties char array to the separated list of properties * the dataSet can return * @return the number of bytes read from the file */ fiftyoneDegreesDataSetInitStatus fiftyoneDegreesInitWithPropertyString(const char *fileName, fiftyoneDegreesDataSet *dataSet, char* requiredProperties) { int32_t requiredPropertyCount = getSeparatorCount(requiredProperties); int32_t index, count = 0; char **requiredPropertiesArray = NULL; char *last = requiredProperties; fiftyoneDegreesDataSetInitStatus status; // Determine if properties were provided. if (requiredPropertyCount > 0) { // Allocate pointers for each of the properties. requiredPropertiesArray = (char**)malloc(requiredPropertyCount * sizeof(char*)); // Change the input string so that the separators are changed to nulls. for(index = 0; count < requiredPropertyCount; index++) { if (*(requiredProperties + index) == ',' || *(requiredProperties + index) == '|' || *(requiredProperties + index) == ' ' || *(requiredProperties + index) == '\t' || *(requiredProperties + index) == 0) { *(requiredProperties + index) = 0; *(requiredPropertiesArray + count) = last; last = requiredProperties + index + 1; count++; } } } status = fiftyoneDegreesInitWithPropertyArray(fileName, dataSet, requiredPropertiesArray, requiredPropertyCount); if (requiredPropertiesArray != NULL) free(requiredPropertiesArray); return status; } /** * Initialises the data set passed to the method with the data from * the file provided. If required properties is provided the data set * will only return those contained in the array. * or tab. * @param fileName of the data source to use for initialisation * @param dataSet pointer to the data set * @param requiredProperties array of strings containing the property names * @param count the number of elements in the requiredProperties array * @return the number of bytes read from the file */ fiftyoneDegreesDataSetInitStatus fiftyoneDegreesInitWithPropertyArray(const char *fileName, fiftyoneDegreesDataSet *dataSet, char** requiredProperties, int32_t count) { FILE *inputFilePtr; fiftyoneDegreesDataSetInitStatus status; // Open the file and hold on to the pointer. #ifndef _MSC_FULL_VER //"C:\\Users\\Mike\\Work\\51Degrees_C\\data\\51Degrees-Lite.dat" inputFilePtr = fopen(fileName, "rb"); #else /* If using Microsoft use the fopen_s method to avoid warning */ if (fopen_s(&inputFilePtr, fileName, "rb") != 0) { return -1; } #endif // If the file didn't open return -1. if (inputFilePtr == NULL) return DATA_SET_INIT_STATUS_FILE_NOT_FOUND; // Read the data set into memory. status = readDataSet(inputFilePtr, dataSet); if (status != DATA_SET_INIT_STATUS_SUCCESS) { return status; } // Set the properties that are returned by the data set. if (requiredProperties == NULL || count == 0) { setAllProperties(dataSet); } else { setProperties(dataSet, requiredProperties, count); } return status; } /** * WORKSET METHODS */ /** * Creates a new workset to perform matches using the dataset provided. * The workset must be destroyed using the freeWorkset method when it's * finished with to release memory. * @param dataSet pointer to the data set * @returns a pointer to the workset created */ fiftyoneDegreesWorkset *fiftyoneDegreesCreateWorkset(const fiftyoneDegreesDataSet *dataSet) { fiftyoneDegreesWorkset *ws = (fiftyoneDegreesWorkset*)malloc(sizeof(fiftyoneDegreesWorkset)); if (ws != NULL) { ws->dataSet = dataSet; // Allocate all the memory needed to the workset. ws->linkedSignatureList.items = (fiftyoneDegreesLinkedSignatureListItem*)malloc(dataSet->header.maxSignaturesClosest * sizeof(fiftyoneDegreesLinkedSignatureListItem)); ws->input = (char*)malloc((dataSet->header.maxUserAgentLength + 1) * sizeof(char)); ws->signatureAsString = (char*)malloc((dataSet->header.maxUserAgentLength + 1) * sizeof(char)); ws->profiles = (const fiftyoneDegreesProfile**)malloc(dataSet->header.components.count * sizeof(const fiftyoneDegreesProfile*)); ws->nodes = (const fiftyoneDegreesNode**)malloc(dataSet->header.maxUserAgentLength * sizeof(const fiftyoneDegreesNode*)); ws->orderedNodes = (const fiftyoneDegreesNode**)malloc(dataSet->header.maxUserAgentLength * sizeof(const fiftyoneDegreesNode*)); ws->targetUserAgentArray = (byte*)malloc(dataSet->header.maxUserAgentLength); ws->relevantNodes = (char*)malloc(dataSet->header.maxUserAgentLength + 1); ws->closestNodes = (char*)malloc(dataSet->header.maxUserAgentLength + 1); ws->values = (const fiftyoneDegreesValue**)malloc(dataSet->header.maxValues * sizeof(const fiftyoneDegreesValue*)); // Check all the memory was allocated correctly. if (ws->linkedSignatureList.items == NULL || ws->input == NULL || ws->signatureAsString == NULL || ws->profiles == NULL || ws->nodes == NULL || ws->orderedNodes == NULL || ws->targetUserAgentArray == NULL || ws->relevantNodes == NULL || ws->closestNodes == NULL || ws->values == NULL) { // One or more of the workset memory allocations failed. // Free any that worked and return NULL. if (ws->linkedSignatureList.items != NULL) { free((void*)ws->linkedSignatureList.items); } if (ws->input != NULL) { free((void*)ws->input); } if (ws->signatureAsString != NULL) { free((void*)ws->signatureAsString); } if (ws->profiles != NULL) { free((void*)ws->profiles); } if (ws->nodes != NULL) { free((void*)ws->nodes); } if (ws->orderedNodes != NULL) { free((void*)ws->orderedNodes); } if (ws->targetUserAgentArray != NULL) { free((void*)ws->targetUserAgentArray); } if (ws->relevantNodes != NULL) { free((void*)ws->relevantNodes); } if (ws->closestNodes != NULL) { free((void*)ws->closestNodes); } if (ws->values != NULL) { free((void*)ws->values); } // Free the workset which worked earlier and return NULL. free(ws); ws = NULL; } else { // Null terminate the strings used to return the relevant and closest nodes. ws->relevantNodes[dataSet->header.maxUserAgentLength] = 0; ws->closestNodes[dataSet->header.maxUserAgentLength] = 0; } } return ws; } /** * Releases the memory used by the workset. * @param pointer to the workset created previously */ void fiftyoneDegreesFreeWorkset(const fiftyoneDegreesWorkset *ws) { free((void*)(ws->input)); free((void*)(ws->signatureAsString)); free((void*)ws->profiles); free((void*)ws->nodes); free((void*)ws->orderedNodes); free((void*)ws->targetUserAgentArray); free((void*)ws->relevantNodes); free((void*)ws->closestNodes); free((void*)ws->values); free((void*)ws->linkedSignatureList.items); free((void*)ws); } /** * Adds the node of the signature into the signature string of the work set * @param ws pointer to the work set used for the match * @param node from the signature to be added to the string * @return the right most character returned */ int addSignatureNodeToString(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { int nodeIndex, signatureIndex; const fiftyoneDegreesAsciiString *characters = fiftyoneDegreesGetString(ws->dataSet, node->characterStringOffset); for(nodeIndex = 0, signatureIndex = node->position + 1; nodeIndex < characters->length - 1; nodeIndex++, signatureIndex++) { ws->signatureAsString[signatureIndex] = (&(characters->firstByte))[nodeIndex]; } return signatureIndex; } /** * Sets the signature provided as the string returned by the match. * @param ws pointer to the work set used for the match * @param signature pointer to be used as the string for the result */ void setSignatureAsString(fiftyoneDegreesWorkset *ws, const byte *signature) { int *nodeOffsets = getNodeOffsetsFromSignature(ws->dataSet, signature); int index, nullPosition = 0, lastCharacter = 0, nodeOffsetCount = getSignatureNodeOffsetsCount(ws->dataSet, nodeOffsets); for(index = 0; index < ws->dataSet->header.maxUserAgentLength; index++) { ws->signatureAsString[index] = '_'; } for(index = 0; index < nodeOffsetCount; index++) { lastCharacter = addSignatureNodeToString(ws, getNodeByOffset(ws->dataSet, *(nodeOffsets + index))); if (lastCharacter > nullPosition) { nullPosition = lastCharacter; } } ws->signatureAsString[nullPosition] = 0; } /** * Adds the node to the end of the workset. * @param ws pointer to the work set used for the match * @param node pointer to be added to the work set * @param index the should be added at */ void addNodeIntoWorkset(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node, int32_t index) { *(ws->nodes + index) = node; ws->nodeCount++; } /** * Inserts the node at the position provided moving all other nodes down. * @param ws pointer to the work set used for the match * @param node pointer to the node being added to the workset * @param insertIndex the index to insert the node at */ void insertNodeIntoWorksetAtIndex(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node, int32_t insertIndex) { int32_t index; for (index = ws->nodeCount - 1; index >= insertIndex; index--) { *(ws->nodes + index + 1) = *(ws->nodes + index); } addNodeIntoWorkset(ws, node, insertIndex); } /** * Inserts the node into the workset considering its position relative to other * nodes already set. * @param ws pointer to the work set used for the match * @param node pointer to be added to the work set * @return the index the node as added at */ int32_t insertNodeIntoWorkSet(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { int32_t index; for(index = 0; index < ws->nodeCount; index++) { if (node > *(ws->nodes + index)) { // The node to be inserted is greater than the current node. // Insert the node before this one. insertNodeIntoWorksetAtIndex(ws, node, index); return index; } } addNodeIntoWorkset(ws, node, index); return index; } /** * MATCH METHODS */ /** * Sets the target user agent and resets any other fields to initial values. * Must be called before a match commences. * @param ws pointer to the workset to be used for the match * @param userAgent char pointer to the user agent. Trimmed if longer than * the maximum allowed for matching */ void setTargetUserAgentArray(fiftyoneDegreesWorkset *ws, char* userAgent) { int32_t index; ws->targetUserAgent = userAgent; ws->targetUserAgentArrayLength = strlen(userAgent); if (ws->targetUserAgentArrayLength > ws->dataSet->header.maxUserAgentLength) ws->targetUserAgentArrayLength = ws->dataSet->header.maxUserAgentLength; /* Work out the starting character position */ for(index = 0; index < ws->targetUserAgentArrayLength; index++) { ws->targetUserAgentArray[index]= userAgent[index]; } ws->nextCharacterPositionIndex = (int16_t)(ws->targetUserAgentArrayLength - 1); /* Check to ensure the length of the user agent does not exceed the number of root nodes. */ if (ws->nextCharacterPositionIndex >= ws->dataSet->header.rootNodes.count) { ws->nextCharacterPositionIndex = (int16_t)(ws->dataSet->header.rootNodes.count - 1); } /* Reset the nodes to zero ready for the new match */ ws->nodeCount = 0; for(index = 0; index < ws->dataSet->header.signatureNodesCount; index++) { *(ws->nodes + index) = NULL; *(ws->orderedNodes + index) = NULL; } /* Reset the profiles to space ready for the new match */ ws->profileCount = 0; for(index = 0; index < ws->dataSet->header.components.count; index++) { *(ws->profiles + index) = NULL; } /* Reset the closest and relevant strings */ for(index = 0; index < ws->dataSet->header.maxUserAgentLength; index++) { ws->relevantNodes[index] = '_'; ws->closestNodes[index] = ' '; } /* Reset the linked lists */ ws->linkedSignatureList.count = 0; ws->linkedSignatureList.first = NULL; ws->linkedSignatureList.last = NULL; /* Reset the counters */ ws->difference = 0; ws->stringsRead = 0; ws->nodesEvaluated = 0; ws->rootNodesEvaluated = 0; ws->signaturesCompared = 0; ws->signaturesRead = 0; /* Reset the profiles and signatures */ ws->profileCount = 0; ws->signature = NULL; } /** * Compares the characters which start at the start index of the target user * agent with the string provided and returns 0 if they're equal, -1 if * lower or 1 if higher. * @param targetUserAgentArray pointer to the target user agent * @param startIndex character position in the array to start comparing * @param string pointer to be compared with the target user agent * @return the difference between the characters, or 0 if equal */ int32_t compareTo(byte* targetUserAgentArray, int32_t startIndex, fiftyoneDegreesString *string) { int32_t i, o, difference; for (i = string->length - 1, o = startIndex + string->length - 1; i >= 0; i--, o--) { difference = *(string->value + i) - *(targetUserAgentArray + o); if (difference != 0) return difference; } return 0; } /** * Returns the next node after the one provided for the target user agent. * @param ws pointer being used for the match * @param node pointer of the current node * @return pointer to the next node to evaluate, or NULL if none match the * target */ const fiftyoneDegreesNode* getNextNode(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { int32_t upper = node->childrenCount - 1, lower, middle, length, startIndex, comparisonResult; const fiftyoneDegreesNodeIndex *children; fiftyoneDegreesString string; if (upper >= 0) { children = getNodeIndexesForNode(node); lower = 0; middle = lower + (upper - lower) / 2; getCharactersForNodeIndex(ws, children + middle, &string); length = string.length; startIndex = node->position - length + 1; while (lower <= upper) { middle = lower + (upper - lower) / 2; /* Increase the number of strings checked. */ if ((children + middle)->isString) ws->stringsRead++; /* Increase the number of nodes checked. */ ws->nodesEvaluated++; getCharactersForNodeIndex(ws, children + middle, &string); comparisonResult = compareTo( ws->targetUserAgentArray, startIndex, &string); if (comparisonResult == 0) return getNodeFromNodeIndex(ws->dataSet, children + middle); else if (comparisonResult > 0) upper = middle - 1; else lower = middle + 1; } } return NULL; } /** * Returns a leaf node if one is available, otherwise NULL. * @param ws pointer the workset used for the match * @param node pointer to the node whose children should be checked * @return a pointer the complete leaf node if one is available */ const fiftyoneDegreesNode* getCompleteNode(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { const fiftyoneDegreesNode *nextNode = getNextNode(ws, node), *foundNode = NULL; if (nextNode != NULL) { foundNode = getCompleteNode(ws, nextNode); } if (foundNode == NULL && getIsNodeComplete(node)) foundNode = node; return foundNode; } /** * Compares the signature to the nodes of the match in the workset and if * they match exactly returns 0. If not -1 or 1 are returned depending on * whether the signature is lower or higher in the list. * @param ws pointer to the workset used for the match * @param signature pointer to the signature being tested * @return the difference between the signature and the matched nodes */ int32_t compareExact(const byte *signature, fiftyoneDegreesWorkset *ws) { int32_t index, nodeIndex, difference; int32_t *nodeOffsets = getNodeOffsetsFromSignature(ws->dataSet, signature); int32_t signatureNodeOffsetsCount = getSignatureNodeOffsetsCount(ws->dataSet, nodeOffsets); int32_t length = signatureNodeOffsetsCount > ws->nodeCount ? ws->nodeCount : signatureNodeOffsetsCount; for (index = 0, nodeIndex = ws->nodeCount - 1; index < length; index++, nodeIndex--) { difference = *(nodeOffsets + index) - getNodeOffsetFromNode(ws->dataSet, *(ws->nodes + nodeIndex)); if (difference != 0) return difference; } if (signatureNodeOffsetsCount < ws->nodeCount) return -1; if (signatureNodeOffsetsCount > ws->nodeCount) return 1; return 0; } /** * Returns the index of the signature exactly associated with the matched * nodes or -1 if no such signature exists. * @param ws pointer to the workset used for the match * @return index of the signature matching the nodes or -1 */ int32_t getExactSignatureIndex(fiftyoneDegreesWorkset *ws) { int32_t comparisonResult, middle, lower = 0, upper = ws->dataSet->header.signatures.count - 1; const byte *signature; while (lower <= upper) { middle = lower + (upper - lower) / 2; signature = getSignatureByIndex(ws->dataSet, middle); ws->signaturesRead++; comparisonResult = compareExact(signature, ws); if (comparisonResult == 0) return middle; else if (comparisonResult > 0) upper = middle - 1; else lower = middle + 1; } return -1; } /** * Sets the characters of the node at the correct position in the output * array provided. * @param dataSet pointer to the dataset * @param node pointer to the node being added to the output * @return the position of the right most character set */ int32_t setNodeString(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNode *node, char* output) { int32_t n, c, last = 0; const fiftyoneDegreesAsciiString *string = fiftyoneDegreesGetString(dataSet, node->characterStringOffset); for(n = 0, c = node->position + 1; n < string->length - 1; c++, n++) { *(output + c) = *(&string->firstByte + n); if (c > last) last = c; } return last; } /** * Sets the characters of the nodes in the worksets relevant nodes pointer. * @param ws pointer to the workset being used for the match */ void setRelevantNodes(fiftyoneDegreesWorkset *ws) { int32_t index, lastPosition, last = -1; for(index = 0; index < ws->nodeCount; index++) { lastPosition = setNodeString(ws->dataSet, *(ws->nodes + index), ws->relevantNodes); if (lastPosition > last) last = lastPosition; } /* Null terminate the string */ *(ws->relevantNodes + last + 1) = 0; } /** * Sets the characters of the signature returned from the match. * @param ws pointer to the workset being used for the match * @param signature pointer to the signature being set for the match */ void setMatchSignature(fiftyoneDegreesWorkset *ws, const byte *signature) { int32_t index, lastPosition, last = 0, profileIndex; int32_t *signatureNodeOffsets = getNodeOffsetsFromSignature(ws->dataSet, signature); int32_t *signatureProfiles = getProfileOffsetsFromSignature(signature); ws->signature = (byte*)signature; ws->profileCount = 0; for(index = 0; index < ws->dataSet->header.signatureProfilesCount; index++) { profileIndex = *(signatureProfiles + index); if (profileIndex >= 0) { *(ws->profiles + index) = (fiftyoneDegreesProfile*)(ws->dataSet->profiles + profileIndex); ws->profileCount++; } } /* Set the closest nodes string from the signature found */ for(index = 0; index < ws->dataSet->header.signatureNodesCount && *(signatureNodeOffsets + index) >= 0; index++) { lastPosition = setNodeString(ws->dataSet, (fiftyoneDegreesNode*)(ws->dataSet->nodes + *(signatureNodeOffsets + index)), ws->closestNodes); if (lastPosition > last) last = lastPosition; } *(ws->closestNodes + last + 1) = 0; } /** * Sets the signature returned for the match. * @param ws pointer to the work set * @param signatureIndex of the signature being set for the match result */ void setMatchSignatureIndex(fiftyoneDegreesWorkset *ws, int32_t signatureIndex) { setMatchSignature(ws, getSignatureByIndex(ws->dataSet, signatureIndex)); } /** * If a match can't be found this function sets the default profiles for each * component type. * @param ws pointer to the work set */ void setMatchDefault(fiftyoneDegreesWorkset *ws) { int32_t index; int32_t profileOffset; ws->profileCount = 0; for (index = 0; index < ws->dataSet->header.components.count; index++) { profileOffset = (ws->dataSet->components + index)->defaultProfileOffset; *(ws->profiles + index) = (fiftyoneDegreesProfile*)(ws->dataSet->profiles + profileOffset); ws->profileCount++; } /* Default the other values as no data available */ ws->signature = NULL; *ws->closestNodes = 0; } /** * Moves the next character position index to the right most character * position for evaluation. * @param ws pointer to the workset used for the match */ void resetNextCharacterPositionIndex(fiftyoneDegreesWorkset *ws) { ws->nextCharacterPositionIndex = ws->targetUserAgentArrayLength < ws->dataSet->header.rootNodes.count ? (int16_t)ws->targetUserAgentArrayLength - 1 : (int16_t)ws->dataSet->header.rootNodes.count -1; } /** * Returns the integer number at the start index of the array provided. The * characters at that position must have already been checked to ensure * they're numeric. * @param array pointer to the start of a byte array of characters * @param start index of the first character to convert to a number * @param length of the characters from start to conver to a number * @return the numeric integer of the characters specified */ int16_t getNumber(const byte *array, int32_t start, int32_t length) { int32_t i, p; int16_t value = 0; for (i = start + length - 1, p = 0; i >= start && p < POWERS_COUNT; i--, p++) { value += POWERS[p] * (array[i] - (byte)'0'); } return value; } /** * Sets the stats target field to the numeric value of the current position in * the target user agent. If no numeric value is available the field remains * unaltered. * @param ws pointer to the work set used for the match * @param node pointer to the node being evaluated * @param state of the numeric node evaluation * @return the number of bytes from the target user agent needed to form a number */ int32_t getCurrentPositionAsNumeric(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node, fiftyoneDegreesNumericNodeState *state) { // Find the left most numeric character from the current position. int32_t index = node->position; while (index >= 0 && *(ws->targetUserAgentArray + index) >= (byte)'0' && *(ws->targetUserAgentArray + index) <= (byte)'9') index--; // If numeric characters were found then return the number. if (index < node->position) { state->target = getNumber( ws->targetUserAgentArray, index + 1, node->position - index); } else { state->target = SHRT_MIN; } return node->position - index; } /** * Determines the integer ranges that can be compared to the target. * @param state whose range field needs to be set */ void setRange(fiftyoneDegreesNumericNodeState *state) { int32_t index; for(index = 0; index < RANGES_COUNT; index++) { if (state->target >= RANGES[index].lower && state->target < RANGES[index].upper) { state->range = &RANGES[index]; } } } /** * Searches the numeric children using a binary search for the states target * provided. If a match can't be found the position to insert the target is * returned. * @param node pointer whose numeric children are to searched * @param state pointer for the numeric evaluation * @return the index of the target or twos compliment of insertion point */ int32_t binarySearchNumericChildren(const fiftyoneDegreesNode *node, fiftyoneDegreesNumericNodeState *state) { int16_t lower = 0, upper = node->numericChildrenCount - 1, middle, comparisonResult; while (lower <= upper) { middle = lower + (upper - lower) / 2; comparisonResult = (state->firstNodeNumericIndex + middle)->value - state->target;; if (comparisonResult == 0) return middle; else if (comparisonResult > 0) upper = middle - 1; else lower = middle + 1; } return ~lower; } /** * Configures the state ready to evaluate the numeric nodes in order of * difference from the target. * @param node pointer whose numeric indexes are to be evaluated * @param data pointer to the state settings used for the evaluation */ void setNumericNodeState(const fiftyoneDegreesNode *node, fiftyoneDegreesNumericNodeState *state) { if (state->target >= 0 && state->target <= SHRT_MAX) { setRange(state); state->node = node; state->firstNodeNumericIndex = getFirstNumericIndexForNode(node); // Get the index in the ordered list to start at. state->startIndex = binarySearchNumericChildren(node, state); if (state->startIndex < 0) state->startIndex = ~state->startIndex - 1; state->lowIndex = state->startIndex; state->highIndex = state->startIndex + 1; // Determine if the low and high indexes are in range. state->lowInRange = state->lowIndex >= 0 && state->lowIndex < node->numericChildrenCount && (state->firstNodeNumericIndex + state->lowIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->lowIndex)->value < state->range->upper; state->highInRange = state->highIndex < node->numericChildrenCount && state->highIndex >= 0 && (state->firstNodeNumericIndex + state->lowIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->lowIndex)->value < state->range->upper; } } /** * The iterator function used to return the next numeric node index for * the evaluation for the state provided. * @param state settings for the evalution * @return NULL if no more indexes are available, or the next index */ const fiftyoneDegreesNodeNumericIndex* getNextNumericNode(fiftyoneDegreesNumericNodeState *state) { int32_t lowDifference, highDifference; const fiftyoneDegreesNodeNumericIndex *nodeNumericIndex = NULL; if (state->lowInRange && state->highInRange) { // Get the differences between the two values. lowDifference = abs((state->firstNodeNumericIndex + state->lowIndex)->value - state->target); highDifference = abs((state->firstNodeNumericIndex + state->highIndex)->value - state->target); // Favour the lowest value where the differences are equal. if (lowDifference <= highDifference) { nodeNumericIndex = (state->firstNodeNumericIndex + state->lowIndex); // Move to the next low index. state->lowIndex--; state->lowInRange = state->lowIndex >= 0 && (state->firstNodeNumericIndex + state->lowIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->lowIndex)->value < state->range->upper; } else { nodeNumericIndex = (state->firstNodeNumericIndex + state->highIndex); // Move to the next high index. state->highIndex++; state->highInRange = state->highIndex < state->node->numericChildrenCount && (state->firstNodeNumericIndex + state->highIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->highIndex)->value < state->range->upper; } } else if (state->lowInRange) { nodeNumericIndex = (state->firstNodeNumericIndex + state->lowIndex); // Move to the next low index. state->lowIndex--; state->lowInRange = state->lowIndex >= 0 && (state->firstNodeNumericIndex + state->lowIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->lowIndex)->value < state->range->upper; } else if (state->highInRange) { nodeNumericIndex = (state->firstNodeNumericIndex + state->highIndex); // Move to the next high index. state->highIndex++; state->highInRange = state->highIndex < state->node->numericChildrenCount && (state->firstNodeNumericIndex + state->highIndex)->value >= state->range->lower && (state->firstNodeNumericIndex + state->highIndex)->value < state->range->upper; } return nodeNumericIndex; } /** * Gets a complete numeric leaf node for the node provided if one exists. * @param ws pointer to the work set used for the match * @param node pointer to be evaluated against the current position * @return pointer to the complete node found, or NULL if no node exists */ const fiftyoneDegreesNode* getCompleteNumericNode(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { const fiftyoneDegreesNode *foundNode = NULL, *nextNode = getNextNode(ws, node); const fiftyoneDegreesNodeNumericIndex *nodeNumericIndex; int32_t difference; fiftyoneDegreesNumericNodeState state; // Check to see if there's a next node which matches // exactly. if (nextNode != NULL) foundNode = getCompleteNumericNode(ws, nextNode); if (foundNode == NULL && node->numericChildrenCount > 0) { // No. So try each of the numeric matches in ascending order of // difference. if (getCurrentPositionAsNumeric(ws, node, &state) > 0 && state.target >= 0) { setNumericNodeState(node, &state); nodeNumericIndex = getNextNumericNode(&state); while (nodeNumericIndex != NULL) { foundNode = getCompleteNumericNode(ws, getNodeByOffset(ws->dataSet, nodeNumericIndex->relatedNodeOffset)); if (foundNode != NULL) { difference = abs(state.target - nodeNumericIndex->value); ws->difference += difference; break; } nodeNumericIndex = getNextNumericNode(&state); } } } if (foundNode == NULL && getIsNodeComplete(node)) foundNode = node; return foundNode; } /** * Passed two nodes and determines if their character positions overlap * @param a the first node to test * @param b the second node to test * @return true if they overlap, otherwise false */ fiftyoneDegreesBool areNodesOverlapped(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesNode *a, const fiftyoneDegreesNode *b) { const fiftyoneDegreesNode *lower = a->position < b->position ? a : b, *higher = lower == b ? a : b, *rootNode = getRootNode(dataSet, lower); if (lower->position == higher->position || rootNode->position > higher->position) { return 1; } return 0; } /** * Determines if the node overlaps any nodes already in the workset. * @param node pointer to be checked * @param ws pointer to the work set used for the match * @return 1 if the node overlaps, otherwise 0 */ fiftyoneDegreesBool isNodeOverlapped(const fiftyoneDegreesNode *node, fiftyoneDegreesWorkset *ws) { const fiftyoneDegreesNode *currentNode; int index; for(index = ws->nodeCount - 1; index >= 0; index--) { currentNode = *(ws->nodes + index); if (currentNode == node || areNodesOverlapped(ws->dataSet, node, currentNode) == 1) { return 1; } } return 0; } /** * Evaluates the target user agent for a numeric match. * @param ws pointer to the work set being used for the match */ void evaluateNumeric(fiftyoneDegreesWorkset *ws) { int32_t existingNodeIndex = 0; const fiftyoneDegreesNode *node; resetNextCharacterPositionIndex(ws); ws->difference = 0; while (ws->nextCharacterPositionIndex > 0 && ws->nodeCount < ws->dataSet->header.signatureNodesCount) { if (existingNodeIndex >= ws->nodeCount || getRootNode(ws->dataSet, *(ws->nodes + existingNodeIndex))->position < ws->nextCharacterPositionIndex) { ws->rootNodesEvaluated++; node = getCompleteNumericNode(ws, *((ws->dataSet->rootNodes) + ws->nextCharacterPositionIndex)); if (node != NULL && isNodeOverlapped(node, ws) == 0) { // Insert the node and update the existing index so that // it's the node to the left of this one. existingNodeIndex = insertNodeIntoWorkSet(ws, node) + 1; // Move to the position of the node found as // we can't use the next node incase there's another // not part of the same signatures closer. ws->nextCharacterPositionIndex = node->position; } else { ws->nextCharacterPositionIndex--; } } else { // The next position to evaluate should be to the left // of the existing node already in the list. ws->nextCharacterPositionIndex = (*(ws->nodes + existingNodeIndex))->position; // Swap the existing node for the next one in the list. existingNodeIndex++; } } } /** * Enumerates the nodes signature indexes updating the frequency counts in the * linked list for any that exist already, adding those that still stand a chance * of making the count, or removing those that aren't necessary. * @param ws pointer to the work set used for the match * @param node pointer to the node whose signatures are to be added * @param count the current count that is needed to be considered * @param iteration the iteration that we're currently in * @return the count after the node has been evaluated */ int32_t setClosestSignaturesForNode(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node, int32_t count, int32_t iteration) { fiftyoneDegreesBool thresholdReached = (ws->nodeCount - iteration) < count; fiftyoneDegreesLinkedSignatureList *linkedList = &(ws->linkedSignatureList); fiftyoneDegreesLinkedSignatureListItem *current = linkedList->first, *next; int32_t index = 0; int32_t *firstRankedSignatureIndex = getFirstRankedSignatureIndexForNode(node), *currentRankedSignatureIndex; while (index < node->signatureCount && current != NULL) { currentRankedSignatureIndex = firstRankedSignatureIndex + index; if (current->rankedSignatureIndex > *currentRankedSignatureIndex) { // The base list is higher than the target list. Add the element // from the target list and move to the next element in each. if (thresholdReached == 0) linkedListAddBefore(linkedList, current, *currentRankedSignatureIndex); index++; } else if (current->rankedSignatureIndex < *currentRankedSignatureIndex) { if (thresholdReached) { // Threshold reached so we can removed this item // from the list as it's not relevant. next = current->next; if (current->frequency < count) linkedListRemove(linkedList, current); current = next; } else { current = current->next; } } else { // They're the same so increase the frequency and move to the next // element in each. current->frequency++; if (current->frequency > count) count = current->frequency; index++; current = current->next; } } if (thresholdReached == 0) { // Add any signature indexes higher than the base list to the base list. while (index < node->signatureCount) { linkedListAdd(linkedList, *(firstRankedSignatureIndex + index)); index++; } } return count; } /** * Orders the nodes so that those with the lowest rank are are the top of the * list. * @param ws pointer to the work set being used for the match * @param count frequency below which signatures should be removed */ void setClosestSignaturesFinal(fiftyoneDegreesWorkset *ws, int32_t count) { fiftyoneDegreesLinkedSignatureList *linkedList = &(ws->linkedSignatureList); fiftyoneDegreesLinkedSignatureListItem *current = linkedList->first; /* First iteration to remove any items with lower than the maxcount. */ while (current != NULL) { if (current->frequency < count) { linkedListRemove(linkedList, current); } current = current->next; } } /** * Compares the signature counts of two nodes for the purposes of ordering * them in ascending order of count. * @param a pointer to the first node * @param b pointer to the second node * @return the difference between the nodes */ int nodeSignatureCountCompare (const void * a, const void * b) { return (*(fiftyoneDegreesNode**)a)->signatureCount - (*(fiftyoneDegreesNode**)b)->signatureCount; } /** * Orders the nodes found in ascending order of signature count. * @param ws pointer to the work set being used for the match */ void orderNodesOnSignatureCount(fiftyoneDegreesWorkset *ws) { memcpy((void*)ws->orderedNodes, ws->nodes, ws->nodeCount * sizeof(fiftyoneDegreesNode*)); qsort((void*)ws->orderedNodes, ws->nodeCount, sizeof(fiftyoneDegreesNode*), nodeSignatureCountCompare); } /** * Fills the workset with those signatures that are closest to the target user * agent. This is required before the NEAREST and CLOSEST methods are used to * determine which signature is in fact closest. * @param ws pointer to the work set being used for the match */ void fillClosestSignatures(fiftyoneDegreesWorkset *ws) { int32_t iteration = 2, maxCount = 1, nodeIndex = 1; const fiftyoneDegreesNode *node; if (ws->nodeCount == 1) { // No need to create a linked list as only 1 node. ws->closestSignatures = ws->nodes[0]->signatureCount; } else { // Order the nodes in ascending order of signature index length. orderNodesOnSignatureCount(ws); // Get the first node and add all the signature indexes. node = *(ws->orderedNodes); buildInitialList(ws, node); // Count the number of times each signature index occurs. while (nodeIndex < ws->nodeCount) { node = *(ws->orderedNodes + nodeIndex); maxCount = setClosestSignaturesForNode( ws, node, maxCount, iteration); iteration++; nodeIndex++; } // Remove any signatures under the max count and order the // remainder in ascending order of Rank. setClosestSignaturesFinal(ws, maxCount); ws->closestSignatures = ws->linkedSignatureList.count; } } /** * Determines if a byte value is a numeric character. * @param value to be checked * @return 1 if the value is numeric, otherwise 0 */ fiftyoneDegreesBool getIsNumeric(byte *value) { return (*value >= (byte)'0' && *value <= (byte)'9'); } /** * Works out the numeric difference between the current position and the target. * @param characters pointer to the ascii string of the node * @param ws pointer to the work set used for the match * @param nodeIndex pointer to the index in the node being evaluated * @param targetIndex pointer to the target user agent index * @return the absolute difference between the characters or 0 if not numeric */ int32_t calculateNumericDifference(const fiftyoneDegreesAsciiString *characters, fiftyoneDegreesWorkset *ws, int32_t *nodeIndex, int32_t *targetIndex) { // Move right when the characters are numeric to ensure // the full number is considered in the difference comparison. int32_t newNodeIndex = *nodeIndex + 1; int32_t newTargetIndex = *targetIndex + 1; int16_t count = 0; while (newNodeIndex < characters->length && newTargetIndex < ws->targetUserAgentArrayLength && getIsNumeric(ws->targetUserAgentArray + newTargetIndex) && getIsNumeric((byte*)(&(characters->firstByte) + newNodeIndex))) { newNodeIndex++; newTargetIndex++; } (*nodeIndex) = newNodeIndex - 1; (*targetIndex) = newTargetIndex - 1; // Find when the characters stop being numbers. while ( nodeIndex >= 0 && getIsNumeric(ws->targetUserAgentArray + *targetIndex) && getIsNumeric((byte*)(&(characters->firstByte) + *nodeIndex))) { (*nodeIndex)--; (*targetIndex)--; count++; } // If there is more than one character that isn't a number then // compare the numeric values. if (count > 1) { return abs( getNumber(ws->targetUserAgentArray, *targetIndex + 1, count) - getNumber(&(characters->firstByte), *nodeIndex + 1, count)); } return 0; } /** * The index of the nodes characters in the target user agent. * @param ws pointer to the work set used for the match * @param node pointer to the node to be checked in the target * @return index in the target user agent of the nodes characters, or -1 if * not present */ int16_t matchIndexOf(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { const fiftyoneDegreesAsciiString *characters = fiftyoneDegreesGetString(ws->dataSet, node->characterStringOffset); int16_t index, nodeIndex, targetIndex, finalNodeIndex = characters->length - 2, charactersLength = characters->length - 1; for (index = 0; index < ws->targetUserAgentArrayLength - charactersLength; index++) { for (nodeIndex = 0, targetIndex = index; nodeIndex < charactersLength && targetIndex < ws->targetUserAgentArrayLength; nodeIndex++, targetIndex++) { if (*(&(characters->firstByte) + nodeIndex) != *(ws->targetUserAgent + targetIndex)) { break; } else if (nodeIndex == finalNodeIndex) { return index; } } } return -1; } /** * Used to determine if the node is in the target user agent and if so how * many character positions different it is. * @param ws pointer to the workset used for the match * @param node pointer to be checked against the target user agent * @return the difference in character positions or -1 if not present. */ int32_t getScoreNearest(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { int16_t index = matchIndexOf(ws, node); if (index >= 0) { return abs(node->position + 1 - index); } // Return -1 to indicate that a score could not be calculated. return -1; } /** * Compares the node against the target user agent on a character by characters * basis. * @param ws pointer to the work set used for the current match * @param node pointer to the node being compared * @return the difference based on character comparisons between the two */ int32_t getScoreClosest(fiftyoneDegreesWorkset *ws, const fiftyoneDegreesNode *node) { const fiftyoneDegreesAsciiString *characters = getNodeCharacters(ws->dataSet, node); int32_t score = 0; int32_t difference; int32_t numericDifference; int32_t nodeIndex = characters->length - 2; int32_t targetIndex = node->position + characters->length - 1; // Adjust the score and indexes if the node is too long. if (targetIndex >= ws->targetUserAgentArrayLength) { score = targetIndex - ws->targetUserAgentArrayLength; nodeIndex -= score; targetIndex = ws->targetUserAgentArrayLength - 1; } while (nodeIndex >= 0 && score < ws->difference) { difference = abs( *(ws->targetUserAgentArray + targetIndex) - *(&(characters->firstByte) + nodeIndex)); if (difference != 0) { numericDifference = calculateNumericDifference( characters, ws, &nodeIndex, &targetIndex); if (numericDifference != 0) score += numericDifference; else score += (difference * 10); } nodeIndex--; targetIndex--; } return score; } /** * Calculates the score for difference score for the signature. * @param ws pointer to the workset used for the match * @param signature pointer to the signature to be compared * @param lastNodeCharacter position of the right most character in the * signature * @return the difference score using the active scoring method between the * signature and the target user agent */ int32_t getScore(fiftyoneDegreesWorkset *ws, const byte *signature, int16_t lastNodeCharacter) { int32_t *nodeOffsets = getNodeOffsetsFromSignature(ws->dataSet, signature); int32_t count = getSignatureNodeOffsetsCount(ws->dataSet, nodeOffsets), runningScore = ws->startWithInitialScore == 1 ? abs(lastNodeCharacter + 1 - getSignatureLengthFromNodeOffsets(ws->dataSet, *(nodeOffsets + count - 1))) : 0, matchNodeIndex = ws->nodeCount - 1, signatureNodeIndex = 0, matchNodeOffset, signatureNodeOffset, score; while (signatureNodeIndex < count && runningScore < ws->difference) { matchNodeOffset = matchNodeIndex < 0 ? INT32_MAX : getNodeOffsetFromNode(ws->dataSet, *(ws->nodes + matchNodeIndex)); signatureNodeOffset = *(nodeOffsets + signatureNodeIndex); if (matchNodeOffset > signatureNodeOffset) { // The matched node is either not available, or is higher than // the current signature node. The signature node is not contained // in the match so we must score it. score = ws->functionPtrGetScore(ws, getNodeByOffset(ws->dataSet, signatureNodeOffset)); // If the score is less than zero then a score could not be // determined and the signature can't be compared to the target // user agent. Exit with a high score. if (score < 0) return INT32_MAX; runningScore += score; signatureNodeIndex++; } else if (matchNodeOffset == signatureNodeOffset) { // They both are the same so move to the next node in each. matchNodeIndex--; signatureNodeIndex++; } else if (matchNodeOffset < signatureNodeOffset) { // The match node is lower so move to the next one and see if // it's higher or equal to the current signature node. matchNodeIndex--; } } return runningScore; } /** * Evaluates a signature using the active scoring method. * @param ws pointer to the work set used for the match * @param signature pointer to be compared to the target user agent * @param lastNodeCharacter position of the right most node character in the * signature */ void evaluateSignature(fiftyoneDegreesWorkset *ws, const byte *signature, int16_t lastNodeCharacter) { // Get the score between the target and the signature stopping if it's // going to be larger than the lowest score already found. int32_t score = getScore(ws, signature, lastNodeCharacter); ws->signaturesCompared++; // If the score is lower than the current lowest then use this signature. if (score < ws->difference) { ws->difference = score; ws->signature = (byte*)signature; } } /** * Gets the next signature to be examined for the single node found. * @param ws the current work set for the match. * @return null if there are no more signature pointers. */ const byte* getNextClosestSignatureForSingleNode(fiftyoneDegreesWorkset *ws) { const byte *signature; if (ws->closestNodeRankedSignatureIndex < ws->nodes[0]->signatureCount) { signature = getSignatureByRankedIndex(ws->dataSet, *(getFirstSignatureIndexForNode(ws->nodes[0]) + ws->closestNodeRankedSignatureIndex)); ws->closestNodeRankedSignatureIndex++; } else { signature = NULL; } return signature; } /** * Gets the next signature to be examined from the linked list. * @param ws the current work set for the match. * @return null if there are no more signature pointers. */ const byte* getNextClosestSignatureForLinkedList(fiftyoneDegreesWorkset *ws) { const byte *signature; if (ws->linkedSignatureList.current != NULL) { signature = getSignatureByRankedIndex(ws->dataSet, ws->linkedSignatureList.current->rankedSignatureIndex); ws->linkedSignatureList.current = ws->linkedSignatureList.current->next; } else { signature = NULL; } return signature; } /** * Resets the work set ready to return the closest signatures. * @param ws the current work set for the match. */ void resetClosestSignatureEnumeration(fiftyoneDegreesWorkset *ws) { if (ws->nodeCount == 1) { /* There's only 1 node so just iterate through it's indexes */ ws->closestNodeRankedSignatureIndex = 0; ws->functionPtrNextClosestSignature = &getNextClosestSignatureForSingleNode; } else if (ws->nodeCount > 1) { /* We'll need to walk the linked list to get the signatures */ ws->linkedSignatureList.current = ws->linkedSignatureList.first; ws->functionPtrNextClosestSignature = &getNextClosestSignatureForLinkedList; } } /** * Evaluates all the signatures that are possible candidates for the result * against the target user agent using the active method. * @param ws pointer to the work set being used for the match */ void evaluateSignatures(fiftyoneDegreesWorkset *ws) { int16_t lastNodeCharacter = getRootNode(ws->dataSet, *(ws->nodes))->position; int32_t count = 0; const byte *currentSignature; /* Setup the linked list to be navigated */ resetClosestSignatureEnumeration(ws); currentSignature = ws->functionPtrNextClosestSignature(ws); ws->difference = INT_MAX; while (currentSignature != NULL && count < ws->dataSet->header.maxSignatures) { setSignatureAsString(ws, currentSignature); evaluateSignature(ws, currentSignature, lastNodeCharacter); currentSignature = ws->functionPtrNextClosestSignature(ws); count++; } } /** * Evaluates the target user agent against root nodes to find those nodes * that match precisely. * @param ws pointer to the work set used for the match */ void evaluate(fiftyoneDegreesWorkset *ws) { const fiftyoneDegreesNode *node; while (ws->nextCharacterPositionIndex > 0 && ws->nodeCount < ws->dataSet->header.signatureNodesCount) { ws->rootNodesEvaluated++; node = getCompleteNode(ws, *(ws->dataSet->rootNodes + ws->nextCharacterPositionIndex)); if (node != NULL) { *(ws->nodes + ws->nodeCount) = node; ws->nodeCount++; ws->nextCharacterPositionIndex = node->nextCharacterPosition; } else { ws->nextCharacterPositionIndex--; } } } /** * Main entry method used for perform a match. * @param ws pointer to a work set to be used for the match created via * createWorkset function * @param userAgent pointer to the target user agent */ void fiftyoneDegreesMatch(fiftyoneDegreesWorkset *ws, char* userAgent) { int32_t signatureIndex; setTargetUserAgentArray(ws, userAgent); if (ws->targetUserAgentArrayLength >= ws->dataSet->header.minUserAgentLength) { evaluate(ws); signatureIndex = getExactSignatureIndex(ws); if (signatureIndex >= 0) { setMatchSignatureIndex(ws, signatureIndex); ws->method = EXACT; } else { evaluateNumeric(ws); signatureIndex = getExactSignatureIndex(ws); if (signatureIndex >= 0) { setMatchSignatureIndex(ws, signatureIndex); ws->method = NUMERIC; } else if (ws->nodeCount > 0) { // Find the closest signatures and compare them // to the target looking at the smallest character // difference. fillClosestSignatures(ws); ws->startWithInitialScore = 0; ws->functionPtrGetScore = &getScoreNearest; evaluateSignatures(ws); if (ws->signature != NULL) { ws->method = NEAREST; } else { ws->startWithInitialScore = 1; ws->functionPtrGetScore = &getScoreClosest; evaluateSignatures(ws); ws->method = CLOSEST; } setMatchSignature(ws, ws->signature); } } if (ws->profileCount == 0) { setMatchDefault(ws); ws->method = NONE; } setRelevantNodes(ws); } } /** * Sets the values associated with the require property index in the workset * so that an array of values can be read. * @param ws pointer to the work set associated with the match * @param requiredPropertyIndex index of the property required from the array of * require properties * @return the number of values that were set. */ int32_t fiftyoneDegreesSetValues(fiftyoneDegreesWorkset *ws, int32_t requiredPropertyIndex) { int32_t profileIndex, valueIndex; const fiftyoneDegreesProfile *profile; const fiftyoneDegreesProperty *property = *(ws->dataSet->requiredProperties + requiredPropertyIndex); int32_t *firstValueIndex; int32_t propertyIndex; const fiftyoneDegreesValue *value; ws->valuesCount = 0; if (property != NULL) { propertyIndex = getPropertyIndex(ws->dataSet, property); for(profileIndex = 0; profileIndex < ws->profileCount; profileIndex++) { profile = *(ws->profiles + profileIndex); if (profile->componentIndex == property->componentIndex) { firstValueIndex = (int32_t*)((byte*)profile + sizeof(fiftyoneDegreesProfile)); for(valueIndex = 0; valueIndex < profile->valueCount; valueIndex++) { value = ws->dataSet->values + *(firstValueIndex + valueIndex); if (value->propertyIndex == propertyIndex) { *(ws->values + ws->valuesCount) = value; ws->valuesCount++; } } } } } return ws->valuesCount; } /** * Process device properties into a CSV string */ int32_t fiftyoneDegreesProcessDeviceCSV(fiftyoneDegreesWorkset *ws, char* result, int32_t resultLength) { int32_t propertyIndex, valueIndex, profileIndex; char* currentPos = result; char* endPos = result + resultLength; if (ws->profileCount > 0) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "Id,"); for(profileIndex = 0; profileIndex < ws->profileCount; profileIndex++) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "%d", (*(ws->profiles + profileIndex))->profileId); if (profileIndex < ws->profileCount - 1) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "-"); } } currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\n"); for(propertyIndex = 0; propertyIndex < ws->dataSet->requiredPropertyCount; propertyIndex++) { if (fiftyoneDegreesSetValues(ws, propertyIndex) > 0) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "%s,", fiftyoneDegreesGetPropertyName(ws->dataSet, *(ws->dataSet->requiredProperties + propertyIndex))); for(valueIndex = 0; valueIndex < ws->valuesCount; valueIndex++) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "%s", fiftyoneDegreesGetValueName(ws->dataSet, *(ws->values + valueIndex))); if (valueIndex < ws->valuesCount - 1) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "|"); } } currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\n"); } } } return (int32_t)(currentPos - result); } /** * Process device properties into a JSON string */ int32_t fiftyoneDegreesProcessDeviceJSON(fiftyoneDegreesWorkset *ws, char* result, int32_t resultLength) { int32_t propertyIndex, valueIndex, profileIndex, valueNameIndex, valueNameLength; const char* valueName; char* currentPos = result; char* endPos = result + resultLength; if (ws->profileCount > 0) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "{\"Id\": \""); for(profileIndex = 0; profileIndex < ws->profileCount; profileIndex++) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "%d", (*(ws->profiles + profileIndex))->profileId); if (profileIndex < ws->profileCount - 1) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "-"); } } currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\",\n"); for(propertyIndex = 0; propertyIndex < ws->dataSet->requiredPropertyCount; propertyIndex++) { if (fiftyoneDegreesSetValues(ws, propertyIndex) > 0) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\"%s\": \"", fiftyoneDegreesGetPropertyName(ws->dataSet, *(ws->dataSet->requiredProperties + propertyIndex))); for(valueIndex = 0; valueIndex < ws->valuesCount; valueIndex++) { valueName = fiftyoneDegreesGetValueName(ws->dataSet, *(ws->values + valueIndex)); valueNameLength = strlen(valueName); for(valueNameIndex = 0; valueNameIndex < valueNameLength; valueNameIndex++) { if(valueName[valueNameIndex] == 0) { break; } else if(valueName[valueNameIndex] == '"') { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\\"); } currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "%c", valueName[valueNameIndex]); } if (valueIndex < ws->valuesCount - 1) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "|"); } } if (propertyIndex + 1 != ws->dataSet->requiredPropertyCount) { currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\",\n"); } } } currentPos += snprintf( currentPos, (int32_t)(endPos - currentPos), "\"}"); } return (int32_t)(currentPos - result); }
hdczsf/51degrees.go
51Degrees.c
C
bsd-2-clause
89,006
class Weight < ActiveRecord::Base belongs_to :user attr_accessible :fatrate, :time, :user_id, :weight end
kazhida/dietrec
app/models/weight.rb
Ruby
bsd-2-clause
111
#ifndef INSTR_MIPS_JTYPE_J_H_ # define INSTR_MIPS_JTYPE_J_H_ # include <instr/mips/jtype/instr.h> namespace sasm { namespace instr { namespace mips { namespace jtype { struct j : public jtype_instr { j(const sasm::elf::elf& elf, uint64 addr) : jtype_instr(elf, addr) { _name = "j"; } }; }}}} #endif /* !INSTR_MIPS_JTYPE_J_H_ */
sas/sasm
src/instr/mips/jtype/j.h
C
bsd-2-clause
341
require File.expand_path("../../Abstract/abstract-php-extension", __FILE__) class Php56Dbus < AbstractPhp56Extension init desc "Extension for interaction with DBUS busses" homepage "https://pecl.php.net/package/dbus" url "https://pecl.php.net/get/dbus-0.1.1.tgz" sha256 "018ce17ceb18bd7085f7151596835b09603140865a49c76130b77e00bc7fcdd7" head "http://svn.php.net/repository/pecl/dbus/trunk/" bottle do revision 1 sha256 "710dbaf6700047d10714a758333233fd801a6048a44cd187bb12f4550721578b" => :el_capitan sha256 "be9a633616809cbe71b0a8bf6c6ba0d7bc794ee2bc7cd454ec59a4f7e167bd3f" => :yosemite sha256 "4df2daf222f3fc9f46e11a91f1960aefcbfbf412ed262b711e56a8f4051b00ed" => :mavericks end depends_on "pkg-config" => :build depends_on "d-bus" => :build def install Dir.chdir "dbus-#{version}" unless build.head? safe_phpize system "./configure", "--prefix=#{prefix}", phpconfig system "make" prefix.install "modules/dbus.so" write_config_file if build.with? "config-file" end end
TomK/homebrew-php
Formula/php56-dbus.rb
Ruby
bsd-2-clause
1,039
/** * The controls module exports the following directives: * {{#crossLink "SliderDirective"}}{{/crossLink}} * {{#crossLink "PlayerComponent"}}{{/crossLink}} * {{#crossLink "CascadeSelectComponent"}}{{/crossLink}} * * @module controls * @main controls */ import { NgModule } from '@angular/core'; import { CommonModule as NgCommonModule } from '@angular/common'; import { SliderDirective } from './slider.directive.ts'; import { PlayerComponent } from './player.component.ts'; import { CascadeSelectComponent } from './cascade-select.component.ts'; const DIRECTIVES = [ SliderDirective, PlayerComponent, CascadeSelectComponent ]; @NgModule({ imports: [NgCommonModule], declarations: DIRECTIVES, exports: DIRECTIVES }) /** * The controls module metadata. * * @module controls * @class ControlsModule */ export class ControlsModule { }
ohsu-qin/qiprofile
src/controls/controls.module.ts
TypeScript
bsd-2-clause
860
#ifndef DATE_H #define DATE_H #include <time.h> #include "macros/macros.h" namespace net { namespace internet { namespace http { class date { public: static time_t parse(const void* buf, size_t len, struct tm& timestamp); static time_t parse(const void* buf, size_t len); private: static time_t parse_ansic(const unsigned char* begin, const unsigned char* end, struct tm& timestamp); static bool parse_year(const unsigned char* ptr, unsigned& year); static bool parse_month(const unsigned char* ptr, unsigned& mon); static bool parse_time(const unsigned char* ptr, unsigned& hour, unsigned& min, unsigned& sec); }; } } } inline time_t net::internet::http::date::parse(const void* buf, size_t len) { struct tm timestamp; return parse(buf, len, timestamp); } inline bool net::internet::http::date::parse_year(const unsigned char* ptr, unsigned& year) { if ((!IS_DIGIT(*ptr)) || (!IS_DIGIT(*(ptr + 1))) || (!IS_DIGIT(*(ptr + 2))) || (!IS_DIGIT(*(ptr + 3)))) { return false; } year = ((*ptr - '0') * 1000) + ((*(ptr + 1) - '0') * 100) + ((*(ptr + 2) - '0') * 10) + (*(ptr + 3) - '0'); return (year >= 1970); } #endif // DATE_H
guidoreina/gsniffer
net/internet/http/date.h
C
bsd-2-clause
1,189
/* Copyright (c) 2017, John Lewin 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; namespace MatterHackers.MatterControl.Library { public class SDCardFileItem : ILibraryItem { public DateTime DateCreated { get; } = DateTime.Now; public DateTime DateModified { get; } = DateTime.Now; public string ID { get; } = Guid.NewGuid().ToString(); public bool IsProtected { get; } = true; public bool IsVisible { get; } = true; private string _name; public string Name { get => _name; set { if (_name != value) { _name = value; NameChanged?.Invoke(this, EventArgs.Empty); } } } public event EventHandler NameChanged; } }
larsbrubaker/MatterControl
MatterControlLib/Library/Providers/Printer/SDCardFileItem.cs
C#
bsd-2-clause
2,122
<?php include_once('AutoLoader.php'); // Register the directory to your include files AutoLoader::registerDirectory('app'); // composer autoloader require_once 'lib/vendor/composer/autoload.php'; require_once 'lib/vendor/composer/hamcrest/hamcrest-php/hamcrest/Hamcrest.php';
tomslabs/sonar-review-creator
test/phpunit/_framework/bootstrap.php
PHP
bsd-2-clause
278
<!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/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>MFINAppPurchaseManager: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="mf_icon.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">MFINAppPurchaseManager &#160;<span id="projectnumber">1.0</span> </div> <div id="projectbrief">A class used to enable In-App Purchases on TVML-based tvOS applications</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('interface_m_f_in_app_purchase_manager.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">MFInAppPurchaseManager Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#aa7f209dbd5eec691c2eea884e179b571">_availableProducts</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#abce6a486f27b97df2d722f984a69ad4a">_errors</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#abc1500dd38a90dc555017cb6655af3ef">_hasBoughtPremium</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#a2a4d2385f2d52d0e7ae5fd9cba86b33d">_productIDs</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#ae874124cd4868f108e31842e2f7d3402">_productRequestWasMade</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#a0998aa8bae334a5bce59eb2ea127a051">_products</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#a1bde01365756e105bc5ea183d5e21222">_productsHaveBeenRestored</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#a0d584c553714d0b5ac9ef290fa16332c">_purchasedProducts</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#ad04c8e03d42d77cffcf9b964d05f707b">_requests</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr><td class="entry"></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html#a9dd695e8f9e7ebfeedbf1cda51be8842">_transactionInProgress</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"><span class="mlabel">protected</span></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#acdcea7c136dec1bd41558646d0542221">availableProducts</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a5b2f35dc03400d0fa72c17d9ef3e8f1f">buyProduct:</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#ad634975a0a1d3060da54fa2076e1e409">errors</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#abd2710d7f7bc36b69ed138cb25be2083">hasPurchasedProductWithID:</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="interface_m_f_in_app_purchase_manager.html#a0b43f4661084f8ee21edb886c88afcc7">initWithProductIDs:</a></td><td class="entry"><a class="el" href="interface_m_f_in_app_purchase_manager.html">MFInAppPurchaseManager</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a315eba048982f99135fb30cc80bc65ed">productRequestWasMade</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a3f8c54ff0c69d9dcd29dfeb32ea55e83">products</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a67070d7d958cc93dece58c1e31db9a21">productWithID:</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a521a8291507e48d28b9c79db9f281d9b">purchasedProducts</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a45c113d74cd283f27d99814b999eaa94">purchaseProduct:</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a8778276fbcb098dec64b031f8391326b">purchaseProductWithID:</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#ac109d9fc626e2f6bc2faf3901e47a994">requestProductInfo</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#a19c1d0a3f37bc28e9efe9e249e7d86a9">restorePurchases</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> <tr><td class="entry">-&#160;</td><td><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html#adb5603d3cb021c950634cbadae025016">transactionInProgress</a></td><td class="entry"><a class="el" href="protocol_m_f_in_app_purchase_manager_java_script_methods-p.html">&lt;MFInAppPurchaseManagerJavaScriptMethods&gt;</a></td><td class="entry"></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated on Mon Oct 26 2015 11:53:20 for MFINAppPurchaseManager by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
MediaflexPL/MFINAppPurchaseManager
docs/html/class_m_f_in_app_purchase_manager-members.html
HTML
bsd-2-clause
14,046
// // BaseView.h // WallpaperMaker // // Created by dd on 14/11/9. // Copyright (c) 2014年 yangxd. All rights reserved. // #import <UIKit/UIKit.h> /** * 所有view的基类 */ @interface BaseView : UIControl @end
smartdong/WallpaperMaker
WallpaperMaker/WallpaperMaker/ViewController/Base/BaseView.h
C
bsd-2-clause
224
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="packages/react/react_with_addons.js"></script> <script src="packages/react/react_dom.js"></script> <link rel="x-dart-test" href="js_dev_with_addons_test.dart"> <script src="packages/test/dart.js"></script> </head> <body> </body> </html>
evanweible-wf/react-dart
test/js_interop_helpers_test/js_dev_with_addons_test.html
HTML
bsd-2-clause
355
<!DOCTYPE html> <html> <head> <title>Hello World!</title> <!-- cssmin and uglify are configured to not discart special comments. So you can include raw versions of library files during development, then they can be minified for production with their copyrights preserved, so that you won't violate their licenses. Alternatively, you can use htmlrefs to replace library files to their pre-minified versions. --> <!-- build:css css/libs.css --> <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.css"> <!-- endbuild --> <!-- build:js js/libs.js --> <script src="../bower_components/jquery/jquery.js"></script> <script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script> <!-- endbuild --> <!-- Any .less or .sass files will be automatically compiled. --> <!-- build:css css/main.css --> <link rel="stylesheet/less" href="css/sample.less"> <!-- endbuild --> <!-- Source maps for all JavaScript files (including library files) will be built for QA build. All the generation and linking are taken care of. --> <!-- build:js js/main.js --> <script src="config/config.js"></script> <script src="js/sample.js"></script> <!-- endbuild --> <!-- htmlrefs is performed BEFORE useminPrepare. So you can use htmlrefs to do some magic to influence usemin or perform htmlrefs features like replaceing and/or removing tags for QA or production. --> <!-- ref:remove --> <script type="text/javascript">var less=less||{};less.env='development';</script> <script src="../bower_components/less/dist/less-1.5.1.min.js"></script> <!-- endref --> </head> <body> <div> Hello World! </div> </body> </html>
initialxy/webapp-annotated-build-scaffolding
src/index.html
HTML
bsd-2-clause
1,977
/* * Copyright 2013-2017 Jonathan Vasquez <[email protected]> * * 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 HOLDER 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. */ package com.vasquez.Windows; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class AboutWindow extends JDialog { public AboutWindow(JFrame mainWindow, String name, String version, String releaseDate, String author, String contact, String license) { super(mainWindow, "About", Dialog.ModalityType.DOCUMENT_MODAL); // Set window properties setDefaultCloseOperation(DISPOSE_ON_CLOSE); setResizable(false); // Bring in the table manager and entry table resources this.name = name; this.version = version; this.releaseDate = releaseDate; this.author = author; this.contact = contact; this.license = license; // Create components and listeners JButton close = new JButton("Close"); close.addActionListener(new CloseListener()); JLabel nameL = new JLabel("Name:"); JLabel versionL = new JLabel("Version:"); JLabel releaseDateL = new JLabel("Released:"); JLabel authorL = new JLabel("Author:"); JLabel contactL = new JLabel("Contact:"); JLabel licenseL = new JLabel("License:"); JTextField nameTF = new JTextField(name); JTextField versionTF = new JTextField(version); JTextField releaseDateTF = new JTextField(releaseDate); JTextField authorTF = new JTextField(author); JTextField contactTF = new JTextField(contact); JTextField licenseTF = new JTextField(license); // Create the layout and add the components to their respective places JPanel centerPanel = new JPanel(new GridLayout(6,2)); JPanel southPanel = new JPanel(new GridLayout(1,2)); southPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); centerPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10)); getContentPane().add(BorderLayout.CENTER, centerPanel); getContentPane().add(BorderLayout.SOUTH, southPanel); southPanel.add(close); centerPanel.add(nameL); centerPanel.add(nameTF); centerPanel.add(versionL); centerPanel.add(versionTF); centerPanel.add(releaseDateL); centerPanel.add(releaseDateTF); centerPanel.add(authorL); centerPanel.add(authorTF); centerPanel.add(contactL); centerPanel.add(contactTF); centerPanel.add(licenseL); centerPanel.add(licenseTF); } private class CloseListener implements ActionListener { public void actionPerformed(ActionEvent ev) { dispose(); } } private String name; private String version; private String releaseDate; private String author; private String contact; private String license; }
fearedbliss/Bliss-Version-Switcher
src/com/vasquez/Windows/AboutWindow.java
Java
bsd-2-clause
4,545
package net.minecraft.src; public class ItemMagmaCreamCornNuts extends ItemFood { public ItemMagmaCreamCornNuts(int par1, int par2, float par3, boolean par4) { super(par1, par2, par3, par4); this.setPotionEffect(Potion.fireResistance.id, 600, 0, 0.6f); } }
KinyoshiMods/Corn-Nuts
ItemMagmaCreamCornNuts.java
Java
bsd-2-clause
286
class Mecab < Formula desc "Yet another part-of-speech and morphological analyzer" homepage "https://taku910.github.io/mecab/" # Canonical url is https://drive.google.com/uc?export=download&id=0B4y35FiV1wh7cENtOXlicTFaRUE url "https://deb.debian.org/debian/pool/main/m/mecab/mecab_0.996.orig.tar.gz" sha256 "e073325783135b72e666145c781bb48fada583d5224fb2490fb6c1403ba69c59" bottle do rebuild 3 sha256 "dba6306bcd5ddb9a824cb366b5432a036889440f2253634c99410fbb0abe0047" => :catalina sha256 "ef261d203140305ca8c9e4b7311c61176a17325df9454610d3eb33a312c4d3c5" => :mojave sha256 "d48340df17075e4a6237ffb87306a42566f8eabb736c546d790586266758f387" => :high_sierra sha256 "d98686ec62189de50f6ed5b7e682d59b90239c8dfd08cf32fd23543466586232" => :sierra sha256 "03df92bdd092065a7cbca5953a0e352c16cadfff5c9f186bbe1ee882258e56d3" => :el_capitan sha256 "4cff10addb8895df884fca8d81cd4d4c7530efdac45896299d85ab707a80cf4f" => :x86_64_linux end conflicts_with "mecab-ko", because: "both install mecab binaries" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--sysconfdir=#{etc}" system "make", "install" # Put dic files in HOMEBREW_PREFIX/lib instead of lib inreplace "#{bin}/mecab-config", "${exec_prefix}/lib/mecab/dic", "#{HOMEBREW_PREFIX}/lib/mecab/dic" inreplace "#{etc}/mecabrc", "#{lib}/mecab/dic", "#{HOMEBREW_PREFIX}/lib/mecab/dic" end def post_install (HOMEBREW_PREFIX/"lib/mecab/dic").mkpath end test do assert_equal "#{HOMEBREW_PREFIX}/lib/mecab/dic", shell_output("#{bin}/mecab-config --dicdir").chomp end end
rwhogg/homebrew-core
Formula/mecab.rb
Ruby
bsd-2-clause
1,688
// // Copyright (c) 2009, Zbigniew Zagorski // This software licensed under terms described in LICENSE.txt // #include "runner.h" namespace tinfra { runner::~runner() {} runnable_base::~runnable_base() {} // WTF is with this language! ? // why can't i just write // runnable runnable::EMPTY_RUNNABLE (0); // or at least // runnable runnable::EMPTY_RUNNABLE (shared_ptr<runnable_ptr>(0)); static runnable_base* foo = 0; static const shared_ptr<runnable_base> RUNNABLE_NULL(foo); runnable runnable::EMPTY_RUNNABLE (RUNNABLE_NULL ); sequential_runner::~sequential_runner() {} }; // jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:
zbigg/tinfra
tinfra/runner.cpp
C++
bsd-2-clause
657
package org.elasticsearch.plugin.geohashcellfacet; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.search.facet.FacetModule; /** * Plugin which extends ElasticSearch with a Geohash Cell facet functionality. */ public class GeoHashCellFacetPlugin extends AbstractPlugin { private final static String version = "1.0.4"; /** * Name of the plugin. * * @return Name of the plugin. */ @Override public String name() { return "gorgeo-" + version; } /** * Description of the plugin. * * @return Description of the plugin. */ @Override public String description() { return "Geohash cell facet support"; } /** * Hooks up to the FacetModule initialization and adds a new facet parser * {@link GeoHashCellFacetParser} which enables using {@link GeoHashCellFacet}. * * @param facetModule {@link FacetModule} instance */ public void onModule(FacetModule facetModule) { facetModule.addFacetProcessor(GeoHashCellFacetParser.class); } }
gornik/gorgeo
src/main/java/org/elasticsearch/plugin/geohashcellfacet/GeoHashCellFacetPlugin.java
Java
bsd-2-clause
1,091
//go:build !windows && !plan9 && !js // +build !windows,!plan9,!js package daemon import ( "os" "syscall" "testing" ) func TestProgram_QuitsOnSystemSignal_SIGINT(t *testing.T) { testProgram_QuitsOnSystemSignal(t, syscall.SIGINT) } func TestProgram_QuitsOnSystemSignal_SIGTERM(t *testing.T) { testProgram_QuitsOnSystemSignal(t, syscall.SIGTERM) } func testProgram_QuitsOnSystemSignal(t *testing.T, sig os.Signal) { t.Helper() setup(t) startServerOpts(t, cli("sock", "db"), ServeOpts{Signals: nil}) p, err := os.FindProcess(os.Getpid()) if err != nil { t.Fatalf("FindProcess: %v", err) } p.Signal(sig) // startServerOpts will wait for server to terminate at cleanup }
elves/elvish
pkg/daemon/server_unix_test.go
GO
bsd-2-clause
686
Page { background-color: #F7F4ED; } .page { margin: 10px; } Label { color: #55443B; } .input { margin: 3px; }
paveldk/TalkUpp-Repo
app/app/app.css
CSS
bsd-2-clause
128
/*********************************************************************/ /* Copyright (c) 2011 - 2012, The University of Texas at Austin. */ /* 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 UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include "ContentWindowGraphicsItem.h" #include "configuration/Configuration.h" #include "Content.h" #include "ContentWindowManager.h" #include "DisplayGroupManager.h" #include "DisplayGroupGraphicsView.h" #include "globals.h" #include "ContentInteractionDelegate.h" #include "gestures/DoubleTapGestureRecognizer.h" #include "gestures/PanGestureRecognizer.h" #include "gestures/PinchGestureRecognizer.h" qreal ContentWindowGraphicsItem::zCounter_ = 0; ContentWindowGraphicsItem::ContentWindowGraphicsItem(ContentWindowManagerPtr contentWindowManager) : ContentWindowInterface(contentWindowManager) , resizing_(false) , moving_(false) { // graphics items are movable setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemIsFocusable, true); // new items at the front // we assume that interface items will be constructed in depth order so this produces the correct result... setZToFront(); grabGesture( DoubleTapGestureRecognizer::type( )); grabGesture( PanGestureRecognizer::type( )); grabGesture( PinchGestureRecognizer::type( )); grabGesture( Qt::SwipeGesture ); grabGesture( Qt::TapAndHoldGesture ); grabGesture( Qt::TapGesture ); } ContentWindowGraphicsItem::~ContentWindowGraphicsItem() { } QRectF ContentWindowGraphicsItem::boundingRect() const { return QRectF(x_, y_, w_, h_); } void ContentWindowGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { if( !getContentWindowManager( )) return; drawFrame_( painter ); drawCloseButton_( painter ); drawResizeIndicator_( painter ); drawFullscreenButton_( painter ); drawMovieControls_( painter ); drawTextLabel_( painter ); } void ContentWindowGraphicsItem::adjustSize( const SizeState state, ContentWindowInterface * source ) { if(source != this) prepareGeometryChange(); ContentWindowInterface::adjustSize( state, source ); } void ContentWindowGraphicsItem::setCoordinates(double x, double y, double w, double h, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setCoordinates(x, y, w, h, source); } void ContentWindowGraphicsItem::setPosition(double x, double y, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setPosition(x, y, source); } void ContentWindowGraphicsItem::setSize(double w, double h, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setSize(w, h, source); } void ContentWindowGraphicsItem::setCenter(double centerX, double centerY, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setCenter(centerX, centerY, source); } void ContentWindowGraphicsItem::setZoom(double zoom, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setZoom(zoom, source); } void ContentWindowGraphicsItem::setWindowState(ContentWindowInterface::WindowState windowState, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setWindowState(windowState, source); } void ContentWindowGraphicsItem::setEvent(Event event, ContentWindowInterface * source) { if(source != this) prepareGeometryChange(); ContentWindowInterface::setEvent(event, source); } void ContentWindowGraphicsItem::setZToFront() { zCounter_ = zCounter_ + 1; setZValue(zCounter_); } bool ContentWindowGraphicsItem::sceneEvent( QEvent* event ) { switch( event->type( )) { case QEvent::Gesture: getContentWindowManager()->getInteractionDelegate().gestureEvent( static_cast< QGestureEvent* >( event )); return true; case QEvent::KeyPress: // Override default behaviour to process TAB key events keyPressEvent(static_cast<QKeyEvent *>(event)); return true; default: return QGraphicsObject::sceneEvent( event ); } } void ContentWindowGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { // handle mouse movements differently depending on selected mode of item if(!selected()) { if(event->buttons().testFlag(Qt::LeftButton) == true) { if(resizing_ == true) { QRectF r = boundingRect(); QPointF eventPos = event->pos(); r.setBottomRight(eventPos); QRectF sceneRect = mapRectToScene(r); double w = sceneRect.width(); double h = sceneRect.height(); setSize(w, h); } else { QPointF delta = event->pos() - event->lastPos(); double x = x_ + delta.x(); double y = y_ + delta.y(); setPosition(x, y); } } } else { ContentWindowManagerPtr contentWindow = getContentWindowManager(); if(contentWindow) { // Zoom or forward event depending on type contentWindow->getInteractionDelegate().mouseMoveEvent(event); // force a redraw to update window info label update(); } } } void ContentWindowGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { // on Mac we've seen that mouse events can go to the wrong graphics item // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493 // here we ignore the event if it shouldn't have been sent to us, which ensures // it will go to the correct item... if(boundingRect().contains(event->pos()) == false) { event->ignore(); return; } // button dimensions float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); // item rectangle and event position QRectF r = boundingRect(); QPointF eventPos = event->pos(); // check to see if user clicked on the close button if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs(r.y() - eventPos.y()) <= buttonHeight) { close(); return; } // move to the front of the GUI display moveToFront(); ContentWindowManagerPtr window = getContentWindowManager(); if (!window) return; if (selected()) { window->getInteractionDelegate().mousePressEvent(event); return; } window->getContent()->blockAdvance( true ); // check to see if user clicked on the resize button if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight) { resizing_ = true; } // check to see if user clicked on the fullscreen button else if(fabs(r.x() - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight) { adjustSize( getSizeState() == SIZE_FULLSCREEN ? SIZE_1TO1 : SIZE_FULLSCREEN ); } else if(fabs(((r.x()+r.width())/2) - eventPos.x() - buttonWidth) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight && g_displayGroupManager->getOptions()->getShowMovieControls( )) { window->setControlState( ControlState(window->getControlState() ^ STATE_PAUSED) ); } else if(fabs(((r.x()+r.width())/2) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight && g_displayGroupManager->getOptions()->getShowMovieControls( )) { window->setControlState( ControlState(window->getControlState() ^ STATE_LOOP) ); } else moving_ = true; QGraphicsItem::mousePressEvent(event); } void ContentWindowGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event) { // on Mac we've seen that mouse events can go to the wrong graphics item // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493 // here we ignore the event if it shouldn't have been sent to us, which ensures // it will go to the correct item... if(boundingRect().contains(event->pos()) == false) { event->ignore(); return; } toggleWindowState(); QGraphicsItem::mouseDoubleClickEvent(event); } void ContentWindowGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { resizing_ = false; moving_ = false; ContentWindowManagerPtr contentWindow = getContentWindowManager(); if( contentWindow ) { contentWindow->getContent()->blockAdvance( false ); if (selected()) { contentWindow->getInteractionDelegate().mouseReleaseEvent(event); } } QGraphicsItem::mouseReleaseEvent(event); } void ContentWindowGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent * event) { // on Mac we've seen that mouse events can go to the wrong graphics item // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493 // here we ignore the event if it shouldn't have been sent to us, which ensures // it will go to the correct item... if(boundingRect().contains(event->pos()) == false) { event->ignore(); return; } ContentWindowManagerPtr contentWindow = getContentWindowManager(); if( contentWindow ) { // handle wheel movements differently depending on state of item window if (selected()) { contentWindow->getInteractionDelegate().wheelEvent(event); } else { // scale size based on wheel delta // typical delta value is 120, so scale based on that double factor = 1. + (double)event->delta() / (10. * 120.); scaleSize(factor); } } } void ContentWindowGraphicsItem::keyPressEvent(QKeyEvent *event) { if (selected()) { ContentWindowManagerPtr contentWindow = getContentWindowManager(); if( contentWindow ) { contentWindow->getInteractionDelegate().keyPressEvent(event); } } } void ContentWindowGraphicsItem::keyReleaseEvent(QKeyEvent *event) { if (selected()) { ContentWindowManagerPtr contentWindow = getContentWindowManager(); if( contentWindow ) { contentWindow->getInteractionDelegate().keyReleaseEvent(event); } } } void ContentWindowGraphicsItem::drawCloseButton_( QPainter* painter ) { float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); QRectF closeRect(x_ + w_ - buttonWidth, y_, buttonWidth, buttonHeight); QPen pen; pen.setColor(QColor(255,0,0)); painter->setPen(pen); painter->drawRect(closeRect); painter->drawLine(QPointF(x_ + w_ - buttonWidth, y_), QPointF(x_ + w_, y_ + buttonHeight)); painter->drawLine(QPointF(x_ + w_, y_), QPointF(x_ + w_ - buttonWidth, y_ + buttonHeight)); } void ContentWindowGraphicsItem::drawResizeIndicator_( QPainter* painter ) { float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); QRectF resizeRect(x_ + w_ - buttonWidth, y_ + h_ - buttonHeight, buttonWidth, buttonHeight); QPen pen; pen.setColor(QColor(128,128,128)); painter->setPen(pen); painter->drawRect(resizeRect); painter->drawLine(QPointF(x_ + w_, y_ + h_ - buttonHeight), QPointF(x_ + w_ - buttonWidth, y_ + h_)); } void ContentWindowGraphicsItem::drawFullscreenButton_( QPainter* painter ) { float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); QRectF fullscreenRect(x_, y_ + h_ - buttonHeight, buttonWidth, buttonHeight); QPen pen; pen.setColor(QColor(128,128,128)); painter->setPen(pen); painter->drawRect(fullscreenRect); } void ContentWindowGraphicsItem::drawMovieControls_( QPainter* painter ) { ContentWindowManagerPtr contentWindowManager = getContentWindowManager(); float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); QPen pen; if( contentWindowManager->getContent()->getType() == CONTENT_TYPE_MOVIE && g_displayGroupManager->getOptions()->getShowMovieControls( )) { // play/pause QRectF playPauseRect(x_ + w_/2 - buttonWidth, y_ + h_ - buttonHeight, buttonWidth, buttonHeight); pen.setColor(QColor(contentWindowManager->getControlState() & STATE_PAUSED ? 128 :200,0,0)); painter->setPen(pen); painter->fillRect(playPauseRect, pen.color()); // loop QRectF loopRect(x_ + w_/2, y_ + h_ - buttonHeight, buttonWidth, buttonHeight); pen.setColor(QColor(0,contentWindowManager->getControlState() & STATE_LOOP ? 200 :128,0)); painter->setPen(pen); painter->fillRect(loopRect, pen.color()); } } void ContentWindowGraphicsItem::drawTextLabel_( QPainter* painter ) { ContentWindowManagerPtr contentWindowManager = getContentWindowManager(); float buttonWidth, buttonHeight; getButtonDimensions(buttonWidth, buttonHeight); const float fontSize = 24.; QFont font; font.setPixelSize(fontSize); painter->setFont(font); // color the text black QPen pen; pen.setColor(QColor(0,0,0)); painter->setPen(pen); // scale the text size down to the height of the graphics view // and, calculate the bounding rectangle for the text based on this scale // the dimensions of the view need to be corrected for the tiled display aspect ratio // recall the tiled display UI is only part of the graphics view since we show it at the correct aspect ratio // TODO refactor this for clarity! float viewWidth = (float)scene()->views()[0]->width(); float viewHeight = (float)scene()->views()[0]->height(); float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight(); if(viewWidth / viewHeight > tiledDisplayAspect) { viewWidth = viewHeight * tiledDisplayAspect; } else if(viewWidth / viewHeight <= tiledDisplayAspect) { viewHeight = viewWidth / tiledDisplayAspect; } float verticalTextScale = 1. / viewHeight; float horizontalTextScale = viewHeight / viewWidth * verticalTextScale; painter->scale(horizontalTextScale, verticalTextScale); QRectF textBoundingRect = QRectF(x_ / horizontalTextScale, y_ / verticalTextScale, w_ / horizontalTextScale, h_ / verticalTextScale); // get the label and render it QString label(contentWindowManager->getContent()->getURI()); QString labelSection = label.section("/", -1, -1).prepend(" "); painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop, labelSection); // draw window info at smaller scale verticalTextScale *= 0.5; horizontalTextScale *= 0.5; painter->scale(0.5, 0.5); textBoundingRect = QRectF((x_+buttonWidth) / horizontalTextScale, y_ / verticalTextScale, (w_-buttonWidth) / horizontalTextScale, h_ / verticalTextScale); QString coordinatesLabel = QString(" (") + QString::number(x_, 'f', 2) + QString(" ,") + QString::number(y_, 'f', 2) + QString(", ") + QString::number(w_, 'f', 2) + QString(", ") + QString::number(h_, 'f', 2) + QString(")\n"); QString zoomCenterLabel = QString(" zoom = ") + QString::number(zoom_, 'f', 2) + QString(" @ (") + QString::number(centerX_, 'f', 2) + QString(", ") + QString::number(centerY_, 'f', 2) + QString(")"); QString interactionLabel = QString(" x: ") + QString::number(event_.mouseX, 'f', 2) + QString(" y: ") + QString::number(event_.mouseY, 'f', 2) + QString(" mouseLeft: ") + QString::number((int) event_.mouseLeft, 'b', 1) + QString(" mouseMiddle: ") + QString::number((int) event_.mouseMiddle, 'b', 1) + QString(" mouseRight: ") + QString::number((int) event_.mouseRight, 'b', 1); QString windowInfoLabel = coordinatesLabel + zoomCenterLabel + interactionLabel; painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignBottom, windowInfoLabel); } void ContentWindowGraphicsItem::drawFrame_(QPainter* painter) { QPen pen; if(selected()) pen.setColor(QColor(255,0,0)); else pen.setColor(QColor(0,0,0)); painter->setPen(pen); painter->setBrush( QBrush(QColor(0, 0, 0, 128))); painter->drawRect(boundingRect()); }
shuaibarshad/KAUST-DisplayCluster
src/core/ContentWindowGraphicsItem.cpp
C++
bsd-2-clause
19,270
# Shows how unittest.mock can be used with dic to mock components during testing import dic import unittest, unittest.mock class Database(object): def __init__(self): self.data = { '1': 'some data', '2': 'other data', } def get_data(self): return self.data class Service(object): def __init__(self, database: Database): self.database = database def load(self): return self.database.get_data() class ServiceTestCase(unittest.TestCase): """ Test case for `Service` that mocks out the database. """ def setUp(self): builder = dic.container.ContainerBuilder() builder.register_class(Service) # register a mock instead of the real database self.database_mock = unittest.mock.Mock(spec=Database) builder.register_instance(Database, self.database_mock) container = builder.build() self.service = container.resolve(Service) def test_get_data(self): # Arrange attrs = {'get_data.return_value': {'3': 'mocked data'}} self.database_mock.configure_mock(**attrs) # Act self.service.load() # Assert self.database_mock.get_data.called_once_with() if __name__ == '__main__': unittest.main()
zsims/dic
samples/mocking/mocking.py
Python
bsd-2-clause
1,306
/* * Reference: http://en.wikipedia.org/wiki/Windows-1252 */ #include "../../src/bsdconv.h" static const struct uint32_range ranges[] = { { 0x0, 0x80 }, { 0x82, 0x8C }, { 0x8E, 0x8E }, { 0x91, 0x9C }, { 0x9E, 0xFF }, }; #include "unicode_range.c"
buganini/bsdconv
modules/filter/LATIN1.c
C
bsd-2-clause
257
MiniKonoha.Eval-パッケージの1行説明文 ==================== パッケージの説明文
konoha-project/konoha3
src/package-devel/Konoha.Eval/doc/ja.md
Markdown
bsd-2-clause
97
var searchData= [ ['mdhim_20tng',['MDHIM TNG',['../index.html',1,'']]] ];
mdhim/mdhim-tng
docs/html/search/pages_6d.js
JavaScript
bsd-2-clause
76
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <assert.h> #include "av1/common/common.h" #include "av1/common/entropy.h" #include "av1/common/entropymode.h" #include "av1/common/entropymv.h" #include "av1/common/mvref_common.h" #include "av1/common/pred_common.h" #include "av1/common/reconinter.h" #include "av1/common/seg_common.h" #include "av1/decoder/decodemv.h" #include "av1/decoder/decodeframe.h" #include "aom_dsp/aom_dsp_common.h" static PREDICTION_MODE read_intra_mode(aom_reader *r, const aom_prob *p) { return (PREDICTION_MODE)aom_read_tree(r, av1_intra_mode_tree, p); } static PREDICTION_MODE read_intra_mode_y(AV1_COMMON *cm, MACROBLOCKD *xd, aom_reader *r, int size_group) { const PREDICTION_MODE y_mode = read_intra_mode(r, cm->fc->y_mode_prob[size_group]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->y_mode[size_group][y_mode]; return y_mode; } static PREDICTION_MODE read_intra_mode_uv(AV1_COMMON *cm, MACROBLOCKD *xd, aom_reader *r, PREDICTION_MODE y_mode) { const PREDICTION_MODE uv_mode = read_intra_mode(r, cm->fc->uv_mode_prob[y_mode]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->uv_mode[y_mode][uv_mode]; return uv_mode; } static PREDICTION_MODE read_inter_mode(AV1_COMMON *cm, MACROBLOCKD *xd, aom_reader *r, int16_t ctx) { #if CONFIG_REF_MV FRAME_COUNTS *counts = xd->counts; int16_t mode_ctx = ctx & NEWMV_CTX_MASK; aom_prob mode_prob = cm->fc->newmv_prob[mode_ctx]; if (aom_read(r, mode_prob) == 0) { if (counts) ++counts->newmv_mode[mode_ctx][0]; return NEWMV; } if (counts) ++counts->newmv_mode[mode_ctx][1]; if (ctx & (1 << ALL_ZERO_FLAG_OFFSET)) return ZEROMV; mode_ctx = (ctx >> ZEROMV_OFFSET) & ZEROMV_CTX_MASK; mode_prob = cm->fc->zeromv_prob[mode_ctx]; if (aom_read(r, mode_prob) == 0) { if (counts) ++counts->zeromv_mode[mode_ctx][0]; return ZEROMV; } if (counts) ++counts->zeromv_mode[mode_ctx][1]; mode_ctx = (ctx >> REFMV_OFFSET) & REFMV_CTX_MASK; if (ctx & (1 << SKIP_NEARESTMV_OFFSET)) mode_ctx = 6; if (ctx & (1 << SKIP_NEARMV_OFFSET)) mode_ctx = 7; if (ctx & (1 << SKIP_NEARESTMV_SUB8X8_OFFSET)) mode_ctx = 8; mode_prob = cm->fc->refmv_prob[mode_ctx]; if (aom_read(r, mode_prob) == 0) { if (counts) ++counts->refmv_mode[mode_ctx][0]; return NEARESTMV; } else { if (counts) ++counts->refmv_mode[mode_ctx][1]; return NEARMV; } // Invalid prediction mode. assert(0); #else const int mode = aom_read_tree(r, av1_inter_mode_tree, cm->fc->inter_mode_probs[ctx]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->inter_mode[ctx][mode]; return NEARESTMV + mode; #endif } #if CONFIG_REF_MV static void read_drl_idx(const AV1_COMMON *cm, MACROBLOCKD *xd, MB_MODE_INFO *mbmi, aom_reader *r) { uint8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame); mbmi->ref_mv_idx = 0; if (xd->ref_mv_count[ref_frame_type] > 2) { uint8_t drl0_ctx = av1_drl_ctx(xd->ref_mv_stack[ref_frame_type], 1); aom_prob drl0_prob = cm->fc->drl_prob0[drl0_ctx]; if (aom_read(r, drl0_prob)) { mbmi->ref_mv_idx = 1; if (xd->counts) ++xd->counts->drl_mode0[drl0_ctx][1]; if (xd->ref_mv_count[ref_frame_type] > 3) { uint8_t drl1_ctx = av1_drl_ctx(xd->ref_mv_stack[ref_frame_type], 2); aom_prob drl1_prob = cm->fc->drl_prob1[drl1_ctx]; if (aom_read(r, drl1_prob)) { mbmi->ref_mv_idx = 2; if (xd->counts) ++xd->counts->drl_mode1[drl1_ctx][1]; return; } if (xd->counts) ++xd->counts->drl_mode1[drl1_ctx][0]; } return; } if (xd->counts) ++xd->counts->drl_mode0[drl0_ctx][0]; } } #endif static int read_segment_id(aom_reader *r, const struct segmentation_probs *segp) { return aom_read_tree(r, av1_segment_tree, segp->tree_probs); } static TX_SIZE read_selected_tx_size(AV1_COMMON *cm, MACROBLOCKD *xd, TX_SIZE max_tx_size, aom_reader *r) { FRAME_COUNTS *counts = xd->counts; const int ctx = get_tx_size_context(xd); const aom_prob *tx_probs = get_tx_probs(max_tx_size, ctx, &cm->fc->tx_probs); int tx_size = aom_read(r, tx_probs[0]); if (tx_size != TX_4X4 && max_tx_size >= TX_16X16) { tx_size += aom_read(r, tx_probs[1]); if (tx_size != TX_8X8 && max_tx_size >= TX_32X32) tx_size += aom_read(r, tx_probs[2]); } if (counts) ++get_tx_counts(max_tx_size, ctx, &counts->tx)[tx_size]; return (TX_SIZE)tx_size; } static TX_SIZE read_tx_size(AV1_COMMON *cm, MACROBLOCKD *xd, int allow_select, aom_reader *r) { TX_MODE tx_mode = cm->tx_mode; BLOCK_SIZE bsize = xd->mi[0]->mbmi.sb_type; const TX_SIZE max_tx_size = max_txsize_lookup[bsize]; if (xd->lossless[xd->mi[0]->mbmi.segment_id]) return TX_4X4; if (allow_select && tx_mode == TX_MODE_SELECT && bsize >= BLOCK_8X8) return read_selected_tx_size(cm, xd, max_tx_size, r); else return AOMMIN(max_tx_size, tx_mode_to_biggest_tx_size[tx_mode]); } static int dec_get_segment_id(const AV1_COMMON *cm, const uint8_t *segment_ids, int mi_offset, int x_mis, int y_mis) { int x, y, segment_id = INT_MAX; for (y = 0; y < y_mis; y++) for (x = 0; x < x_mis; x++) segment_id = AOMMIN(segment_id, segment_ids[mi_offset + y * cm->mi_cols + x]); assert(segment_id >= 0 && segment_id < MAX_SEGMENTS); return segment_id; } static void set_segment_id(AV1_COMMON *cm, int mi_offset, int x_mis, int y_mis, int segment_id) { int x, y; assert(segment_id >= 0 && segment_id < MAX_SEGMENTS); for (y = 0; y < y_mis; y++) for (x = 0; x < x_mis; x++) cm->current_frame_seg_map[mi_offset + y * cm->mi_cols + x] = segment_id; } static int read_intra_segment_id(AV1_COMMON *const cm, MACROBLOCKD *const xd, int mi_offset, int x_mis, int y_mis, aom_reader *r) { struct segmentation *const seg = &cm->seg; #if CONFIG_MISC_FIXES FRAME_COUNTS *counts = xd->counts; struct segmentation_probs *const segp = &cm->fc->seg; #else struct segmentation_probs *const segp = &cm->segp; #endif int segment_id; #if !CONFIG_MISC_FIXES (void)xd; #endif if (!seg->enabled) return 0; // Default for disabled segmentation assert(seg->update_map && !seg->temporal_update); segment_id = read_segment_id(r, segp); #if CONFIG_MISC_FIXES if (counts) ++counts->seg.tree_total[segment_id]; #endif set_segment_id(cm, mi_offset, x_mis, y_mis, segment_id); return segment_id; } static void copy_segment_id(const AV1_COMMON *cm, const uint8_t *last_segment_ids, uint8_t *current_segment_ids, int mi_offset, int x_mis, int y_mis) { int x, y; for (y = 0; y < y_mis; y++) for (x = 0; x < x_mis; x++) current_segment_ids[mi_offset + y * cm->mi_cols + x] = last_segment_ids ? last_segment_ids[mi_offset + y * cm->mi_cols + x] : 0; } static int read_inter_segment_id(AV1_COMMON *const cm, MACROBLOCKD *const xd, int mi_row, int mi_col, aom_reader *r) { struct segmentation *const seg = &cm->seg; #if CONFIG_MISC_FIXES FRAME_COUNTS *counts = xd->counts; struct segmentation_probs *const segp = &cm->fc->seg; #else struct segmentation_probs *const segp = &cm->segp; #endif MB_MODE_INFO *const mbmi = &xd->mi[0]->mbmi; int predicted_segment_id, segment_id; const int mi_offset = mi_row * cm->mi_cols + mi_col; const int bw = xd->plane[0].n4_w >> 1; const int bh = xd->plane[0].n4_h >> 1; // TODO(slavarnway): move x_mis, y_mis into xd ????? const int x_mis = AOMMIN(cm->mi_cols - mi_col, bw); const int y_mis = AOMMIN(cm->mi_rows - mi_row, bh); if (!seg->enabled) return 0; // Default for disabled segmentation predicted_segment_id = cm->last_frame_seg_map ? dec_get_segment_id(cm, cm->last_frame_seg_map, mi_offset, x_mis, y_mis) : 0; if (!seg->update_map) { copy_segment_id(cm, cm->last_frame_seg_map, cm->current_frame_seg_map, mi_offset, x_mis, y_mis); return predicted_segment_id; } if (seg->temporal_update) { const int ctx = av1_get_pred_context_seg_id(xd); const aom_prob pred_prob = segp->pred_probs[ctx]; mbmi->seg_id_predicted = aom_read(r, pred_prob); #if CONFIG_MISC_FIXES if (counts) ++counts->seg.pred[ctx][mbmi->seg_id_predicted]; #endif if (mbmi->seg_id_predicted) { segment_id = predicted_segment_id; } else { segment_id = read_segment_id(r, segp); #if CONFIG_MISC_FIXES if (counts) ++counts->seg.tree_mispred[segment_id]; #endif } } else { segment_id = read_segment_id(r, segp); #if CONFIG_MISC_FIXES if (counts) ++counts->seg.tree_total[segment_id]; #endif } set_segment_id(cm, mi_offset, x_mis, y_mis, segment_id); return segment_id; } static int read_skip(AV1_COMMON *cm, const MACROBLOCKD *xd, int segment_id, aom_reader *r) { if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)) { return 1; } else { const int ctx = av1_get_skip_context(xd); const int skip = aom_read(r, cm->fc->skip_probs[ctx]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->skip[ctx][skip]; return skip; } } static void read_intra_frame_mode_info(AV1_COMMON *const cm, MACROBLOCKD *const xd, int mi_row, int mi_col, aom_reader *r) { MODE_INFO *const mi = xd->mi[0]; MB_MODE_INFO *const mbmi = &mi->mbmi; const MODE_INFO *above_mi = xd->above_mi; const MODE_INFO *left_mi = xd->left_mi; const BLOCK_SIZE bsize = mbmi->sb_type; int i; const int mi_offset = mi_row * cm->mi_cols + mi_col; const int bw = xd->plane[0].n4_w >> 1; const int bh = xd->plane[0].n4_h >> 1; // TODO(slavarnway): move x_mis, y_mis into xd ????? const int x_mis = AOMMIN(cm->mi_cols - mi_col, bw); const int y_mis = AOMMIN(cm->mi_rows - mi_row, bh); mbmi->segment_id = read_intra_segment_id(cm, xd, mi_offset, x_mis, y_mis, r); mbmi->skip = read_skip(cm, xd, mbmi->segment_id, r); mbmi->tx_size = read_tx_size(cm, xd, 1, r); mbmi->ref_frame[0] = INTRA_FRAME; mbmi->ref_frame[1] = NONE; switch (bsize) { case BLOCK_4X4: for (i = 0; i < 4; ++i) mi->bmi[i].as_mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, i)); mbmi->mode = mi->bmi[3].as_mode; break; case BLOCK_4X8: mi->bmi[0].as_mode = mi->bmi[2].as_mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, 0)); mi->bmi[1].as_mode = mi->bmi[3].as_mode = mbmi->mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, 1)); break; case BLOCK_8X4: mi->bmi[0].as_mode = mi->bmi[1].as_mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, 0)); mi->bmi[2].as_mode = mi->bmi[3].as_mode = mbmi->mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, 2)); break; default: mbmi->mode = read_intra_mode(r, get_y_mode_probs(cm, mi, above_mi, left_mi, 0)); } mbmi->uv_mode = read_intra_mode_uv(cm, xd, r, mbmi->mode); if (mbmi->tx_size < TX_32X32 && cm->base_qindex > 0 && !mbmi->skip && !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) { FRAME_COUNTS *counts = xd->counts; TX_TYPE tx_type_nom = intra_mode_to_tx_type_context[mbmi->mode]; mbmi->tx_type = aom_read_tree(r, av1_ext_tx_tree, cm->fc->intra_ext_tx_prob[mbmi->tx_size][tx_type_nom]); if (counts) ++counts->intra_ext_tx[mbmi->tx_size][tx_type_nom][mbmi->tx_type]; } else { mbmi->tx_type = DCT_DCT; } } static int read_mv_component(aom_reader *r, const nmv_component *mvcomp, int usehp) { int mag, d, fr, hp; const int sign = aom_read(r, mvcomp->sign); const int mv_class = aom_read_tree(r, av1_mv_class_tree, mvcomp->classes); const int class0 = mv_class == MV_CLASS_0; // Integer part if (class0) { d = aom_read_tree(r, av1_mv_class0_tree, mvcomp->class0); mag = 0; } else { int i; const int n = mv_class + CLASS0_BITS - 1; // number of bits d = 0; for (i = 0; i < n; ++i) d |= aom_read(r, mvcomp->bits[i]) << i; mag = CLASS0_SIZE << (mv_class + 2); } // Fractional part fr = aom_read_tree(r, av1_mv_fp_tree, class0 ? mvcomp->class0_fp[d] : mvcomp->fp); // High precision part (if hp is not used, the default value of the hp is 1) hp = usehp ? aom_read(r, class0 ? mvcomp->class0_hp : mvcomp->hp) : 1; // Result mag += ((d << 3) | (fr << 1) | hp) + 1; return sign ? -mag : mag; } static INLINE void read_mv(aom_reader *r, MV *mv, const MV *ref, const nmv_context *ctx, nmv_context_counts *counts, int allow_hp) { const MV_JOINT_TYPE joint_type = (MV_JOINT_TYPE)aom_read_tree(r, av1_mv_joint_tree, ctx->joints); const int use_hp = allow_hp && av1_use_mv_hp(ref); MV diff = { 0, 0 }; if (mv_joint_vertical(joint_type)) diff.row = read_mv_component(r, &ctx->comps[0], use_hp); if (mv_joint_horizontal(joint_type)) diff.col = read_mv_component(r, &ctx->comps[1], use_hp); av1_inc_mv(&diff, counts, use_hp); mv->row = ref->row + diff.row; mv->col = ref->col + diff.col; } static REFERENCE_MODE read_block_reference_mode(AV1_COMMON *cm, const MACROBLOCKD *xd, aom_reader *r) { if (cm->reference_mode == REFERENCE_MODE_SELECT) { const int ctx = av1_get_reference_mode_context(cm, xd); const REFERENCE_MODE mode = (REFERENCE_MODE)aom_read(r, cm->fc->comp_inter_prob[ctx]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->comp_inter[ctx][mode]; return mode; // SINGLE_REFERENCE or COMPOUND_REFERENCE } else { return cm->reference_mode; } } // Read the referncence frame static void read_ref_frames(AV1_COMMON *const cm, MACROBLOCKD *const xd, aom_reader *r, int segment_id, MV_REFERENCE_FRAME ref_frame[2]) { FRAME_CONTEXT *const fc = cm->fc; FRAME_COUNTS *counts = xd->counts; if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) { ref_frame[0] = (MV_REFERENCE_FRAME)get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME); ref_frame[1] = NONE; } else { const REFERENCE_MODE mode = read_block_reference_mode(cm, xd, r); // FIXME(rbultje) I'm pretty sure this breaks segmentation ref frame coding if (mode == COMPOUND_REFERENCE) { const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref]; const int ctx = av1_get_pred_context_comp_ref_p(cm, xd); const int bit = aom_read(r, fc->comp_ref_prob[ctx]); if (counts) ++counts->comp_ref[ctx][bit]; ref_frame[idx] = cm->comp_fixed_ref; ref_frame[!idx] = cm->comp_var_ref[bit]; } else if (mode == SINGLE_REFERENCE) { const int ctx0 = av1_get_pred_context_single_ref_p1(xd); const int bit0 = aom_read(r, fc->single_ref_prob[ctx0][0]); if (counts) ++counts->single_ref[ctx0][0][bit0]; if (bit0) { const int ctx1 = av1_get_pred_context_single_ref_p2(xd); const int bit1 = aom_read(r, fc->single_ref_prob[ctx1][1]); if (counts) ++counts->single_ref[ctx1][1][bit1]; ref_frame[0] = bit1 ? ALTREF_FRAME : GOLDEN_FRAME; } else { ref_frame[0] = LAST_FRAME; } ref_frame[1] = NONE; } else { assert(0 && "Invalid prediction mode."); } } } static INLINE INTERP_FILTER read_switchable_interp_filter(AV1_COMMON *const cm, MACROBLOCKD *const xd, aom_reader *r) { const int ctx = av1_get_pred_context_switchable_interp(xd); const INTERP_FILTER type = (INTERP_FILTER)aom_read_tree( r, av1_switchable_interp_tree, cm->fc->switchable_interp_prob[ctx]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->switchable_interp[ctx][type]; return type; } static void read_intra_block_mode_info(AV1_COMMON *const cm, MACROBLOCKD *const xd, MODE_INFO *mi, aom_reader *r) { MB_MODE_INFO *const mbmi = &mi->mbmi; const BLOCK_SIZE bsize = mi->mbmi.sb_type; int i; mbmi->ref_frame[0] = INTRA_FRAME; mbmi->ref_frame[1] = NONE; switch (bsize) { case BLOCK_4X4: for (i = 0; i < 4; ++i) mi->bmi[i].as_mode = read_intra_mode_y(cm, xd, r, 0); mbmi->mode = mi->bmi[3].as_mode; break; case BLOCK_4X8: mi->bmi[0].as_mode = mi->bmi[2].as_mode = read_intra_mode_y(cm, xd, r, 0); mi->bmi[1].as_mode = mi->bmi[3].as_mode = mbmi->mode = read_intra_mode_y(cm, xd, r, 0); break; case BLOCK_8X4: mi->bmi[0].as_mode = mi->bmi[1].as_mode = read_intra_mode_y(cm, xd, r, 0); mi->bmi[2].as_mode = mi->bmi[3].as_mode = mbmi->mode = read_intra_mode_y(cm, xd, r, 0); break; default: mbmi->mode = read_intra_mode_y(cm, xd, r, size_group_lookup[bsize]); } mbmi->uv_mode = read_intra_mode_uv(cm, xd, r, mbmi->mode); } static INLINE int is_mv_valid(const MV *mv) { return mv->row > MV_LOW && mv->row < MV_UPP && mv->col > MV_LOW && mv->col < MV_UPP; } static INLINE int assign_mv(AV1_COMMON *cm, MACROBLOCKD *xd, PREDICTION_MODE mode, int block, int_mv mv[2], int_mv ref_mv[2], int_mv nearest_mv[2], int_mv near_mv[2], int is_compound, int allow_hp, aom_reader *r) { int i; int ret = 1; #if CONFIG_REF_MV MB_MODE_INFO *mbmi = &xd->mi[0]->mbmi; BLOCK_SIZE bsize = mbmi->sb_type; int_mv *pred_mv = (bsize >= BLOCK_8X8) ? mbmi->pred_mv : xd->mi[0]->bmi[block].pred_mv; #else (void)block; #endif switch (mode) { case NEWMV: { FRAME_COUNTS *counts = xd->counts; #if !CONFIG_REF_MV nmv_context_counts *const mv_counts = counts ? &counts->mv : NULL; #endif for (i = 0; i < 1 + is_compound; ++i) { #if CONFIG_REF_MV int nmv_ctx = av1_nmv_ctx(xd->ref_mv_count[mbmi->ref_frame[i]], xd->ref_mv_stack[mbmi->ref_frame[i]]); nmv_context_counts *const mv_counts = counts ? &counts->mv[nmv_ctx] : NULL; read_mv(r, &mv[i].as_mv, &ref_mv[i].as_mv, &cm->fc->nmvc[nmv_ctx], mv_counts, allow_hp); #else read_mv(r, &mv[i].as_mv, &ref_mv[i].as_mv, &cm->fc->nmvc, mv_counts, allow_hp); #endif ret = ret && is_mv_valid(&mv[i].as_mv); #if CONFIG_REF_MV pred_mv[i].as_int = ref_mv[i].as_int; #endif } break; } case NEARESTMV: { mv[0].as_int = nearest_mv[0].as_int; if (is_compound) mv[1].as_int = nearest_mv[1].as_int; #if CONFIG_REF_MV pred_mv[0].as_int = nearest_mv[0].as_int; if (is_compound) pred_mv[1].as_int = nearest_mv[1].as_int; #endif break; } case NEARMV: { mv[0].as_int = near_mv[0].as_int; if (is_compound) mv[1].as_int = near_mv[1].as_int; #if CONFIG_REF_MV pred_mv[0].as_int = near_mv[0].as_int; if (is_compound) pred_mv[1].as_int = near_mv[1].as_int; #endif break; } case ZEROMV: { mv[0].as_int = 0; if (is_compound) mv[1].as_int = 0; #if CONFIG_REF_MV pred_mv[0].as_int = 0; if (is_compound) pred_mv[1].as_int = 0; #endif break; } default: { return 0; } } return ret; } static int read_is_inter_block(AV1_COMMON *const cm, MACROBLOCKD *const xd, int segment_id, aom_reader *r) { if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) { return get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME) != INTRA_FRAME; } else { const int ctx = av1_get_intra_inter_context(xd); const int is_inter = aom_read(r, cm->fc->intra_inter_prob[ctx]); FRAME_COUNTS *counts = xd->counts; if (counts) ++counts->intra_inter[ctx][is_inter]; return is_inter; } } static void fpm_sync(void *const data, int mi_row) { AV1Decoder *const pbi = (AV1Decoder *)data; av1_frameworker_wait(pbi->frame_worker_owner, pbi->common.prev_frame, mi_row << MI_BLOCK_SIZE_LOG2); } static void read_inter_block_mode_info(AV1Decoder *const pbi, MACROBLOCKD *const xd, MODE_INFO *const mi, int mi_row, int mi_col, aom_reader *r) { AV1_COMMON *const cm = &pbi->common; MB_MODE_INFO *const mbmi = &mi->mbmi; const BLOCK_SIZE bsize = mbmi->sb_type; const int allow_hp = cm->allow_high_precision_mv; int_mv nearestmv[2], nearmv[2]; int_mv ref_mvs[MODE_CTX_REF_FRAMES][MAX_MV_REF_CANDIDATES]; int ref, is_compound; int16_t inter_mode_ctx[MODE_CTX_REF_FRAMES]; int16_t mode_ctx = 0; MV_REFERENCE_FRAME ref_frame; read_ref_frames(cm, xd, r, mbmi->segment_id, mbmi->ref_frame); is_compound = has_second_ref(mbmi); for (ref = 0; ref < 1 + is_compound; ++ref) { const MV_REFERENCE_FRAME frame = mbmi->ref_frame[ref]; RefBuffer *ref_buf = &cm->frame_refs[frame - LAST_FRAME]; xd->block_refs[ref] = ref_buf; if ((!av1_is_valid_scale(&ref_buf->sf))) aom_internal_error(xd->error_info, AOM_CODEC_UNSUP_BITSTREAM, "Reference frame has invalid dimensions"); av1_setup_pre_planes(xd, ref, ref_buf->buf, mi_row, mi_col, &ref_buf->sf); } for (ref_frame = LAST_FRAME; ref_frame < MODE_CTX_REF_FRAMES; ++ref_frame) { av1_find_mv_refs(cm, xd, mi, ref_frame, #if CONFIG_REF_MV &xd->ref_mv_count[ref_frame], xd->ref_mv_stack[ref_frame], #endif ref_mvs[ref_frame], mi_row, mi_col, fpm_sync, (void *)pbi, inter_mode_ctx); } #if CONFIG_REF_MV mode_ctx = av1_mode_context_analyzer(inter_mode_ctx, mbmi->ref_frame, bsize, -1); mbmi->ref_mv_idx = 0; #else mode_ctx = inter_mode_ctx[mbmi->ref_frame[0]]; #endif if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) { mbmi->mode = ZEROMV; if (bsize < BLOCK_8X8) { aom_internal_error(xd->error_info, AOM_CODEC_UNSUP_BITSTREAM, "Invalid usage of segement feature on small blocks"); return; } } else { if (bsize >= BLOCK_8X8) { mbmi->mode = read_inter_mode(cm, xd, r, mode_ctx); #if CONFIG_REF_MV if (mbmi->mode == NEARMV) read_drl_idx(cm, xd, mbmi, r); #endif } } if (bsize < BLOCK_8X8 || mbmi->mode != ZEROMV) { for (ref = 0; ref < 1 + is_compound; ++ref) { av1_find_best_ref_mvs(allow_hp, ref_mvs[mbmi->ref_frame[ref]], &nearestmv[ref], &nearmv[ref]); } } #if CONFIG_REF_MV if (mbmi->ref_mv_idx > 0) { int_mv cur_mv = xd->ref_mv_stack[mbmi->ref_frame[0]][1 + mbmi->ref_mv_idx].this_mv; lower_mv_precision(&cur_mv.as_mv, cm->allow_high_precision_mv); nearmv[0] = cur_mv; } if (is_compound && bsize >= BLOCK_8X8 && mbmi->mode != NEWMV && mbmi->mode != ZEROMV) { uint8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame); if (xd->ref_mv_count[ref_frame_type] == 1 && mbmi->mode == NEARESTMV) { int i; nearestmv[0] = xd->ref_mv_stack[ref_frame_type][0].this_mv; nearestmv[1] = xd->ref_mv_stack[ref_frame_type][0].comp_mv; for (i = 0; i < 2; ++i) lower_mv_precision(&nearestmv[i].as_mv, allow_hp); } if (xd->ref_mv_count[ref_frame_type] > 1) { int i; const int ref_mv_idx = 1 + mbmi->ref_mv_idx; nearestmv[0] = xd->ref_mv_stack[ref_frame_type][0].this_mv; nearestmv[1] = xd->ref_mv_stack[ref_frame_type][0].comp_mv; nearmv[0] = xd->ref_mv_stack[ref_frame_type][ref_mv_idx].this_mv; nearmv[1] = xd->ref_mv_stack[ref_frame_type][ref_mv_idx].comp_mv; for (i = 0; i < 2; ++i) { lower_mv_precision(&nearestmv[i].as_mv, allow_hp); lower_mv_precision(&nearmv[i].as_mv, allow_hp); } } } #endif mbmi->interp_filter = (cm->interp_filter == SWITCHABLE) ? read_switchable_interp_filter(cm, xd, r) : cm->interp_filter; if (bsize < BLOCK_8X8) { const int num_4x4_w = 1 << xd->bmode_blocks_wl; const int num_4x4_h = 1 << xd->bmode_blocks_hl; int idx, idy; PREDICTION_MODE b_mode; int_mv nearest_sub8x8[2], near_sub8x8[2]; for (idy = 0; idy < 2; idy += num_4x4_h) { for (idx = 0; idx < 2; idx += num_4x4_w) { int_mv block[2]; const int j = idy * 2 + idx; #if CONFIG_REF_MV mode_ctx = av1_mode_context_analyzer(inter_mode_ctx, mbmi->ref_frame, bsize, j); #endif b_mode = read_inter_mode(cm, xd, r, mode_ctx); if (b_mode == NEARESTMV || b_mode == NEARMV) { for (ref = 0; ref < 1 + is_compound; ++ref) av1_append_sub8x8_mvs_for_idx(cm, xd, j, ref, mi_row, mi_col, &nearest_sub8x8[ref], &near_sub8x8[ref]); } if (!assign_mv(cm, xd, b_mode, j, block, nearestmv, nearest_sub8x8, near_sub8x8, is_compound, allow_hp, r)) { xd->corrupted |= 1; break; }; mi->bmi[j].as_mv[0].as_int = block[0].as_int; if (is_compound) mi->bmi[j].as_mv[1].as_int = block[1].as_int; if (num_4x4_h == 2) mi->bmi[j + 2] = mi->bmi[j]; if (num_4x4_w == 2) mi->bmi[j + 1] = mi->bmi[j]; } } mi->mbmi.mode = b_mode; #if CONFIG_REF_MV mbmi->pred_mv[0].as_int = mi->bmi[3].pred_mv[0].as_int; mbmi->pred_mv[1].as_int = mi->bmi[3].pred_mv[1].as_int; #endif mbmi->mv[0].as_int = mi->bmi[3].as_mv[0].as_int; mbmi->mv[1].as_int = mi->bmi[3].as_mv[1].as_int; } else { xd->corrupted |= !assign_mv(cm, xd, mbmi->mode, 0, mbmi->mv, nearestmv, nearestmv, nearmv, is_compound, allow_hp, r); } } static void read_inter_frame_mode_info(AV1Decoder *const pbi, MACROBLOCKD *const xd, int mi_row, int mi_col, aom_reader *r) { AV1_COMMON *const cm = &pbi->common; MODE_INFO *const mi = xd->mi[0]; MB_MODE_INFO *const mbmi = &mi->mbmi; int inter_block; mbmi->mv[0].as_int = 0; mbmi->mv[1].as_int = 0; mbmi->segment_id = read_inter_segment_id(cm, xd, mi_row, mi_col, r); mbmi->skip = read_skip(cm, xd, mbmi->segment_id, r); inter_block = read_is_inter_block(cm, xd, mbmi->segment_id, r); mbmi->tx_size = read_tx_size(cm, xd, !mbmi->skip || !inter_block, r); if (inter_block) read_inter_block_mode_info(pbi, xd, mi, mi_row, mi_col, r); else read_intra_block_mode_info(cm, xd, mi, r); if (mbmi->tx_size < TX_32X32 && cm->base_qindex > 0 && !mbmi->skip && !segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP)) { FRAME_COUNTS *counts = xd->counts; if (inter_block) { mbmi->tx_type = aom_read_tree(r, av1_ext_tx_tree, cm->fc->inter_ext_tx_prob[mbmi->tx_size]); if (counts) ++counts->inter_ext_tx[mbmi->tx_size][mbmi->tx_type]; } else { const TX_TYPE tx_type_nom = intra_mode_to_tx_type_context[mbmi->mode]; mbmi->tx_type = aom_read_tree(r, av1_ext_tx_tree, cm->fc->intra_ext_tx_prob[mbmi->tx_size][tx_type_nom]); if (counts) ++counts->intra_ext_tx[mbmi->tx_size][tx_type_nom][mbmi->tx_type]; } } else { mbmi->tx_type = DCT_DCT; } } void av1_read_mode_info(AV1Decoder *const pbi, MACROBLOCKD *xd, int mi_row, int mi_col, aom_reader *r, int x_mis, int y_mis) { AV1_COMMON *const cm = &pbi->common; MODE_INFO *const mi = xd->mi[0]; MV_REF *frame_mvs = cm->cur_frame->mvs + mi_row * cm->mi_cols + mi_col; int w, h; if (frame_is_intra_only(cm)) { read_intra_frame_mode_info(cm, xd, mi_row, mi_col, r); } else { read_inter_frame_mode_info(pbi, xd, mi_row, mi_col, r); for (h = 0; h < y_mis; ++h) { MV_REF *const frame_mv = frame_mvs + h * cm->mi_cols; for (w = 0; w < x_mis; ++w) { MV_REF *const mv = frame_mv + w; mv->ref_frame[0] = mi->mbmi.ref_frame[0]; mv->ref_frame[1] = mi->mbmi.ref_frame[1]; mv->mv[0].as_int = mi->mbmi.mv[0].as_int; mv->mv[1].as_int = mi->mbmi.mv[1].as_int; } } } }
thdav/aom
av1/decoder/decodemv.c
C
bsd-2-clause
30,026
/* Copyright (c) Citrix Systems Inc. * 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. * * 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 HOLDER 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. */ #define INITGUID 1 #include "fdo.h" #include "driver.h" #include "pdo.h" #include "srbext.h" #include "hvm.h" #include "store.h" #include "evtchn.h" #include "gnttab.h" #include "austere.h" #include "frontend.h" #include "log.h" #include "assert.h" #include "util.h" #include <xencdb.h> #include <names.h> #include <stdlib.h> struct _XENVBD_FDO { PXENVBD_PDO Target; }; //============================================================================= // Initialize, Start, Stop static FORCEINLINE PCHAR __Next( IN PCHAR Ptr ) { if (Ptr == NULL) return NULL; while (*Ptr != '\0') ++Ptr; ++Ptr; if (*Ptr == '\0') return NULL; return Ptr; } static NTSTATUS FdoCloseAllTargets( ) { NTSTATUS Status; PCHAR Device; PCHAR DeviceList; Status = StoreDirectory(NULL, "device", "vbd", &DeviceList); if (!NT_SUCCESS(Status)) goto fail1; for (Device = DeviceList; Device; Device = __Next(Device)) { PCHAR FrontendPath; PCHAR BackendPath; FrontendPath = DriverFormat("device/vbd/%s", Device); if (FrontendPath == NULL) continue; Status = StoreRead(NULL, FrontendPath, "backend", &BackendPath); if (!NT_SUCCESS(Status)) { AustereFree(FrontendPath); continue; } FrontendCloseTarget(FrontendPath, BackendPath); AustereFree(FrontendPath); AustereFree(BackendPath); } AustereFree(DeviceList); return STATUS_SUCCESS; fail1: LogError("Fail1 (%08x)\n", Status); return Status; } static BOOLEAN FdoGetFeatureFlag( IN PCHAR Path, IN PCHAR Feature ) { BOOLEAN Ret = FALSE; NTSTATUS Status; PCHAR Value; Status = StoreRead(NULL, Path, Feature, &Value); if (NT_SUCCESS(Status)) { if (strtoul(Value, NULL, 10) > 0) Ret = TRUE; AustereFree(Value); } LogTrace("<===> (%08x) %s/%s = %s\n", Status, Path, Feature, Ret ? "TRUE" : "FALSE"); return Ret; } static FORCEINLINE NTSTATUS FdoCreateTarget( IN PXENVBD_FDO Fdo, IN PCHAR DeviceId, IN ULONG TargetId ) { NTSTATUS Status; PXENVBD_PDO Pdo; LogTrace("===> %p, %s, %d\n", Fdo, DeviceId, TargetId); Status = PdoCreate(Fdo, DeviceId, TargetId, &Pdo); if (NT_SUCCESS(Status)) { Fdo->Target = Pdo; } LogTrace("<=== (%08x)\n", Status); return Status; } static NTSTATUS FdoFindTarget( IN PXENVBD_FDO Fdo ) { NTSTATUS Status; ULONG TargetId; PCHAR TargetPath; PCHAR Disk = NULL; const ULONG OperatingMode = DriverGetOperatingMode(); LogTrace("====>\n"); for (TargetId = 0; TargetId < XENVBD_MAX_TARGETS; ++TargetId) { TargetPath = DriverFormat("data/scsi/target/%d", TargetId); if (!TargetPath) continue; LogTrace("Target[%d] = %s\n", TargetId, TargetPath); if (OperatingMode == DUMP_MODE) { if (!FdoGetFeatureFlag(TargetPath, "dump")) { AustereFree(TargetPath); continue; } } else if (OperatingMode == HIBER_MODE) { if (!FdoGetFeatureFlag(TargetPath, "hibernation")) { AustereFree(TargetPath); continue; } } else { Status = STATUS_INVALID_PARAMETER; goto done; } Status = StoreRead(NULL, TargetPath, "device", &Disk); if (!NT_SUCCESS(Status)) { AustereFree(TargetPath); continue; } AustereFree(TargetPath); LogVerbose("%s Target is %s (%d)\n", OperatingMode == DUMP_MODE ? "DUMP" : "HIBER", Disk, TargetId); Status = FdoCreateTarget(Fdo, Disk, TargetId); AustereFree(Disk); goto done; } LogVerbose("%s Target not found, trying Target[0]\n", OperatingMode == DUMP_MODE ? "DUMP" : "HIBER"); Status = FdoCreateTarget(Fdo, "768", 0); done: LogTrace("<==== (%08x)\n", Status); return Status; } static FORCEINLINE BOOLEAN FdoInitialize( IN PXENVBD_FDO Fdo ) { NTSTATUS Status; LogTrace("====>\n"); DriverLinkFdo(Fdo); Status = HvmInitialize(); if (!NT_SUCCESS(Status)) { LogError("HvmInitialize (%08x)\n", Status); goto fail; } Status = StoreInitialize(); if (!NT_SUCCESS(Status)) { LogError("StoreInitialize (%08x)\n", Status); goto fail; } Status = GnttabInitialize(); if (!NT_SUCCESS(Status)) { LogError("GnttabInitialize (%08x)\n", Status); goto fail; } // Hack! force all targets to closed (if not already), so backends dont lock // creating the dump target will transition via closed anyway Status = FdoCloseAllTargets(); if (!NT_SUCCESS(Status)) { LogError("FdoCloseAllTargets (%08x)\n", Status); goto fail; } Status = FdoFindTarget(Fdo); if (!NT_SUCCESS(Status)) { LogError("FdoFindTarget (%08x)\n", Status); goto fail; } LogTrace("<==== TRUE\n"); return TRUE; fail: LogTrace("<==== FALSE\n"); return FALSE; } VOID FdoTerminate( IN PXENVBD_FDO Fdo ) { LogTrace("====>\n"); DriverUnlinkFdo(Fdo); if (Fdo->Target) PdoDestroy(Fdo->Target); Fdo->Target = NULL; GnttabTerminate(); StoreTerminate(); HvmTerminate(); LogTrace("<====\n"); } //============================================================================= // Query Methods ULONG FdoSizeofXenvbdFdo( ) { return (ULONG)sizeof(XENVBD_FDO); } PXENVBD_PDO FdoGetPdo( IN PXENVBD_FDO Fdo ) { return Fdo->Target; } //============================================================================= // SRB Methods FORCEINLINE VOID FdoCompleteSrb( IN PXENVBD_FDO Fdo, IN PSCSI_REQUEST_BLOCK Srb ) { StorPortNotification(RequestComplete, Fdo, Srb); } //============================================================================= // StorPort Methods BOOLEAN FdoResetBus( IN PXENVBD_FDO Fdo ) { PXENVBD_PDO Pdo; LogTrace("===> (Irql=%d)\n", KeGetCurrentIrql()); Pdo = Fdo->Target; if (Pdo) { PdoReference(Pdo); PdoReset(Pdo); PdoDereference(Pdo); } LogTrace("<=== TRUE (Irql=%d)\n", KeGetCurrentIrql()); return TRUE; } SCSI_ADAPTER_CONTROL_STATUS FdoAdapterControl( IN PXENVBD_FDO Fdo, IN SCSI_ADAPTER_CONTROL_TYPE ControlType, IN PVOID Parameters ) { LogTrace("%s ===> (Irql=%d)\n", ScsiAdapterControlTypeName(ControlType), KeGetCurrentIrql()); UNREFERENCED_PARAMETER(Fdo); switch (ControlType) { case ScsiQuerySupportedControlTypes: { PSCSI_SUPPORTED_CONTROL_TYPE_LIST List = Parameters; #define SET_SUPPORTED(_l, _i, _v) \ if (_l->MaxControlType > _i) _l->SupportedTypeList[_i] = _v; SET_SUPPORTED(List, 0, TRUE); // ScsiQuerySupportedControlTypes SET_SUPPORTED(List, 1, TRUE); // ScsiStopAdapter SET_SUPPORTED(List, 2, TRUE); // ScsiRestartAdapter SET_SUPPORTED(List, 3, TRUE); // ScsiSetBootConfig SET_SUPPORTED(List, 4, TRUE); // ScsiSetRunningConfig #undef SET_SUPPORTED } break; default: LogVerbose("%s\n", ScsiAdapterControlTypeName(ControlType)); break; } LogTrace("%s <=== ScsiAdapterControlSuccess (Irql=%d)\n", ScsiAdapterControlTypeName(ControlType), KeGetCurrentIrql()); return ScsiAdapterControlSuccess; } ULONG FdoFindAdapter( IN PXENVBD_FDO Fdo, IN OUT PPORT_CONFIGURATION_INFORMATION ConfigInfo ) { LogTrace("===> (Irql=%d)\n", KeGetCurrentIrql()); if (!FdoInitialize(Fdo)) { LogTrace("<=== SP_RETURN_BAD_CONFIG (Irql=%d)\n", KeGetCurrentIrql()); return SP_RETURN_BAD_CONFIG; } // setup config info ConfigInfo->MaximumTransferLength = XENVBD_MAX_TRANSFER_LENGTH; ConfigInfo->NumberOfPhysicalBreaks = XENVBD_MAX_PHYSICAL_BREAKS; ConfigInfo->AlignmentMask = 0; // Byte-Aligned ConfigInfo->NumberOfBuses = 1; ConfigInfo->InitiatorBusId[0] = 1; ConfigInfo->ScatterGather = TRUE; ConfigInfo->Master = TRUE; ConfigInfo->CachesData = FALSE; ConfigInfo->MapBuffers = STOR_MAP_NON_READ_WRITE_BUFFERS; ConfigInfo->MaximumNumberOfTargets = XENVBD_MAX_TARGETS; ConfigInfo->MaximumNumberOfLogicalUnits = 1; ConfigInfo->WmiDataProvider = FALSE; // should be TRUE ConfigInfo->SynchronizationModel = StorSynchronizeFullDuplex; if (ConfigInfo->Dma64BitAddresses == SCSI_DMA64_SYSTEM_SUPPORTED) { LogTrace("64bit DMA\n"); ConfigInfo->Dma64BitAddresses = SCSI_DMA64_MINIPORT_SUPPORTED; } LogTrace("<=== SP_RETURN_FOUND (Irql=%d)\n", KeGetCurrentIrql()); return SP_RETURN_FOUND; } BOOLEAN FdoBuildIo( IN PXENVBD_FDO Fdo, IN PSCSI_REQUEST_BLOCK Srb ) { PXENVBD_SRBEXT SrbExt = GetSrbExt(Srb); RtlZeroMemory(SrbExt, sizeof(XENVBD_SRBEXT)); Srb->SrbStatus = SRB_STATUS_INVALID_REQUEST; switch (Srb->Function) { case SRB_FUNCTION_EXECUTE_SCSI: case SRB_FUNCTION_RESET_DEVICE: case SRB_FUNCTION_FLUSH: case SRB_FUNCTION_SHUTDOWN: return TRUE; // dont pass to StartIo case SRB_FUNCTION_ABORT_COMMAND: LogVerbose("SRB_FUNCTION_ABORT_COMMAND -> SRB_STATUS_ABORT_FAILED\n"); Srb->SrbStatus = SRB_STATUS_ABORT_FAILED; break; case SRB_FUNCTION_RESET_BUS: LogVerbose("SRB_FUNCTION_RESET_BUS -> SRB_STATUS_SUCCESS\n"); Srb->SrbStatus = SRB_STATUS_SUCCESS; FdoResetBus(Fdo); break; default: LogVerbose("Ignoring SRB %02x\n", Srb->Function); break; } StorPortNotification(RequestComplete, Fdo, Srb); StorPortNotification(NextRequest, Fdo); return FALSE; } static FORCEINLINE PCHAR SrbFunctionName( IN UCHAR Func ) { switch (Func) { case SRB_FUNCTION_EXECUTE_SCSI: return "EXECUTE_SCSI"; case SRB_FUNCTION_RESET_DEVICE: return "RESET_DEVICE"; case SRB_FUNCTION_FLUSH: return "FLUSH"; case SRB_FUNCTION_SHUTDOWN: return "SHUTDOWN"; case SRB_FUNCTION_ABORT_COMMAND:return "ABORT_COMMAND"; case SRB_FUNCTION_RESET_BUS: return "RESET_BUS"; default: return "UNKNOWN"; } } BOOLEAN FdoStartIo( IN PXENVBD_FDO Fdo, IN PSCSI_REQUEST_BLOCK Srb ) { PXENVBD_PDO Pdo = NULL; BOOLEAN CompleteSrb = TRUE; if (Fdo->Target) { Pdo = Fdo->Target; PdoReference(Pdo); } if (Pdo) { CompleteSrb = PdoStartIo(Pdo, Srb); PdoDereference(Pdo); } else { LogVerbose("No PDO for SRB %s\n", SrbFunctionName(Srb->Function)); } if (CompleteSrb) { FdoCompleteSrb(Fdo, Srb); } StorPortNotification(NextRequest, Fdo); return TRUE; }
xenserver/win-xenvbd
src/xencrsh/fdo.c
C
bsd-2-clause
12,972
package com.clarifi.reporting package ermine.parsing import com.clarifi.reporting.ermine.MonadicPlus import com.clarifi.reporting.ermine.Document import com.clarifi.reporting.ermine.Document.{ text, fillSep } import scala.collection.immutable.List import scalaz.{ Monad } import scalaz.Scalaz._ import scalaz.Free.{ suspend, Return, Trampoline } import scalaz.Ordering._ import Supply._ /** A parser with a nice error handling * * @author EAK */ abstract class Parser[+A] extends MonadicPlus[Parser,A] { that => def self = that def apply(s: ParseState, vs: Supply): Trampoline[ParseResult[A]] def run(s: ParseState, vs: Supply): Either[Err, (ParseState, A)] = apply(s,vs).run match { case Pure(a,_) => Right((s,a)) case Commit(t,a,_) => Right((t,a)) case Fail(b,aux,xs) => Left(Err.report(s.loc,b,aux,xs)) case e: Err => Left(e) } // functorial def map[B](f: A => B) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).map(_ map f) } // filtered def lift[B](p: Parser[B]) = p def withFilter(p : A => Boolean): Parser[A] = new Parser[A] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case Pure(a,e) if !p(a) => e case Commit(t,a,xs) if !p(a) => Err.report(t.loc,None,List(),xs) case r => r } } override def filterMap[B](f: A => Option[B]) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case Pure(a,e) => f(a) match { case Some(b) => Pure(b, e) case None => e } case Commit(s,a,xs) => f(a) match { case Some(b) => Commit(s,b,xs) case None => Err.report(s.loc, None, List()) } case r : ParseFailure => r } } // monadic def flatMap[B](f: A => Parser[B]) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).flatMap { case r@Pure(a, e) => f(a)(s, vs).map { case Pure(b, ep) => Pure(b, e ++ ep) case r : Fail => e ++ r case r => r } case Commit(t, a, xs) => f(a)(t, vs).map { case Pure(b, Fail(_, _, ys)) => Commit(t, b, xs ++ ys) case Fail(e, aux, ys) => Err.report(t.loc, e, aux, xs ++ ys) case r => r } case r : ParseFailure => suspend(Return(r)) } } def wouldSucceed: Parser[Boolean] = new Parser[Boolean] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case e : ParseFailure => Pure(false) case _ => Pure(true) } } def race[B >: A](p: Parser[B]) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).flatMap { case e : Fail => p(s, vs) map { case ep : Fail => e ++ ep case Pure(b, ep) => Pure(b, e ++ ep) case r => r } case e@Err(l,msg,aux,stk) => p(s, vs) map { case _ : Fail => e case ep@Err(lp,msgp,auxp,stkp) => (l ?|? ep.loc) match { case LT => ep case EQ => e // Err(l, msg, aux ++ List(ep.pretty), stk) case GT => e } case r => r } case r => suspend(Return(r)) } } // monadicplus def |[B >: A](other: => Parser[B]) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).flatMap { case e : Fail => other(s, vs).map { case ep : Fail => e ++ ep case Pure(a, ep) => Pure(a, e ++ ep) case r => r } case r => suspend(Return(r)) } } def orElse[B >: A](b: => B) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case e : Fail => Pure(b, e) case r => r } } // context def scope(desc: String) = new Parser[A] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case Fail(m, aux, _) => Fail(m, aux, Set(desc)) case Err(p,d,aux,stk) if s.tracing => Err(p,d,aux,(s.loc,desc)::stk) case Pure(a, Fail(m : Some[Document], aux, _)) => Pure(a, Fail(m, aux, Set(desc))) // TODO: can we drop the Some? case r => r } } // allow backtracking to retry after a parser state change def attempt = new Parser[A] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case e@Err(p,d,aux,stk) => Fail(None, List(e.pretty), Set()) // we can attach the current message, now! case r => r } } def attempt(s: String): Parser[A] = attempt scope s def not = new Parser[Unit] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case Pure(a, _) => Fail(Some("unexpected" :+: text(a.toString))) case Commit(t, a, _) => Err.report(s.loc, Some("unexpected" :+: text(a.toString)), List(), Set()) case _ => Pure(()) } } def handle[B >: A](f: ParseFailure => Parser[B]) = new Parser[B] { def apply(s: ParseState, vs: Supply) = that(s, vs).flatMap { case r : Err => f(r)(s, vs) case r@Fail(e, aux, xs) => f(r)(s, vs).map { case Fail(ep, auxp, ys) => Fail(ep orElse e, if (ep.isDefined) auxp else aux, xs ++ ys) case r => r } case r => suspend(Return(r)) } } def slice = new Parser[String] { def apply(s: ParseState, vs: Supply) = that(s, vs).map { case Pure(_, e) => Pure("", e) case Commit(t, _, xs) => Commit(t, s.input.substring(s.offset, t.offset), xs) // s.rest.take(s.rest.length - t.rest.length), xs) case r : ParseFailure => r } } def when(b: Boolean) = if (b) skip else Parser((_,_) => Pure(())) } object Parser { def apply[A](f: (ParseState, Supply) => ParseResult[A]) = new Parser[A] { def apply(s: ParseState, vs: Supply) = suspend(Return(f(s, vs))) } }
ermine-language/ermine-legacy
src/main/scala/com/clarifi/reporting/ermine/parsing/Parser.scala
Scala
bsd-2-clause
5,671
class Mapture < Cask version '0.0.16' sha256 '54301ca09e3f781dd979fc41978ee2dc547c56bc5776d4b25876bad1ab37b85d' url "http://anatoo.jp/mapture/Mapture-#{version}.app.zip" homepage 'http://anatoo.jp/mapture/' app "Mapture-#{version}.app" end
gregkare/homebrew-cask
Casks/mapture.rb
Ruby
bsd-2-clause
252
<!DOCTYPE HTML> <html> <head> <title>Marker/GPS 2 Reverse Geocoding - Asynchronous</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <link href="mapBasic.css" rel="stylesheet" type="text/css" media="screen" title="no title"> <style> * {margin:0;padding:0;font-size:large;} #feedback, #content {border:black solid 1px;height:5em;text-align:right;} .a {margin:1em;} .b {margin:0.2em;padding:0.2em;} </style> <script src='gpsNotepad.js' type="text/javascript"></script> <script src='gps.js' type="text/javascript"></script> <script src='gps2rgeo_marker.js' type="text/javascript"></script> <script> </script> </head> <body > <div id='mapBasic'> </div> <div id='feedback'> <span id=faddress class=a></span> </div> <div id='content'> <span id=city class=b></span><br /> <span id=state class=b></span> </div> <script> /* The map we draw */ var gMapObject = {}; gMapObject.gMap = {}; gMapObject.gElementID = 'mapBasic'; gMapObject.gZoomSize = 15; // hacker dojo gMapObject.gLat = 37.402937; // 37.8623390197754; gMapObject.gLon = -122.049943; // -122.430931091309; /* hook to libraries */ var RevGEO = {}; // function initializeGeo() { RevGEO = reverseGeocode(); //RevGEO.loadMap(gMapObject); //RevGEO.reverseGeocode({lat: gMapObject.gLat, lng: gMapObject.gLon}, drawstuff); console.log('init map done.'); /* GPS */ pgGL = pgGeoLocation(ui_GPSonSuccess, ui_GPSonError); // Hook GPS to our view pgGL.getLocation(); // one short GPS lookup //pgGL.watchLocation(); // background GPS lookup // NOTE: MAP DRAWING is now moves in 'ui_GPSonSuccess' }; // function drawstuff(results) { // Full address document.getElementById('faddress').innerHTML = results.formatted_address; // City document.getElementById('city').innerHTML = RevGEO.decodeResults(results.address_components, 'locality'); // State document.getElementById('state').innerHTML = RevGEO.decodeResults(results.address_components, 'administrative_area_level_1'); }; // Google Maps loadGeoLibraries('initializeGeo'); </script> </body> </html>
jessemonroy650/googleMapExamples
gps2rgeo/gps2rgeo_marker.html
HTML
bsd-2-clause
2,587
/* * Copyright 2010 the original author or authors. * * 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. */ package org.gradle.api.internal.resource; import java.io.File; import java.net.URI; public class DelegatingResource implements Resource { private final Resource resource; public DelegatingResource(Resource resource) { this.resource = resource; } public Resource getResource() { return resource; } public String getDisplayName() { return resource.getDisplayName(); } public File getFile() { return resource.getFile(); } public URI getURI() { return resource.getURI(); } public boolean getExists() { return resource.getExists(); } public String getText() { return resource.getText(); } }
Pushjet/Pushjet-Android
gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core/org/gradle/api/internal/resource/DelegatingResource.java
Java
bsd-2-clause
1,328
package git import ( "github.com/stvp/assert" "testing" ) func TestContains(t *testing.T) { assert.True(t, contains([]string{"a", "b", "c"}, "b")) assert.False(t, contains([]string{"a", "b", "c"}, "d")) assert.False(t, contains([]string{"a", "b", "c"}, "A")) assert.False(t, contains([]string{"a", "b", "c"}, "ab")) assert.False(t, contains([]string{}, "d")) }
git-comment/git-comment
git/remote_test.go
GO
bsd-2-clause
370
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_51) on Fri Mar 06 12:54:24 CET 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>SandboxConnection</title> <meta name="date" content="2015-03-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SandboxConnection"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxStreamHandler.html" title="class in org.jetel.util.protocols.sandbox"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/jetel/util/protocols/sandbox/SandboxConnection.html" target="_top">Frames</a></li> <li><a href="SandboxConnection.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_java.net.URLConnection">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.jetel.util.protocols.sandbox</div> <h2 title="Class SandboxConnection" class="title">Class SandboxConnection</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.net.URLConnection</li> <li> <ul class="inheritance"> <li>org.jetel.util.protocols.sandbox.SandboxConnection</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">SandboxConnection</span> extends java.net.URLConnection</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_java.net.URLConnection"> <!-- --> </a> <h3>Fields inherited from class&nbsp;java.net.URLConnection</h3> <code>allowUserInteraction, connected, doInput, doOutput, ifModifiedSince, url, useCaches</code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier</th> <th class="colLast" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected </code></td> <td class="colLast"><code><strong><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxConnection.html#SandboxConnection(java.net.URL)">SandboxConnection</a></strong>(java.net.URL&nbsp;url)</code> <div class="block">SFTP constructor.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxConnection.html#connect()">connect</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.io.InputStream</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxConnection.html#getInputStream()">getInputStream</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.io.OutputStream</code></td> <td class="colLast"><code><strong><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxConnection.html#getOutputStream()">getOutputStream</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.net.URLConnection"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.net.URLConnection</h3> <code>addRequestProperty, getAllowUserInteraction, getConnectTimeout, getContent, getContent, getContentEncoding, getContentLength, getContentLengthLong, getContentType, getDate, getDefaultAllowUserInteraction, getDefaultRequestProperty, getDefaultUseCaches, getDoInput, getDoOutput, getExpiration, getFileNameMap, getHeaderField, getHeaderField, getHeaderFieldDate, getHeaderFieldInt, getHeaderFieldKey, getHeaderFieldLong, getHeaderFields, getIfModifiedSince, getLastModified, getPermission, getReadTimeout, getRequestProperties, getRequestProperty, getURL, getUseCaches, guessContentTypeFromName, guessContentTypeFromStream, setAllowUserInteraction, setConnectTimeout, setContentHandlerFactory, setDefaultAllowUserInteraction, setDefaultRequestProperty, setDefaultUseCaches, setDoInput, setDoOutput, setFileNameMap, setIfModifiedSince, setReadTimeout, setRequestProperty, setUseCaches, toString</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="SandboxConnection(java.net.URL)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>SandboxConnection</h4> <pre>protected&nbsp;SandboxConnection(java.net.URL&nbsp;url)</pre> <div class="block">SFTP constructor.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>graph</code> - </dd><dd><code>url</code> - </dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getInputStream()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInputStream</h4> <pre>public&nbsp;java.io.InputStream&nbsp;getInputStream() throws java.io.IOException</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>getInputStream</code>&nbsp;in class&nbsp;<code>java.net.URLConnection</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="getOutputStream()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getOutputStream</h4> <pre>public&nbsp;java.io.OutputStream&nbsp;getOutputStream() throws java.io.IOException</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>getOutputStream</code>&nbsp;in class&nbsp;<code>java.net.URLConnection</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="connect()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>connect</h4> <pre>public&nbsp;void&nbsp;connect() throws java.io.IOException</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>connect</code>&nbsp;in class&nbsp;<code>java.net.URLConnection</code></dd> <dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../org/jetel/util/protocols/sandbox/SandboxStreamHandler.html" title="class in org.jetel.util.protocols.sandbox"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/jetel/util/protocols/sandbox/SandboxConnection.html" target="_top">Frames</a></li> <li><a href="SandboxConnection.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_java.net.URLConnection">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <address>Copyright &#169; 2002-2015 Javlin a.s.</address> </small></p> </body> </html>
chris-watson/chpl-api
chpl/chpl-etl/javadoc/org/jetel/util/protocols/sandbox/SandboxConnection.html
HTML
bsd-2-clause
12,451
/* | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith */ #include <stdio.h> #include <math.h> #include "lisp.h" /************************************************************************* ** (member exp list) Will return the sublist of list beginning with exp** ** if that list is (equal) to exp. Otherwise it returns nil. ** *************************************************************************/ struct conscell *bumember(form) struct conscell *form; { struct conscell *list,*exp; if ((form!=NULL)&&(form->cdrp != NULL)) { exp = form->carp; form = form->cdrp; if ((form!=NULL)&&(form->cdrp == NULL)) { for(list = form->carp; list != NULL; list = list->cdrp) { if (list->celltype != CONSCELL) return(NULL); if (equal(list->carp,exp)) return(list); }; return(NULL); }; }; ierror("member"); /* doesn't return */ return NULL; /* keep compiler happy */ }
blakemcbride/PC-LISP
src/bumember.c
C
bsd-2-clause
1,051
#pragma once #include "event_base.h" namespace handy { // Tcp连接,使用引用计数 struct TcpConn : public std::enable_shared_from_this<TcpConn>, private noncopyable { // Tcp连接的个状态 enum State { Invalid = 1, Handshaking, Connected, Closed, Failed, }; // Tcp构造函数,实际可用的连接应当通过createConnection创建 TcpConn(); virtual ~TcpConn(); //可传入连接类型,返回智能指针 template <class C = TcpConn> static TcpConnPtr createConnection(EventBase *base, const std::string &host, unsigned short port, int timeout = 0, const std::string &localip = "") { TcpConnPtr con(new C); con->connect(base, host, port, timeout, localip); return con; } template <class C = TcpConn> static TcpConnPtr createConnection(EventBase *base, int fd, Ip4Addr local, Ip4Addr peer) { TcpConnPtr con(new C); con->attach(base, fd, local, peer); return con; } bool isClient() { return destPort_ > 0; } // automatically managed context. allocated when first used, deleted when destruct template <class T> T &context() { return ctx_.context<T>(); } EventBase *getBase() { return base_; } State getState() { return state_; } // TcpConn的输入输出缓冲区 Buffer &getInput() { return input_; } Buffer &getOutput() { return output_; } Channel *getChannel() { return channel_; } bool writable() { return channel_ ? channel_->writeEnabled() : false; } //发送数据 void sendOutput() { send(output_); } void send(Buffer &msg); void send(const char *buf, size_t len); void send(const std::string &s) { send(s.data(), s.size()); } void send(const char *s) { send(s, strlen(s)); } //数据到达时回调 void onRead(const TcpCallBack &cb) { assert(!readcb_); readcb_ = cb; }; //当tcp缓冲区可写时回调 void onWritable(const TcpCallBack &cb) { writablecb_ = cb; } // tcp状态改变时回调 void onState(const TcpCallBack &cb) { statecb_ = cb; } // tcp空闲回调 void addIdleCB(int idle, const TcpCallBack &cb); //消息回调,此回调与onRead回调冲突,只能够调用一个 // codec所有权交给onMsg void onMsg(CodecBase *codec, const MsgCallBack &cb); //发送消息 void sendMsg(Slice msg); // conn会在下个事件周期进行处理 void close(); //设置重连时间间隔,-1: 不重连,0:立即重连,其它:等待毫秒数,未设置不重连 void setReconnectInterval(int milli) { reconnectInterval_ = milli; } //!慎用。立即关闭连接,清理相关资源,可能导致该连接的引用计数变为0,从而使当前调用者引用的连接被析构 void closeNow() { if (channel_) channel_->close(); } //远程地址的字符串 std::string str() { return peer_.toString(); } public: EventBase *base_; Channel *channel_; Buffer input_, output_; Ip4Addr local_, peer_; State state_; TcpCallBack readcb_, writablecb_, statecb_; std::list<IdleId> idleIds_; TimerId timeoutId_; AutoContext ctx_, internalCtx_; std::string destHost_, localIp_; int destPort_, connectTimeout_, reconnectInterval_; int64_t connectedTime_; std::unique_ptr<CodecBase> codec_; void handleRead(const TcpConnPtr &con); void handleWrite(const TcpConnPtr &con); ssize_t isend(const char *buf, size_t len); void cleanup(const TcpConnPtr &con); void connect(EventBase *base, const std::string &host, unsigned short port, int timeout, const std::string &localip); void reconnect(); void attach(EventBase *base, int fd, Ip4Addr local, Ip4Addr peer); virtual int readImp(int fd, void *buf, size_t bytes) { return ::read(fd, buf, bytes); } virtual int writeImp(int fd, const void *buf, size_t bytes) { return ::write(fd, buf, bytes); } virtual int handleHandshake(const TcpConnPtr &con); }; // Tcp服务器 struct TcpServer : private noncopyable { TcpServer(EventBases *bases); // return 0 on sucess, errno on error int bind(const std::string &host, unsigned short port, bool reusePort = false); static TcpServerPtr startServer(EventBases *bases, const std::string &host, unsigned short port, bool reusePort = false); ~TcpServer() { delete listen_channel_; } Ip4Addr getAddr() { return addr_; } EventBase *getBase() { return base_; } void onConnCreate(const std::function<TcpConnPtr()> &cb) { createcb_ = cb; } void onConnState(const TcpCallBack &cb) { statecb_ = cb; } void onConnRead(const TcpCallBack &cb) { readcb_ = cb; assert(!msgcb_); } // 消息处理与Read回调冲突,只能调用一个 void onConnMsg(CodecBase *codec, const MsgCallBack &cb) { codec_.reset(codec); msgcb_ = cb; assert(!readcb_); } private: EventBase *base_; EventBases *bases_; Ip4Addr addr_; Channel *listen_channel_; TcpCallBack statecb_, readcb_; MsgCallBack msgcb_; std::function<TcpConnPtr()> createcb_; std::unique_ptr<CodecBase> codec_; void handleAccept(); }; typedef std::function<std::string(const TcpConnPtr &, const std::string &msg)> RetMsgCallBack; //半同步半异步服务器 struct HSHA; typedef std::shared_ptr<HSHA> HSHAPtr; struct HSHA { static HSHAPtr startServer(EventBase *base, const std::string &host, unsigned short port, int threads); HSHA(int threads) : threadPool_(threads) {} void exit() { threadPool_.exit(); threadPool_.join(); } void onMsg(CodecBase *codec, const RetMsgCallBack &cb); TcpServerPtr server_; ThreadPool threadPool_; }; } // namespace handy
yedf/handy
handy/conn.h
C
bsd-2-clause
5,839
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """dnspython release version information.""" MAJOR = 1 MINOR = 15 MICRO = 0 RELEASELEVEL = 0x0f SERIAL = 0 if RELEASELEVEL == 0x0f: version = '%d.%d.%d' % (MAJOR, MINOR, MICRO) elif RELEASELEVEL == 0x00: version = '%d.%d.%dx%d' % \ (MAJOR, MINOR, MICRO, SERIAL) else: version = '%d.%d.%d%x%d' % \ (MAJOR, MINOR, MICRO, RELEASELEVEL, SERIAL) hexversion = MAJOR << 24 | MINOR << 16 | MICRO << 8 | RELEASELEVEL << 4 | \ SERIAL # Vendored with EEH version = version +"-vendor"
Varbin/EEH
_vendor/dns/version.py
Python
bsd-2-clause
1,308
--- title: Grove - Finger-clip Heart Rate Sensor category: Sensor bzurl: https://www.seeedstudio.com/Grove-Finger-clip-Heart-Rate-Sensor-p-2425.html oldwikiname: Grove - Finger-clip Heart Rate Sensor prodimagename: Grove-Finger-clip_Heart_Rate_Sensor.jpg surveyurl: https://www.research.net/r/Grove-Finger-clip_Heart_Rate_Sensor sku: 103020024 --- ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Grove-Finger-clip_Heart_Rate_Sensor.jpg) Grove - Finger-clip Heart Rate Sensor is based on PAH8001EI-2G, a high performance and low power CMOS-process optical sensor with Green LED and DSP integrated serving as a Heart Rate Detection(HRD) sensor. This module is based on optical technology which measures the variation human blood movement in the vessel. Low power consumption and flexible power saving mode make it suitable for wearable device. Cause the heart rate sensor chip need high processing speed for the algorithm of heart rate data(), this module integrate a STM32, reserved SWD interface allow users to reprogram the STM32. [![](https://github.com/SeeedDocument/Seeed-WiKi/raw/master/docs/images/300px-Get_One_Now_Banner-ragular.png)](https://www.seeedstudio.com/Grove-Finger-clip-Heart-Rate-Sensor-p-2425.html) ## Specification --- * Ultra-low power consumption, power saving mode during time of no touch movement * Flexible sleep rate control * Integrated the STM32F103 * I2C interface * Heart rate sensor area just 3.0 x 4.7mm * Reserved SWD interface * Working temperature: -20 ~ +60℃ ## Interface Function --- ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Finger-clip_Heart_Rate_Sensor_TOP.jpg) ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Finger-clip_Heart_Rate_Sensor_Bottom.jpg) * 1: Grove Interface * 2: Reserved SWD Interface for programming to STM32 * 3: Heart Rate Sensor ## Usage --- Here, We will provide an example here to show you how to use this sensor. ### Hardware Installation Link the Sensor to I2C port of Seeeduino with Grove Cable. ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Finger-clip_Heart_Rate_Sensor_Connect.jpg) ### Software Part #### With [Arduino](/w/index.php?title=Arduino&amp;action=edit&amp;redlink=1 "Arduino&amp;action=edit&amp;redlink=1") Copy the following code into a new sketch of Arduino and upload the sketch, then you can get heart rate from the Serial Monitor. It may take about a minute to get valid heart rate after you touch your finger with sensor. ``` #include <Wire.h> void setup() { Serial.begin(9600); Serial.println("heart rate sensor:"); Wire.begin(); } void loop() { Wire.requestFrom(0xA0 >> 1, 1); // request 1 bytes from slave device while(Wire.available()) { // slave may send less than requested unsigned char c = Wire.read(); // receive heart rate value (a byte) Serial.println(c, DEC); // print heart rate value } delay(500); } ``` #### With [Mbed](/w/index.php?title=Mbed&amp;action=edit&amp;redlink=1 "Mbed&amp;action=edit&amp;redlink=1") Read a byte from I2C device 0xA0 (8 bit address), it's the heart rate. ``` #include "mbed.h" I2C i2c(I2C_SDA, I2C_SCL); const int addr = 0xA0; int main() { char heart_rate; while (1) { i2c.read(addr, &heart_rate, 1); printf("heart rate: = %d\r\n", heart_rate); } } ``` #### Upgrade firmware We can upgrade the firmware of the heart rate sensor through its bootloader. * The bootloader is located at 0x08000000 - 0x08002000 * The application is located at 0x08002000 - 0x08020000 ##### Hardware Connection ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Firmware_Connection.jpg) * [USB to serial adapter](https://www.seeedstudio.com/CH340G-USB-to-Serial-%28TTL%29-Module%26Adapter-p-2359.html) is required * UART (the Grove connector supports I2C and UART),when upgrade the firmware, the Grove interface run in UART mode. | Grove-Finger-clip_Heart_Rate_Sensor | USB to Serial (TTL) Module&Adapter | |-------------------------------------|------------------------------------| | VCC | VCC | | GND | GND | | SDA | TX | | SCL | RX | ##### Software * Download [Tera Term](https://ttssh2.osdn.jp/index.html.en) Software * Set UART Baud Rate as 115200 ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/BaudRate_Setting.png) * Download [firmware](ttps://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/res/Grove-Finger-clip_Heart_Rate_Sensor_bin.zip) * Select Grove - Finger-clip Heart Rate Sensor.bin ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Select_firmware.png) * Downloading the firmware to Grove-Finger-clip_Heart_Rate_Sensor ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Firmware_download.png) * Firmware download successfully ![](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/img/Finish_Downloading.png) !!!NOTE: Grove - Finger-clip Heart Rate Sensor provide heart rate measurements.However, it is not a medical device. To use the heart rate detection sensor on your wrist, finger or palm, you must: - Fasten the sensor snugly makes tight contact with your skin and maintain table (no motion) while measuring to acquire accurate heart rate.If the sensor does not contact the skin well or have extreme motion while measuring that the heart rate will not be measured correctly. - Sensor's performance is optimized with greater blood flow. On cold days or users have poor circulation(ex: cold hands, fingers and cold feet) the sensor performance (heart rate accuracy) can be impacted because of lower blood flow in the measuring position. ## Resource --- * [Grove - Finger-clip Heart Rate Sensor eagle file](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/res/Grove-Finger-clip_Heart_Rate_Sensor_v1.0_sch_pcb.zip) * [Grove - Finger-clip Heart Rate Sensor bin file](https://github.com/SeeedDocument/Grove-Finger-clip_Heart_Rate_Sensor/raw/master/res/Grove-Finger-clip_Heart_Rate_Sensor_bin.zip)
SeeedDocument/Seeed-WiKi
docs/Grove-Finger-clip_Heart_Rate_Sensor.md
Markdown
bsd-2-clause
6,745
package pointGroups.geometry; import java.io.Serializable; /** * A quaternion is a number from the set a+bi+cj+dk with a,b,c,d real numbers. * The imaginary units i, j, k follow haliton's rules i^2 = j^2 = k^2 = ijk = * -1. Quaternions can be used to represent rotations in R^3 and R^4 (see * {@link UnitQuaternion}). * * @author Alex */ public class Quaternion implements Point, Serializable { /** * */ private static final long serialVersionUID = -2584314271811803851L; /** real unit '1' as {@link Quaternion} */ public final static Quaternion ONE = new Quaternion(1, 0, 0, 0); /** imaginary unit 'i' as {@link Quaternion} */ public final static Quaternion I = new Quaternion(0, 1, 0, 0); /** imaginary unit 'j' as {@link Quaternion} */ public final static Quaternion J = new Quaternion(0, 0, 1, 0); /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final double sigma = (Math.sqrt(5) - 1) / 2; /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final double tau = (Math.sqrt(5) + 1) / 2; /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final Quaternion qw = new Quaternion(-0.5, 0.5, 0.5, 0.5); /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final Quaternion qI = new Quaternion(0, 0.5, sigma * 0.5, tau * 0.5); /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final Quaternion qO = new Quaternion(0, 0, 1 / Math.sqrt(2), 1 / Math.sqrt(2)); /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final Quaternion qT = new Quaternion(0, 1, 0, 0); /** See On Quaternions and Ocontions John H. Conway, Derek A. Smith page 33 */ public static final Quaternion qI2 = new Quaternion((sigma + tau + 1) / 4, (sigma + tau - 1) / 4, (-sigma + tau + 1) / 4, (sigma - tau + 1) / 4); private final static int digits = 5; private final static double r = Math.pow(10, digits); public final double i, j, k, re; /** * Creates a {@link Quaternion} q with given coordinates. * * @param re real coordinate of q * @param i i-coordinate of q * @param j j-coordinate of q * @param k k-coordinate of q */ public Quaternion(final double re, final double i, final double j, final double k) { this.re = re; this.i = i; this.j = j; this.k = k; } protected Quaternion(final double re, final double i, final double j, final double k, final boolean assumeUnit) { double norm = 1d; if (!assumeUnit) norm = 1d / Math.sqrt(i * i + j * j + k * k + re * re); this.re = norm * re; this.i = norm * i; this.j = norm * j; this.k = norm * k; } public Quaternion plus(final Quaternion b) { return new Quaternion(this.re + b.re, this.i + b.i, this.j + b.j, this.k + b.k); } /** * a + minus(a) = 0 * * @return - re, - i, - j, - k */ public Quaternion minus() { return new Quaternion(-this.re, -this.i, -this.j, -this.k); } /** * Multiplication (to the right) of the {@link Quaternion} <code>b</code> * according to the <i>Hamilton product</i>. * * @param b Right factor of multiplication * @return Return a new quaternion q with q = this*b */ public Quaternion mult(final Quaternion b) { Quaternion a = this; double y0, y1, y2, y3; y0 = a.re * b.re - a.i * b.i - a.j * b.j - a.k * b.k; y1 = a.re * b.i + a.i * b.re + a.j * b.k - a.k * b.j; y2 = a.re * b.j - a.i * b.k + a.j * b.re + a.k * b.i; y3 = a.re * b.k + a.i * b.j - a.j * b.i + a.k * b.re; return new Quaternion(y0, y1, y2, y3); } /** * Calculates the conjugate of the quaternion. * * @return The conjugated quaternion */ public Quaternion conjugate() { return new Quaternion(this.re, -this.i, -this.j, -this.k); } /** * Calculates the inverse quaternion. * * @return this^-1 */ public Quaternion inverse() { double mron = 1d / norm(); return new Quaternion(this.re * mron, -this.i * mron, -this.j * mron, -this.k * mron); } /** * Returns the length (norm) of the quaternion. * * @return norm of this */ public double norm() { return Math.sqrt(this.i * this.i + this.j * this.j + this.k * this.k + this.re * this.re); } public double normSquared() { return this.i * this.i + this.j * this.j + this.k * this.k + this.re * this.re; } /** * Creates a new {@link UnitQuaternion} which is the normalized equivalent to * <code>this</code> * * @return unit quaternion representation of <code>this</code> */ public UnitQuaternion asUnit() { double y0, y1, y2, y3; double mron = 1d / norm(); y0 = mron * this.re; y1 = mron * this.i; y2 = mron * this.j; y3 = mron * this.k; return new UnitQuaternion(y0, y1, y2, y3); } /** * Converts the {@link Quaternion} to a {@link Point3D}, the real part is * ignored. * * @return 3d-point */ public Point3D asPoint3D() { return new Point3D(this.i, this.j, this.k); } /** * Interpreted the {@link Quaternion} as four-dimensional vector and returns * it as {@link Point4D} * * @return 4d-point */ public Point4D asPoint4D() { return new Point4D(this.re, this.i, this.j, this.k); } @Override public String toString() { return this.re + " + " + this.i + "i " + this.j + " j" + this.k + " k"; } public static Quaternion fromDouble(final double d) { return new Quaternion(d, 0, 0, 0); } /** * Distance between a and b * * @param a * @param b * @return euclidean distance between a und b */ public static double distance(final Quaternion a, final Quaternion b) { double re = (a.re - b.re) * (a.re - b.re); double i = Math.pow((a.i - b.i), 2); double j = Math.pow((a.j - b.j), 2); double k = Math.pow((a.k - b.k), 2); return Math.sqrt(re + i + j + k); } /** * @return components of the quaternion represented in an array of doubles */ @Override public double[] getComponents() { double[] components = { this.re, this.i, this.j, this.k }; return components; } /** * source code from Jreality */ @Override public int hashCode() { double x = Math.round(r * re) / r; double y = Math.round(r * i) / r; double z = Math.round(r * j) / r; double w = Math.round(r * k) / r; final int PRIME = 31; int result = 1; long temp; temp = Double.doubleToLongBits(w); result = PRIME * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(x); result = PRIME * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(y); result = PRIME * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(z); result = PRIME * result + (int) (temp ^ (temp >>> 32)); return result; } public static boolean isAlmostZero(final double d) { return Math.round(r * d) / r == 0; } /** * source code from Jreality */ @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Quaternion other = (Quaternion) obj; double x1 = Math.round(r * re) / r; double y1 = Math.round(r * i) / r; double z1 = Math.round(r * j) / r; double w1 = Math.round(r * k) / r; double x2 = Math.round(r * other.re) / r; double y2 = Math.round(r * other.i) / r; double z2 = Math.round(r * other.j) / r; double w2 = Math.round(r * other.k) / r; if (x1 == x2 && y1 == y2 && z1 == z2 && w1 == w2) return true; return false; } }
Ryugoron/point-groups
src/main/java/pointGroups/geometry/Quaternion.java
Java
bsd-2-clause
7,848
package org.jcodegen.java; public enum IncDecPosition { BEFORE, AFTER }
cpythoud/java-codegen
src/org/jcodegen/java/IncDecPosition.java
Java
bsd-2-clause
77
// // Copyright (c) 2015, Robert Glissmann // 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. // // 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 HOLDER 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. // // %% license-end-token %% // // Author: [email protected] (Robert Glissmann) // // #ifndef RPC_PACKET_H #define RPC_PACKET_H #include "GenericPacket.h" #include "RpcObject.h" namespace coral { namespace rpc { /// /// The RpcPacket is the netapp transport container for RpcObject requests and /// responses. /// class RpcPacket : public coral::netapp::GenericPacket { public: struct Data { // Payload length in bytes ui32 length; ui32 format; ui32 encoding; }; /// /// Construct an empty packet. The packet will be allocated to the size of /// the Data structure. /// RpcPacket(); /// /// Construct a packet to transport the specified object. /// /// @param object Request or response object /// RpcPacket( const RpcObject& object ); /// /// Retrieve a deserialized request or response object from the payload of /// the packet. /// /// @param object RpcObject to deserialize from the payload of this /// packet. /// @return bool True if the object was successfully deserialized; false /// otherwise /// bool getObject( RpcObject& object ) const; /// /// Allocate the packet from the specified byte buffer. This method /// implements the GenericPacket interface. /// /// @param data_ptr Pointer to data buffer /// @param size_bytes Size of buffer in bytes /// @return bool True if the packet is successfully allocated from the /// buffer; false otherwise /// bool allocate( const void* data_ptr, ui32 size_bytes ); /// /// Get a pointer to the packet header. If the packet has not been /// allocated, NULL is returned. /// /// @return Data* Pointer to packet header /// Data* const data() const; protected: /// /// Swap endianness of packet fields /// void swap( void* data_ptr, ui32 size_bytes ); private: typedef coral::netapp::GenericPacket inherited; }; } // end namespace rpc } // end namespace coral #endif // RPC_PACKET_H
rgmann/coral
includes/rpc/RpcPacket.h
C
bsd-2-clause
3,468
#include "Scene.h" namespace pipeline { }
shanysheng/RenderPipeline
engine/Scene.cpp
C++
bsd-2-clause
53
//================================================================================================= /*! // \file blaze/math/typetraits/HasSIMDExp2.h // \brief Header file for the HasSIMDExp2 type trait // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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 HOLDER 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. */ //================================================================================================= #ifndef _BLAZE_MATH_TYPETRAITS_HASSIMDEXP2_H_ #define _BLAZE_MATH_TYPETRAITS_HASSIMDEXP2_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/system/Vectorization.h> #include <blaze/util/EnableIf.h> #include <blaze/util/IntegralConstant.h> #include <blaze/util/mpl/Or.h> #include <blaze/util/typetraits/Decay.h> #include <blaze/util/typetraits/IsDouble.h> #include <blaze/util/typetraits/IsFloat.h> namespace blaze { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename T // Type of the operand , typename = void > // Restricting condition struct HasSIMDExp2Helper { enum : bool { value = false }; }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ #if BLAZE_SVML_MODE template< typename T > struct HasSIMDExp2Helper< T, EnableIf_< Or< IsFloat<T>, IsDouble<T> > > > { enum : bool { value = bool( BLAZE_SSE_MODE ) || bool( BLAZE_AVX_MODE ) || bool( BLAZE_MIC_MODE ) || bool( BLAZE_AVX512F_MODE ) }; }; #endif /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*!\brief Availability of a SIMD \c exp2() operation for the given data type. // \ingroup math_type_traits // // Depending on the available instruction set (SSE, SSE2, SSE3, SSE4, AVX, AVX2, MIC, ...) and // the used compiler, this type trait provides the information whether a SIMD \c exp2() operation // exists for the given data type \a T (ignoring the cv-qualifiers). In case the SIMD operation // is available, the \a value member constant is set to \a true, the nested type definition // \a Type is \a TrueType, and the class derives from \a TrueType. Otherwise \a value is set // to \a false, \a Type is \a FalseType, and the class derives from \a FalseType. The following // example assumes that the Intel SVML is available: \code blaze::HasSIMDExp2< float >::value // Evaluates to 1 blaze::HasSIMDExp2< double >::Type // Results in TrueType blaze::HasSIMDExp2< const double > // Is derived from TrueType blaze::HasSIMDExp2< unsigned int >::value // Evaluates to 0 blaze::HasSIMDExp2< long double >::Type // Results in FalseType blaze::HasSIMDExp2< complex<double> > // Is derived from FalseType \endcode */ template< typename T > // Type of the operand struct HasSIMDExp2 : public BoolConstant< HasSIMDExp2Helper< Decay_<T> >::value > {}; //************************************************************************************************* } // namespace blaze #endif
Kolkir/blaze-nn
third-party/blaze/include/blaze/math/typetraits/HasSIMDExp2.h
C
bsd-2-clause
5,432
/** * Copyright 2011 Gerco Dries. 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. * * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``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 GERCO DRIES 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. */ package nl.gdries.camel.component.apama; import java.net.URI; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.impl.DefaultComponent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.apama.services.event.EventServiceFactory; import com.apama.services.event.IEventService; /** * This class implements the Apama Camel Component. URI should be in the form of * apama://host:port/channel,channel2,channel3 * <p> * For a component that is only used for sending events, no channel value is * required, but the trailing slash after port must be given. For example: * apama://host:port/ * * @author Gerco Dries */ public class ApamaComponent extends DefaultComponent { public static final String PROCESS_NAME_PARAMETER = "processName"; private final Log log = LogFactory.getLog(getClass()); private String defaultProcessName = "Apama Camel Component"; public ApamaComponent() { } public ApamaComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uriString, String remaining, Map<String, Object> parameters) throws Exception { URI uri = new URI(uriString); String processName = parameters.containsKey(PROCESS_NAME_PARAMETER) ? (String)parameters.get(PROCESS_NAME_PARAMETER) : defaultProcessName; parameters.remove(PROCESS_NAME_PARAMETER); log.info("Connecting to " + uriString); IEventService eventService = EventServiceFactory.createEventService( uri.getHost(), uri.getPort(), processName); String channels = uri.getPath().substring(1); return new ApamaEndpoint(this, eventService, channels); } }
gerco/camel-apama
src/main/java/nl/gdries/camel/component/apama/ApamaComponent.java
Java
bsd-2-clause
2,916
module Emulator.CPU.Instructions.ARM.OpcodesSpec where import Emulator.CPU import Emulator.CPU.Instructions.ARM.Opcodes import Emulator.Types import Control.Lens import Control.Monad.State.Class (MonadState(..)) import Control.Monad.Trans.State import Data.Default.Class import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "cmp" $ do context "CMP _ (r1 = 5) 0" $ do let res = exec (def & r1 .~ 0x5) $ cmp () r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should set carry" $ res ^. flags.carry `shouldBe` True it "should not set overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False context "CMP _ (r1 = 0) 0" $ do let res = exec (def & r1 .~ 0x0) $ cmp () r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should set carry" $ res ^. flags.carry `shouldBe` True it "should not set overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "CMP _ (r1 = a) a" $ do let res = exec (def & r1 .~ 0xA) $ cmp () r1 (operand2Lens $ Right $ Rotated 0 0xA) True it "should set the zero flag, false the negative, carry and overflow" $ do res ^. flags.carry `shouldBe` False res ^. flags.zero `shouldBe` True res ^. flags.overflow `shouldBe` False res ^. flags.negative `shouldBe` False describe "mov" $ do context "MOV r0 _ 5" $ do let res = exec def $ mov r0 () (operand2Lens $ Right $ Rotated 0 5) True it "should not set result" $ res ^. r0 `shouldBe` 0x5 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False context "MOV r0 _ 0" $ do let res = exec def $ mov r0 () (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "MOV r0 _ (r2 = 1 << 2)" $ do let res = exec (def & r2 .~ 0x1) $ mov r0 () (operand2Lens $ Left $ AmountShift 2 LogicalLeft $ RegisterName 2) True it "should not set result" $ res ^. r0 `shouldBe` 0x4 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False context "MOV r0 _ (r2 = 15 << r3 = 2)" $ do let res = exec (def & r2 .~ 0xF & r3 .~ 0x2) $ mov r0 () (operand2Lens $ Left $ RegisterShift (RegisterName 3) LogicalLeft (RegisterName 2)) True it "should not set result" $ res ^. r0 `shouldBe` 0x3C it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False context "MOV r0 _ (r15 = 0x00000000)" $ return () describe "add" $ do context "ADD r0 (r1 = 0) 0" $ do let res = exec def $ add r0 r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "ADD r0 (r1 = 0xFFFFFFFF) (r2 = 0xFFFFFFFF)" $ do let res = exec (def & r1 .~ 0xFFFFFFFF & r2 .~ 0xFFFFFFFF) $ add r0 r1 (operand2Lens $ Left $ AmountShift 0 LogicalLeft $ RegisterName 2) True it "should not set result" $ res ^. r0 `shouldBe` 0xFFFFFFFE it "should set carry" $ res ^. flags.carry `shouldBe` True it "should set overflow" $ res ^. flags.overflow `shouldBe` True it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should set negative" $ res ^. flags.negative `shouldBe` True describe "cmn" $ do context "CMN _ (r1 = 0) 0" $ do let res = exec def $ cmn () r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "CMN _ (r1 = 0) 1" $ do let res = exec def $ cmn () r1 (operand2Lens $ Right $ Rotated 0 1) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False context "CMN _ (r1 = 0xFFFFFFFF) (r2 = 0xFFFFFFFF)" $ do let res = exec (def & r1 .~ 0xFFFFFFFF & r2 .~ 0xFFFFFFFF) $ cmn () r1 (operand2Lens $ Left $ AmountShift 0 LogicalLeft $ RegisterName 2) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should set carry" $ res ^. flags.carry `shouldBe` True it "should set overflow" $ res ^. flags.overflow `shouldBe` True it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should set negative" $ res ^. flags.negative `shouldBe` True describe "teq" $ do context "TEQ _ (r1 = 0) 0" $ do let res = exec (def & r0 .~ 0x1) $ teq () r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x1 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "TEQ _ (r1 = 2) 1" $ do let res = exec (def & r1 .~ 0x2 & flags.zero .~ True) $ teq () r1 (operand2Lens $ Right $ Rotated 0 1) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False describe "orr" $ do context "ORR r0 (r1 = 0) 0" $ do let res = exec def $ orr r0 r1 (operand2Lens $ Right $ Rotated 0 0) True it "should set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "ORR r0 (r1 = 1) 4" $ do let res = exec (def & r1 .~ 0x1) $ orr r0 r1 (operand2Lens $ Right $ Rotated 0 4) True it "should set result" $ res ^. r0 `shouldBe` 0x5 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should not set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False describe "tst" $ do context "TST _ (r1 = 0) 0" $ do let res = exec def $ tst () r1 (operand2Lens $ Right $ Rotated 0 0) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` True it "should not set negative" $ res ^. flags.negative `shouldBe` False context "TST _ (r1 = 3) 2" $ do let res = exec (def & r1 .~ 0x3) $ tst () r1 (operand2Lens $ Right $ Rotated 0 2) True it "should not set result" $ res ^. r0 `shouldBe` 0x0 it "should not affect carry" $ res ^. flags.carry `shouldBe` False it "should not affect overflow" $ res ^. flags.overflow `shouldBe` False it "should set zero" $ res ^. flags.zero `shouldBe` False it "should not set negative" $ res ^. flags.negative `shouldBe` False newtype OpcodeState a = OpcodeState (State Registers a) deriving (Functor, Applicative, Monad, MonadState Registers) exec :: Registers -> OpcodeState () -> Registers exec r (OpcodeState x) = execState x r
intolerable/GroupProject
test/Emulator/CPU/Instructions/ARM/OpcodesSpec.hs
Haskell
bsd-2-clause
10,197
#! /bin/sh # start.sh if [ -z $NODE_PATH ]; then export NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript echo "NODE_PATH updated to ${NODE_PATH}" else echo "NODE_PATH is ${NODE_PATH}" fi delayScript() { sleep 30 cd /opt/geroix/gero node index.js } delayScript &
Geroix/gero
start.sh
Shell
bsd-2-clause
293
#pragma once #include <core/common/basetypes.hpp> namespace runtime { class reflection_probe_system { public: reflection_probe_system(); ~reflection_probe_system(); //----------------------------------------------------------------------------- // Name : frame_update (virtual ) /// <summary> /// /// /// /// </summary> //----------------------------------------------------------------------------- void frame_update(delta_t dt); }; }
volcoma/EtherealEngine
engine/runtime/ecs/systems/reflection_probe_system.h
C
bsd-2-clause
450
package adf.util.map; import adf.util.compatibility.WorldData; import rescuecore2.misc.Pair; import rescuecore2.misc.geometry.Point2D; import rescuecore2.standard.entities.*; import rescuecore2.worldmodel.EntityID; import java.util.List; public class DistanceUtil { /** * 2つの座標から距離を求めます. * * @param positionX 1つ目の座標のX成分 * @param positionY 1つ目の座標のY成分 * @param anotherX 2つ目の座標のX成分 * @param anotherY 2つ目の座標のY成分 * @return 2つの座標間の距離 */ public static double getDistance(double positionX, double positionY, double anotherX, double anotherY) { double dx = positionX - anotherX; double dy = positionY - anotherY; return Math.hypot(dx, dy); } /** * 2つの座標から距離を求めます. * * @param position 1つ目の座標 * @param another 2つ目の座標 * @return 2つの座標間の距離 */ public static double getDistance(Pair<Integer, Integer> position, Pair<Integer, Integer> another) { return getDistance(position.first(), position.second(), another.first(), another.second()); } /** * 2つの座標から距離を求めます. * * @param position 1つ目の座標 * @param another 2つ目の座標 * @return 2つの座標間の距離 */ public static double getDistance(Point2D position, Point2D another) { return getDistance(position.getX(), position.getY(), another.getX(), another.getY()); } /** * 2つのEdgeの直線距離を求めます. * * @param position 1つ目のEdge * @param another 2つ目のEdge * @see rescuecore2.standard.entities.Area * @see rescuecore2.standard.entities.Edge * @return 2つのEdge間の直線距離 */ public static double getDistance(Edge position, Edge another) { return getDistance(PositionUtil.getEdgePoint(position), PositionUtil.getEdgePoint(another)); } /** * 2つの座標から距離を求めます. * * @param position 1つ目の座標 * @param another 2つ目の座標 * @return 2つの座標間の距離 */ public static double getDistance(Pair<Integer, Integer> position, Point2D another) { return getDistance(position.first(), position.second(), another.getX(), another.getY()); } /** * Get the maxDistance between two entities. * * @param world World Object * @param first The ID of the first entity. * @param second The ID of the second entity. * @return The maxDistance between the two entities. A negative value indicates that one or both objects either doesn't exist or could not be located. */ public static double getDistance(WorldData world, EntityID first, EntityID second) { return getDistance(world.getWorldObject(), first, second); } /** * Get the maxDistance between two entities. * * @param world World Object * @param first The ID of the first entity. * @param second The ID of the second entity. * @return The maxDistance between the two entities. A negative value indicates that one or both objects either doesn't exist or could not be located. */ public static double getDistance(StandardWorldModel world, EntityID first, EntityID second) { StandardEntity a = world.getEntity(first); StandardEntity b = world.getEntity(second); if (a == null || b == null) { return -1; } return getDistance(world, a, b); } /** * Get the maxDistance between two entities. * * @param world World Object * @param first The first entity. * @param second The second entity. * @return The maxDistance between the two entities. A negative value indicates that one or both objects could not be located. */ public static double getDistance(WorldData world, StandardEntity first, StandardEntity second) { return getDistance(world.getWorldObject(), first, second); } /** * Get the maxDistance between two entities. * * @param world World Object * @param first The first entity. * @param second The second entity. * @return The maxDistance between the two entities. A negative value indicates that one or both objects could not be located. */ public static double getDistance(StandardWorldModel world, StandardEntity first, StandardEntity second) { Pair<Integer, Integer> a = first.getLocation(world); Pair<Integer, Integer> b = second.getLocation(world); if (a == null || b == null) { return -1; } return getDistance(a, b); } /** * 比較のための距離を求めます.<br> * {@link Math#hypot(double, double)}を行わず,Xの差,Yの差をそれぞれ2乗し足しあわせています. * * @param position 1つ目の座標 * @param another 2つ目の座標 * @return 2つの座標間の距離 */ public static long valueOfCompare(Pair<Integer, Integer> position, Pair<Integer, Integer> another) { long dx = position.first() - another.first(); long dy = position.second() - another.second(); return dx*dx + dy*dy; } /** * 比較のための距離を求めます.<br> * {@link Math#hypot(double, double)}を行わず,Xの差,Yの差をそれぞれ2乗し足しあわせています. * * @param position 1つ目の座標 * @param another 2つ目の座標 * @return 2つの座標間の距離 */ public static double valueOfCompare(Point2D position, Point2D another) { return valueOfCompare(position.getX(), position.getY(), another.getX(), another.getY()); } /** * 比較のための距離を求めます.<br> * {@link Math#hypot(double, double)}を行わず,Xの差,Yの差をそれぞれ2乗し足しあわせています. * * @param positionX 1つ目の座標のX成分 * @param positionY 1つ目の座標のY成分 * @param anotherX 2つ目の座標のX成分 * @param anotherY 2つ目の座標のY成分 * @return 2つの座標間の距離 */ public static double valueOfCompare(double positionX, double positionY, double anotherX, double anotherY) { double dX = positionX - anotherX; double dY = positionY - anotherY; return (dX * dX) + (dY * dY); } /** * 移動パスの距離を求めます. * * @param world World * @param path 移動パス * @return 移動パスの距離 */ public static double getPathDistance(WorldData world, List<EntityID> path) { return getPathDistance(world.getWorldObject(), path); } /** * 移動パスの距離を求めます. * * @param world World * @param path 移動パス * @return 移動パスの距離 */ public static double getPathDistance(StandardWorldModel world, List<EntityID> path) { double distance = 0.0D; int limit = path.size() - 1; Area area = (Area)world.getEntity(path.get(0)); distance += getDistance(area.getLocation(world), PositionUtil.getEdgePoint(area.getEdgeTo(path.get(1)))); area = (Area)world.getEntity(path.get(limit)); distance += getDistance(area.getLocation(world), PositionUtil.getEdgePoint(area.getEdgeTo(path.get(limit - 1)))); EntityID areaID; for(int i = 1; i < limit; i++) { areaID = path.get(i); area = (Area)world.getEntity(areaID); distance += getDistance(area.getEdgeTo(path.get(i - 1)), area.getEdgeTo(path.get(i + 1))); } return distance; } /** * Humanの実際に移動した距離を求めます. * * @param human 移動したHuman * @return 移動距離 */ public static double getMoveDistance(Human human) { int[] array = human.getPositionHistory(); double result = 0.0D; int limit = array.length - 2; for(int i = 0; i < limit; i+=2) { result += getDistance(array[i], array[i + 1], array[i + 2], array[i + 3]); } return result; } }
tkmnet/RCRS-ADF
modules/util/src/main/java/adf/util/map/DistanceUtil.java
Java
bsd-2-clause
8,343
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2010 Sangwoo Im http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * @ignore */ cc.SCROLLVIEW_DIRECTION_NONE = -1; cc.SCROLLVIEW_DIRECTION_HORIZONTAL = 0; cc.SCROLLVIEW_DIRECTION_VERTICAL = 1; cc.SCROLLVIEW_DIRECTION_BOTH = 2; var SCROLL_DEACCEL_RATE = 0.95; var SCROLL_DEACCEL_DIST = 1.0; var BOUNCE_DURATION = 0.15; var INSET_RATIO = 0.2; var MOVE_INCH = 7.0/160.0; var BOUNCE_BACK_FACTOR = 0.35; cc.convertDistanceFromPointToInch = function(pointDis){ var eglViewer = cc.view; var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2; return (pointDis * factor) / 160; // CCDevice::getDPI() default value }; cc.ScrollViewDelegate = cc.Class.extend({ scrollViewDidScroll:function (view) { }, scrollViewDidZoom:function (view) { } }); /** * ScrollView support for cocos2d -x. * It provides scroll view functionalities to cocos2d projects natively. * @class * @extend cc.Layer * * @property {cc.Point} minOffset - <@readonly> The current container's minimum offset * @property {cc.Point} maxOffset - <@readonly> The current container's maximum offset * @property {Boolean} bounceable - Indicate whether the scroll view is bounceable * @property {cc.Size} viewSize - The size of the scroll view * @property {cc.Layer} container - The inside container of the scroll view * @property {Number} direction - The direction allowed to scroll: cc.SCROLLVIEW_DIRECTION_BOTH by default, or cc.SCROLLVIEW_DIRECTION_NONE | cc.SCROLLVIEW_DIRECTION_HORIZONTAL | cc.SCROLLVIEW_DIRECTION_VERTICAL * @property {cc.ScrollViewDelegate} delegate - The inside container of the scroll view * @property {Boolean} clippingToBounds - Indicate whether the scroll view clips its children */ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ _zoomScale:0, _minZoomScale:0, _maxZoomScale:0, _delegate:null, _direction:cc.SCROLLVIEW_DIRECTION_BOTH, _dragging:false, _contentOffset:null, _container:null, _touchMoved:false, _maxInset:null, _minInset:null, _bounceable:false, _clippingToBounds:false, _scrollDistance:null, _touchPoint:null, _touchLength:0, _touches:null, _viewSize:null, _minScale:0, _maxScale:0, //scissor rect for parent, just for restoring GL_SCISSOR_BOX _parentScissorRect:null, _scissorRestored:false, // cache object _tmpViewRect:null, _touchListener: null, _className:"ScrollView", /** * @contructor * @param size * @param container * @returns {ScrollView} */ ctor:function (size, container) { cc.Layer.prototype.ctor.call(this); this._contentOffset = cc.p(0,0); this._maxInset = cc.p(0, 0); this._minInset = cc.p(0, 0); this._scrollDistance = cc.p(0, 0); this._touchPoint = cc.p(0, 0); this._touches = []; this._viewSize = cc.size(0, 0); this._parentScissorRect = new cc.Rect(0,0,0,0); this._tmpViewRect = new cc.Rect(0,0,0,0); if(container != undefined) this.initWithViewSize(size, container); else this.initWithViewSize(cc.size(200, 200), null); }, init:function () { return this.initWithViewSize(cc.size(200, 200), null); }, /** * initialized whether success or fail * @param {cc.Size} size * @param {cc.Node} container * @return {Boolean} */ initWithViewSize:function (size, container) { var pZero = cc.p(0,0); if (cc.Layer.prototype.init.call(this)) { this._container = container; if (!this._container) { this._container = cc.Layer.create(); this._container.ignoreAnchorPointForPosition(false); this._container.setAnchorPoint(pZero); } this.setViewSize(size); this.setTouchEnabled(true); this._touches.length = 0; this._delegate = null; this._bounceable = true; this._clippingToBounds = true; //this._container.setContentSize(CCSizeZero); this._direction = cc.SCROLLVIEW_DIRECTION_BOTH; this._container.setPosition(pZero); this._touchLength = 0.0; this.addChild(this._container); this._minScale = this._maxScale = 1.0; return true; } return false; }, /** * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) * * @param {cc.Point} offset new offset * @param {Number} [animated=] If true, the view will scroll to the new offset */ setContentOffset: function (offset, animated) { if (animated) { //animate scrolling this.setContentOffsetInDuration(offset, BOUNCE_DURATION); return; } if (!this._bounceable) { var minOffset = this.minContainerOffset(); var maxOffset = this.maxContainerOffset(); offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x)); offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y)); } this._container.setPosition(offset); var locDelegate = this._delegate; if (locDelegate != null && locDelegate.scrollViewDidScroll) { locDelegate.scrollViewDidScroll(this); } }, getContentOffset:function () { var locPos = this._container.getPosition(); return cc.p(locPos.x, locPos.y); }, /** * <p>Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) <br/> * You can override the animation duration with this method. * </p> * @param {cc.Point} offset new offset * @param {Number} dt animation duration */ setContentOffsetInDuration:function (offset, dt) { var scroll = cc.MoveTo.create(dt, offset); var expire = cc.CallFunc.create(this._stoppedAnimatedScroll, this); this._container.runAction(cc.Sequence.create(scroll, expire)); this.schedule(this._performedAnimatedScroll); }, /** * Sets a new scale and does that for a predefined duration. * * @param {Number} scale a new scale vale * @param {Boolean} [animated=null] if YES, scaling is animated */ setZoomScale: function (scale, animated) { if (animated) { this.setZoomScaleInDuration(scale, BOUNCE_DURATION); return; } var locContainer = this._container; if (locContainer.getScale() != scale) { var oldCenter, newCenter; var center; if (this._touchLength == 0.0) { var locViewSize = this._viewSize; center = cc.p(locViewSize.width * 0.5, locViewSize.height * 0.5); center = this.convertToWorldSpace(center); } else center = this._touchPoint; oldCenter = locContainer.convertToNodeSpace(center); locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale))); newCenter = locContainer.convertToWorldSpace(oldCenter); var offset = cc.pSub(center, newCenter); if (this._delegate && this._delegate.scrollViewDidZoom) this._delegate.scrollViewDidZoom(this); this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset)); } }, getZoomScale:function () { return this._container.getScale(); }, /** * Sets a new scale for container in a given duration. * * @param {Number} s a new scale value * @param {Number} dt animation duration */ setZoomScaleInDuration:function (s, dt) { if (dt > 0) { var locScale = this._container.getScale(); if (locScale != s) { var scaleAction = cc.ActionTween.create(dt, "zoomScale", locScale, s); this.runAction(scaleAction); } } else { this.setZoomScale(s); } }, /** * Returns the current container's minimum offset. You may want this while you animate scrolling by yourself * @return {cc.Point} Returns the current container's minimum offset. */ minContainerOffset:function () { var locContainer = this._container; var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize; return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(), locViewSize.height - locContentSize.height * locContainer.getScaleY()); }, /** * Returns the current container's maximum offset. You may want this while you animate scrolling by yourself * @return {cc.Point} Returns the current container's maximum offset. */ maxContainerOffset:function () { return cc.p(0.0, 0.0); }, /** * Determines if a given node's bounding box is in visible bounds * @param {cc.Node} node * @return {Boolean} YES if it is in visible bounds */ isNodeVisible:function (node) { var offset = this.getContentOffset(); var size = this.getViewSize(); var scale = this.getZoomScale(); var viewRect = cc.rect(-offset.x / scale, -offset.y / scale, size.width / scale, size.height / scale); return cc.rectIntersectsRect(viewRect, node.getBoundingBox()); }, /** * Provided to make scroll view compatible with SWLayer's pause method */ pause:function (sender) { this._container.pause(); var selChildren = this._container.getChildren(); for (var i = 0; i < selChildren.length; i++) { selChildren[i].pause(); } this._super(); }, /** * Provided to make scroll view compatible with SWLayer's resume method */ resume:function (sender) { var selChildren = this._container.getChildren(); for (var i = 0, len = selChildren.length; i < len; i++) { selChildren[i].resume(); } this._container.resume(); this._super(); }, isDragging:function () { return this._dragging; }, isTouchMoved:function () { return this._touchMoved; }, isBounceable:function () { return this._bounceable; }, setBounceable:function (bounceable) { this._bounceable = bounceable; }, /** * <p> * size to clip. CCNode boundingBox uses contentSize directly. <br/> * It's semantically different what it actually means to common scroll views. <br/> * Hence, this scroll view will use a separate size property. * </p> */ getViewSize:function () { return this._viewSize; }, setViewSize:function (size) { this._viewSize = size; cc.Node.prototype.setContentSize.call(this,size); }, getContainer:function () { return this._container; }, setContainer:function (container) { // Make sure that 'm_pContainer' has a non-NULL value since there are // lots of logic that use 'm_pContainer'. if (!container) return; this.removeAllChildren(true); this._container = container; container.ignoreAnchorPointForPosition(false); container.setAnchorPoint(0, 0); this.addChild(container); this.setViewSize(this._viewSize); }, /** * direction allowed to scroll. CCScrollViewDirectionBoth by default. */ getDirection:function () { return this._direction; }, setDirection:function (direction) { this._direction = direction; }, getDelegate:function () { return this._delegate; }, setDelegate:function (delegate) { this._delegate = delegate; }, /** override functions */ // optional onTouchBegan:function (touch, event) { if (!this.isVisible()) return false; //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition()); //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); var frame = this._getViewRect(); //dispatcher does not know about clipping. reject touches outside visible bounds. var locContainer = this._container; var locPoint = locContainer.convertToWorldSpace(locContainer.convertTouchToNodeSpace(touch)); var locTouches = this._touches; if (locTouches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint)) return false; locTouches.push(touch); //} if (locTouches.length === 1) { // scrolling this._touchPoint = this.convertTouchToNodeSpace(touch); this._touchMoved = false; this._dragging = true; //dragging started this._scrollDistance.x = 0; this._scrollDistance.y = 0; this._touchLength = 0.0; } else if (locTouches.length == 2) { this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(locTouches[0]), this.convertTouchToNodeSpace(locTouches[1])); this._touchLength = cc.pDistance(locContainer.convertTouchToNodeSpace(locTouches[0]), locContainer.convertTouchToNodeSpace(locTouches[1])); this._dragging = false; } return true; }, onTouchMoved:function (touch, event) { if (!this.isVisible()) return; if (this._touches.length === 1 && this._dragging) { // scrolling this._touchMoved = true; //var frameOriginal = this.getParent().convertToWorldSpace(this.getPosition()); //var frame = cc.rect(frameOriginal.x, frameOriginal.y, this._viewSize.width, this._viewSize.height); var frame = this._getViewRect(); //var newPoint = this.convertTouchToNodeSpace(this._touches[0]); var newPoint = this.convertTouchToNodeSpace(touch); var moveDistance = cc.pSub(newPoint, this._touchPoint); var dis = 0.0, locDirection = this._direction, pos; if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL){ dis = moveDistance.y; pos = this._container.getPositionY(); if (!(this.minContainerOffset().y <= pos && pos <= this.maxContainerOffset().y)) moveDistance.y *= BOUNCE_BACK_FACTOR; } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL){ dis = moveDistance.x; pos = this._container.getPositionX(); if (!(this.minContainerOffset().x <= pos && pos <= this.maxContainerOffset().x)) moveDistance.x *= BOUNCE_BACK_FACTOR; }else { dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y); pos = this._container.getPositionY(); var _minOffset = this.minContainerOffset(), _maxOffset = this.maxContainerOffset(); if (!(_minOffset.y <= pos && pos <= _maxOffset.y)) moveDistance.y *= BOUNCE_BACK_FACTOR; pos = this._container.getPositionX(); if (!(_minOffset.x <= pos && pos <= _maxOffset.x)) moveDistance.x *= BOUNCE_BACK_FACTOR; } if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){ //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y); return; } if (!this._touchMoved){ moveDistance.x = 0; moveDistance.y = 0; } this._touchPoint = newPoint; this._touchMoved = true; if (this._dragging) { switch (locDirection) { case cc.SCROLLVIEW_DIRECTION_VERTICAL: moveDistance.x = 0.0; break; case cc.SCROLLVIEW_DIRECTION_HORIZONTAL: moveDistance.y = 0.0; break; default: break; } var locPosition = this._container.getPosition(); var newX = locPosition.x + moveDistance.x; var newY = locPosition.y + moveDistance.y; this._scrollDistance = moveDistance; this.setContentOffset(cc.p(newX, newY)); } } else if (this._touches.length === 2 && !this._dragging) { var len = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]), this._container.convertTouchToNodeSpace(this._touches[1])); this.setZoomScale(this.getZoomScale() * len / this._touchLength); } }, onTouchEnded:function (touch, event) { if (!this.isVisible()) return; if (this._touches.length == 1 && this._touchMoved) this.schedule(this._deaccelerateScrolling); this._touches.length = 0; this._dragging = false; this._touchMoved = false; }, onTouchCancelled:function (touch, event) { if (!this.isVisible()) return; this._touches.length = 0; this._dragging = false; this._touchMoved = false; }, setContentSize: function (size, height) { if (this.getContainer() != null) { if(height === undefined) this.getContainer().setContentSize(size); else this.getContainer().setContentSize(size, height); this.updateInset(); } }, _setWidth: function (value) { var container = this.getContainer(); if (container != null) { container._setWidth(value); this.updateInset(); } }, _setHeight: function (value) { var container = this.getContainer(); if (container != null) { container._setHeight(value); this.updateInset(); } }, getContentSize:function () { return this._container.getContentSize(); }, updateInset:function () { if (this.getContainer() != null) { var locViewSize = this._viewSize; var tempOffset = this.maxContainerOffset(); this._maxInset.x = tempOffset.x + locViewSize.width * INSET_RATIO; this._maxInset.y = tempOffset.y + locViewSize.height * INSET_RATIO; tempOffset = this.minContainerOffset(); this._minInset.x = tempOffset.x - locViewSize.width * INSET_RATIO; this._minInset.y = tempOffset.y - locViewSize.height * INSET_RATIO; } }, /** * Determines whether it clips its children or not. */ isClippingToBounds:function () { return this._clippingToBounds; }, setClippingToBounds:function (clippingToBounds) { this._clippingToBounds = clippingToBounds; }, visit:function (ctx) { // quick return if not visible if (!this.isVisible()) return; var context = ctx || cc._renderContext; var i, locChildren = this._children, selChild, childrenLen; if (cc._renderType === cc._RENDER_TYPE_CANVAS) { context.save(); this.transform(context); this._beforeDraw(context); if (locChildren && locChildren.length > 0) { childrenLen = locChildren.length; this.sortAllChildren(); // draw children zOrder < 0 for (i = 0; i < childrenLen; i++) { selChild = locChildren[i]; if (selChild && selChild._localZOrder < 0) selChild.visit(context); else break; } this.draw(context); // self draw // draw children zOrder >= 0 for (; i < childrenLen; i++) locChildren[i].visit(context); } else{ this.draw(context); // self draw } this._afterDraw(); context.restore(); } else { cc.kmGLPushMatrix(); var locGrid = this.grid; if (locGrid && locGrid.isActive()) { locGrid.beforeDraw(); this.transformAncestors(); } this.transform(context); this._beforeDraw(context); if (locChildren && locChildren.length > 0) { childrenLen = locChildren.length; // draw children zOrder < 0 for (i = 0; i < childrenLen; i++) { selChild = locChildren[i]; if (selChild && selChild._localZOrder < 0) selChild.visit(); else break; } // this draw this.draw(context); // draw children zOrder >= 0 for (; i < childrenLen; i++) locChildren[i].visit(); } else{ this.draw(context); } this._afterDraw(context); if (locGrid && locGrid.isActive()) locGrid.afterDraw(this); cc.kmGLPopMatrix(); } }, addChild:function (child, zOrder, tag) { if (!child) throw new Error("child must not nil!"); zOrder = zOrder || child.getLocalZOrder(); tag = tag || child.getTag(); //child.ignoreAnchorPointForPosition(false); //child.setAnchorPoint(0, 0); if (this._container != child) { this._container.addChild(child, zOrder, tag); } else { cc.Layer.prototype.addChild.call(this, child, zOrder, tag); } }, isTouchEnabled: function(){ return this._touchListener != null; }, setTouchEnabled:function (e) { if(this._touchListener) cc.eventManager.removeListener(this._touchListener); this._touchListener = null; if (!e) { this._dragging = false; this._touchMoved = false; this._touches.length = 0; } else { var listener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE }); if(this.onTouchBegan) listener.onTouchBegan = this.onTouchBegan.bind(this); if(this.onTouchMoved) listener.onTouchMoved = this.onTouchMoved.bind(this); if(this.onTouchEnded) listener.onTouchEnded = this.onTouchEnded.bind(this); if(this.onTouchCancelled) listener.onTouchCancelled = this.onTouchCancelled.bind(this); this._touchListener = listener; cc.eventManager.addListener(listener, this); } }, /** * Init this object with a given size to clip its content. * * @param size view size * @return initialized scroll view object */ _initWithViewSize:function (size) { return null; }, /** * Relocates the container at the proper offset, in bounds of max/min offsets. * * @param animated If YES, relocation is animated */ _relocateContainer:function (animated) { var min = this.minContainerOffset(); var max = this.maxContainerOffset(); var locDirection = this._direction; var oldPoint = this._container.getPosition(); var newX = oldPoint.x; var newY = oldPoint.y; if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { newX = Math.max(newX, min.x); newX = Math.min(newX, max.x); } if (locDirection == cc.SCROLLVIEW_DIRECTION_BOTH || locDirection == cc.SCROLLVIEW_DIRECTION_VERTICAL) { newY = Math.min(newY, max.y); newY = Math.max(newY, min.y); } if (newY != oldPoint.y || newX != oldPoint.x) { this.setContentOffset(cc.p(newX, newY), animated); } }, /** * implements auto-scrolling behavior. change SCROLL_DEACCEL_RATE as needed to choose <br/> * deacceleration speed. it must be less than 1.0. * * @param {Number} dt delta */ _deaccelerateScrolling:function (dt) { if (this._dragging) { this.unschedule(this._deaccelerateScrolling); return; } var maxInset, minInset; var oldPosition = this._container.getPosition(); var locScrollDistance = this._scrollDistance; this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y); if (this._bounceable) { maxInset = this._maxInset; minInset = this._minInset; } else { maxInset = this.maxContainerOffset(); minInset = this.minContainerOffset(); } //check to see if offset lies within the inset bounds var newX = this._container.getPositionX(); var newY = this._container.getPositionY(); locScrollDistance.x = locScrollDistance.x * SCROLL_DEACCEL_RATE; locScrollDistance.y = locScrollDistance.y * SCROLL_DEACCEL_RATE; this.setContentOffset(cc.p(newX, newY)); if ((Math.abs(locScrollDistance.x) <= SCROLL_DEACCEL_DIST && Math.abs(locScrollDistance.y) <= SCROLL_DEACCEL_DIST) || newY > maxInset.y || newY < minInset.y || newX > maxInset.x || newX < minInset.x || newX == maxInset.x || newX == minInset.x || newY == maxInset.y || newY == minInset.y) { this.unschedule(this._deaccelerateScrolling); this._relocateContainer(true); } }, /** * This method makes sure auto scrolling causes delegate to invoke its method */ _performedAnimatedScroll:function (dt) { if (this._dragging) { this.unschedule(this._performedAnimatedScroll); return; } if (this._delegate && this._delegate.scrollViewDidScroll) this._delegate.scrollViewDidScroll(this); }, /** * Expire animated scroll delegate calls */ _stoppedAnimatedScroll:function (node) { this.unschedule(this._performedAnimatedScroll); // After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells. if (this._delegate && this._delegate.scrollViewDidScroll) { this._delegate.scrollViewDidScroll(this); } }, /** * clip this view so that outside of the visible bounds can be hidden. */ _beforeDraw:function (context) { if (this._clippingToBounds) { this._scissorRestored = false; var frame = this._getViewRect(), locEGLViewer = cc.view; var scaleX = this.getScaleX(); var scaleY = this.getScaleY(); var ctx = context || cc._renderContext; if (cc._renderType === cc._RENDER_TYPE_CANVAS) { var getWidth = (this._viewSize.width * scaleX) * locEGLViewer.getScaleX(); var getHeight = (this._viewSize.height * scaleY) * locEGLViewer.getScaleY(); var startX = 0; var startY = 0; ctx.beginPath(); ctx.rect(startX, startY, getWidth, -getHeight); ctx.clip(); ctx.closePath(); } else { var EGLViewer = cc.view; if(EGLViewer.isScissorEnabled()){ this._scissorRestored = true; this._parentScissorRect = EGLViewer.getScissorRect(); //set the intersection of m_tParentScissorRect and frame as the new scissor rect if (cc.rectIntersection(frame, this._parentScissorRect)) { var locPSRect = this._parentScissorRect; var x = Math.max(frame.x, locPSRect.x); var y = Math.max(frame.y, locPSRect.y); var xx = Math.min(frame.x + frame.width, locPSRect.x + locPSRect.width); var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height); EGLViewer.setScissorInPoints(x, y, xx - x, yy - y); } }else{ ctx.enable(ctx.SCISSOR_TEST); //clip EGLViewer.setScissorInPoints(frame.x, frame.y, frame.width, frame.height); } } } }, /** * retract what's done in beforeDraw so that there's no side effect to * other nodes. */ _afterDraw:function (context) { if (this._clippingToBounds && cc._renderType === cc._RENDER_TYPE_WEBGL) { if (this._scissorRestored) { //restore the parent's scissor rect var rect = this._parentScissorRect; cc.view.setScissorInPoints(rect.x, rect.y, rect.width, rect.height) }else{ var ctx = context || cc._renderContext; ctx.disable(ctx.SCISSOR_TEST); } } }, /** * Zoom handling */ _handleZoom:function () { }, _getViewRect:function(){ var screenPos = this.convertToWorldSpace(cc.p(0,0)); var locViewSize = this._viewSize; var scaleX = this.getScaleX(); var scaleY = this.getScaleY(); for (var p = this._parent; p != null; p = p.getParent()) { scaleX *= p.getScaleX(); scaleY *= p.getScaleY(); } // Support negative scaling. Not doing so causes intersectsRect calls // (eg: to check if the touch was within the bounds) to return false. // Note, CCNode::getScale will assert if X and Y scales are different. if (scaleX < 0) { screenPos.x += locViewSize.width * scaleX; scaleX = -scaleX; } if (scaleY < 0) { screenPos.y += locViewSize.height * scaleY; scaleY = -scaleY; } var locViewRect = this._tmpViewRect; locViewRect.x = screenPos.x; locViewRect.y = screenPos.y; locViewRect.width = locViewSize.width * scaleX; locViewRect.height = locViewSize.height * scaleY; return locViewRect; } }); var _p = cc.ScrollView.prototype; // Extended properties /** @expose */ _p.minOffset; cc.defineGetterSetter(_p, "minOffset", _p.minContainerOffset); /** @expose */ _p.maxOffset; cc.defineGetterSetter(_p, "maxOffset", _p.maxContainerOffset); /** @expose */ _p.bounceable; cc.defineGetterSetter(_p, "bounceable", _p.isBounceable, _p.setBounceable); /** @expose */ _p.viewSize; cc.defineGetterSetter(_p, "viewSize", _p.getViewSize, _p.setViewSize); /** @expose */ _p.container; cc.defineGetterSetter(_p, "container", _p.getContainer, _p.setContainer); /** @expose */ _p.direction; cc.defineGetterSetter(_p, "direction", _p.getDirection, _p.setDirection); /** @expose */ _p.delegate; cc.defineGetterSetter(_p, "delegate", _p.getDelegate, _p.setDelegate); /** @expose */ _p.clippingToBounds; cc.defineGetterSetter(_p, "clippingToBounds", _p.isClippingToBounds, _p.setClippingToBounds); _p = null; /** * Returns an autoreleased scroll view object. * @deprecated * @param {cc.Size} size view size * @param {cc.Node} container parent object * @return {cc.ScrollView} scroll view object */ cc.ScrollView.create = function (size, container) { return new cc.ScrollView(size, container); };
SystemEngineer/coastline-js
client/frameworks/cocos2d-html5/extensions/gui/scrollview/CCScrollView.js
JavaScript
bsd-2-clause
33,336
using System; using System.ComponentModel.Composition; using Core.Framework.Permissions.Models; using Core.Framework.Plugins.Web; using Core.Framework.Plugins.Widgets; using Core.Profiles.Verbs.Widgets; namespace Core.Profiles.Widgets { [Export(typeof(ICoreWidget))] [Export(typeof(IPermissible))] public class LoginWidget : BaseWidget { #region Singleton private static LoginWidget instance; private static readonly Object syncRoot = new Object(); public static LoginWidget Instance { get { lock (syncRoot) { return instance ?? (instance = new LoginWidget()); } } } private LoginWidget() { } #endregion public override ICorePlugin Plugin { get { return ProfilesPlugin.Instance; } } public override IWidgetActionVerb ViewAction { get { return LoginWidgetViewerVerb.Instance; } } public override IWidgetActionVerb EditAction { get { return null; } } public override IWidgetActionVerb SaveAction { get { return null; } } /* public override void Remove(ICoreWidgetInstance coreWidgetInstance) { WebContentWidgetHelper.Remove(coreWidgetInstance); } public override long? Clone(ICoreWidgetInstance coreWidgetInstance) { return WebContentWidgetHelper.CloneWebContentWidget(coreWidgetInstance); }*/ } }
coreframework/Core-Framework
Source/Core.Profiles/Widgets/LoginWidget.cs
C#
bsd-2-clause
1,642
// 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. // This file intentionally does not have header guards, it's included // inside a macro to generate enum values. // This file contains the list of network errors. // // Ranges: // 0- 99 System related errors // 100-199 Connection related errors // 200-299 Certificate errors // 300-399 HTTP errors // 400-499 Cache errors // 500-599 ? // 600-699 FTP errors // 700-799 Certificate manager errors // 800-899 DNS resolver errors // An asynchronous IO operation is not yet complete. This usually does not // indicate a fatal error. Typically this error will be generated as a // notification to wait for some external notification that the IO operation // finally completed. NET_ERROR(IO_PENDING, -1) // A generic failure occurred. NET_ERROR(FAILED, -2) // An operation was aborted (due to user action). NET_ERROR(ABORTED, -3) // An argument to the function is incorrect. NET_ERROR(INVALID_ARGUMENT, -4) // The handle or file descriptor is invalid. NET_ERROR(INVALID_HANDLE, -5) // The file or directory cannot be found. NET_ERROR(FILE_NOT_FOUND, -6) // An operation timed out. NET_ERROR(TIMED_OUT, -7) // The file is too large. NET_ERROR(FILE_TOO_BIG, -8) // An unexpected error. This may be caused by a programming mistake or an // invalid assumption. NET_ERROR(UNEXPECTED, -9) // Permission to access a resource, other than the network, was denied. NET_ERROR(ACCESS_DENIED, -10) // The operation failed because of unimplemented functionality. NET_ERROR(NOT_IMPLEMENTED, -11) // There were not enough resources to complete the operation. NET_ERROR(INSUFFICIENT_RESOURCES, -12) // Memory allocation failed. NET_ERROR(OUT_OF_MEMORY, -13) // The file upload failed because the file's modification time was different // from the expectation. NET_ERROR(UPLOAD_FILE_CHANGED, -14) // The socket is not connected. NET_ERROR(SOCKET_NOT_CONNECTED, -15) // The file already exists. NET_ERROR(FILE_EXISTS, -16) // The path or file name is too long. NET_ERROR(FILE_PATH_TOO_LONG, -17) // Not enough room left on the disk. NET_ERROR(FILE_NO_SPACE, -18) // The file has a virus. NET_ERROR(FILE_VIRUS_INFECTED, -19) // The client chose to block the request. NET_ERROR(BLOCKED_BY_CLIENT, -20) // The network changed. NET_ERROR(NETWORK_CHANGED, -21) // The request was blocked by the URL blacklist configured by the domain // administrator. NET_ERROR(BLOCKED_BY_ADMINISTRATOR, -22) // The socket is already connected. NET_ERROR(SOCKET_IS_CONNECTED, -23) // The request was blocked because the forced reenrollment check is still // pending. This error can only occur on ChromeOS. // The error can be emitted by code in chrome/browser/policy/policy_helpers.cc. NET_ERROR(BLOCKED_ENROLLMENT_CHECK_PENDING, -24) // The upload failed because the upload stream needed to be re-read, due to a // retry or a redirect, but the upload stream doesn't support that operation. NET_ERROR(UPLOAD_STREAM_REWIND_NOT_SUPPORTED, -25) // The request failed because the URLRequestContext is shutting down, or has // been shut down. NET_ERROR(CONTEXT_SHUT_DOWN, -26) // The request failed because the response was delivered along with requirements // which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor // checks, for instance). NET_ERROR(BLOCKED_BY_RESPONSE, -27) // A connection was closed (corresponding to a TCP FIN). NET_ERROR(CONNECTION_CLOSED, -100) // A connection was reset (corresponding to a TCP RST). NET_ERROR(CONNECTION_RESET, -101) // A connection attempt was refused. NET_ERROR(CONNECTION_REFUSED, -102) // A connection timed out as a result of not receiving an ACK for data sent. // This can include a FIN packet that did not get ACK'd. NET_ERROR(CONNECTION_ABORTED, -103) // A connection attempt failed. NET_ERROR(CONNECTION_FAILED, -104) // The host name could not be resolved. NET_ERROR(NAME_NOT_RESOLVED, -105) // The Internet connection has been lost. NET_ERROR(INTERNET_DISCONNECTED, -106) // An SSL protocol error occurred. NET_ERROR(SSL_PROTOCOL_ERROR, -107) // The IP address or port number is invalid (e.g., cannot connect to the IP // address 0 or the port 0). NET_ERROR(ADDRESS_INVALID, -108) // The IP address is unreachable. This usually means that there is no route to // the specified host or network. NET_ERROR(ADDRESS_UNREACHABLE, -109) // The server requested a client certificate for SSL client authentication. NET_ERROR(SSL_CLIENT_AUTH_CERT_NEEDED, -110) // A tunnel connection through the proxy could not be established. NET_ERROR(TUNNEL_CONNECTION_FAILED, -111) // No SSL protocol versions are enabled. NET_ERROR(NO_SSL_VERSIONS_ENABLED, -112) // The client and server don't support a common SSL protocol version or // cipher suite. NET_ERROR(SSL_VERSION_OR_CIPHER_MISMATCH, -113) // The server requested a renegotiation (rehandshake). NET_ERROR(SSL_RENEGOTIATION_REQUESTED, -114) // The proxy requested authentication (for tunnel establishment) with an // unsupported method. NET_ERROR(PROXY_AUTH_UNSUPPORTED, -115) // During SSL renegotiation (rehandshake), the server sent a certificate with // an error. // // Note: this error is not in the -2xx range so that it won't be handled as a // certificate error. NET_ERROR(CERT_ERROR_IN_SSL_RENEGOTIATION, -116) // The SSL handshake failed because of a bad or missing client certificate. NET_ERROR(BAD_SSL_CLIENT_AUTH_CERT, -117) // A connection attempt timed out. NET_ERROR(CONNECTION_TIMED_OUT, -118) // There are too many pending DNS resolves, so a request in the queue was // aborted. NET_ERROR(HOST_RESOLVER_QUEUE_TOO_LARGE, -119) // Failed establishing a connection to the SOCKS proxy server for a target host. NET_ERROR(SOCKS_CONNECTION_FAILED, -120) // The SOCKS proxy server failed establishing connection to the target host // because that host is unreachable. NET_ERROR(SOCKS_CONNECTION_HOST_UNREACHABLE, -121) // The request to negotiate an alternate protocol failed. NET_ERROR(ALPN_NEGOTIATION_FAILED, -122) // The peer sent an SSL no_renegotiation alert message. NET_ERROR(SSL_NO_RENEGOTIATION, -123) // Winsock sometimes reports more data written than passed. This is probably // due to a broken LSP. NET_ERROR(WINSOCK_UNEXPECTED_WRITTEN_BYTES, -124) // An SSL peer sent us a fatal decompression_failure alert. This typically // occurs when a peer selects DEFLATE compression in the mistaken belief that // it supports it. NET_ERROR(SSL_DECOMPRESSION_FAILURE_ALERT, -125) // An SSL peer sent us a fatal bad_record_mac alert. This has been observed // from servers with buggy DEFLATE support. NET_ERROR(SSL_BAD_RECORD_MAC_ALERT, -126) // The proxy requested authentication (for tunnel establishment). NET_ERROR(PROXY_AUTH_REQUESTED, -127) // The SSL server attempted to use a weak ephemeral Diffie-Hellman key. NET_ERROR(SSL_WEAK_SERVER_EPHEMERAL_DH_KEY, -129) // Could not create a connection to the proxy server. An error occurred // either in resolving its name, or in connecting a socket to it. // Note that this does NOT include failures during the actual "CONNECT" method // of an HTTP proxy. NET_ERROR(PROXY_CONNECTION_FAILED, -130) // A mandatory proxy configuration could not be used. Currently this means // that a mandatory PAC script could not be fetched, parsed or executed. NET_ERROR(MANDATORY_PROXY_CONFIGURATION_FAILED, -131) // -132 was formerly ERR_ESET_ANTI_VIRUS_SSL_INTERCEPTION // We've hit the max socket limit for the socket pool while preconnecting. We // don't bother trying to preconnect more sockets. NET_ERROR(PRECONNECT_MAX_SOCKET_LIMIT, -133) // The permission to use the SSL client certificate's private key was denied. NET_ERROR(SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED, -134) // The SSL client certificate has no private key. NET_ERROR(SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY, -135) // The certificate presented by the HTTPS Proxy was invalid. NET_ERROR(PROXY_CERTIFICATE_INVALID, -136) // An error occurred when trying to do a name resolution (DNS). NET_ERROR(NAME_RESOLUTION_FAILED, -137) // Permission to access the network was denied. This is used to distinguish // errors that were most likely caused by a firewall from other access denied // errors. See also ERR_ACCESS_DENIED. NET_ERROR(NETWORK_ACCESS_DENIED, -138) // The request throttler module cancelled this request to avoid DDOS. NET_ERROR(TEMPORARILY_THROTTLED, -139) // A request to create an SSL tunnel connection through the HTTPS proxy // received a non-200 (OK) and non-407 (Proxy Auth) response. The response // body might include a description of why the request failed. NET_ERROR(HTTPS_PROXY_TUNNEL_RESPONSE, -140) // We were unable to sign the CertificateVerify data of an SSL client auth // handshake with the client certificate's private key. // // Possible causes for this include the user implicitly or explicitly // denying access to the private key, the private key may not be valid for // signing, the key may be relying on a cached handle which is no longer // valid, or the CSP won't allow arbitrary data to be signed. NET_ERROR(SSL_CLIENT_AUTH_SIGNATURE_FAILED, -141) // The message was too large for the transport. (for example a UDP message // which exceeds size threshold). NET_ERROR(MSG_TOO_BIG, -142) // A SPDY session already exists, and should be used instead of this connection. NET_ERROR(SPDY_SESSION_ALREADY_EXISTS, -143) // Error -144 was removed (LIMIT_VIOLATION). // Websocket protocol error. Indicates that we are terminating the connection // due to a malformed frame or other protocol violation. NET_ERROR(WS_PROTOCOL_ERROR, -145) // Error -146 was removed (PROTOCOL_SWITCHED) // Returned when attempting to bind an address that is already in use. NET_ERROR(ADDRESS_IN_USE, -147) // An operation failed because the SSL handshake has not completed. NET_ERROR(SSL_HANDSHAKE_NOT_COMPLETED, -148) // SSL peer's public key is invalid. NET_ERROR(SSL_BAD_PEER_PUBLIC_KEY, -149) // The certificate didn't match the built-in public key pins for the host name. // The pins are set in net/http/transport_security_state.cc and require that // one of a set of public keys exist on the path from the leaf to the root. NET_ERROR(SSL_PINNED_KEY_NOT_IN_CERT_CHAIN, -150) // Server request for client certificate did not contain any types we support. NET_ERROR(CLIENT_AUTH_CERT_TYPE_UNSUPPORTED, -151) // Server requested one type of cert, then requested a different type while the // first was still being generated. NET_ERROR(ORIGIN_BOUND_CERT_GENERATION_TYPE_MISMATCH, -152) // An SSL peer sent us a fatal decrypt_error alert. This typically occurs when // a peer could not correctly verify a signature (in CertificateVerify or // ServerKeyExchange) or validate a Finished message. NET_ERROR(SSL_DECRYPT_ERROR_ALERT, -153) // There are too many pending WebSocketJob instances, so the new job was not // pushed to the queue. NET_ERROR(WS_THROTTLE_QUEUE_TOO_LARGE, -154) // Error -155 was removed (TOO_MANY_SOCKET_STREAMS) // The SSL server certificate changed in a renegotiation. NET_ERROR(SSL_SERVER_CERT_CHANGED, -156) // Error -157 was removed (SSL_INAPPROPRIATE_FALLBACK). // Certificate Transparency: All Signed Certificate Timestamps failed to verify. NET_ERROR(CT_NO_SCTS_VERIFIED_OK, -158) // The SSL server sent us a fatal unrecognized_name alert. NET_ERROR(SSL_UNRECOGNIZED_NAME_ALERT, -159) // Failed to set the socket's receive buffer size as requested. NET_ERROR(SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR, -160) // Failed to set the socket's send buffer size as requested. NET_ERROR(SOCKET_SET_SEND_BUFFER_SIZE_ERROR, -161) // Failed to set the socket's receive buffer size as requested, despite success // return code from setsockopt. NET_ERROR(SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE, -162) // Failed to set the socket's send buffer size as requested, despite success // return code from setsockopt. NET_ERROR(SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE, -163) // Failed to import a client certificate from the platform store into the SSL // library. NET_ERROR(SSL_CLIENT_AUTH_CERT_BAD_FORMAT, -164) // Error -165 was removed (SSL_FALLBACK_BEYOND_MINIMUM_VERSION). // Resolving a hostname to an IP address list included the IPv4 address // "127.0.53.53". This is a special IP address which ICANN has recommended to // indicate there was a name collision, and alert admins to a potential // problem. NET_ERROR(ICANN_NAME_COLLISION, -166) // The SSL server presented a certificate which could not be decoded. This is // not a certificate error code as no X509Certificate object is available. This // error is fatal. NET_ERROR(SSL_SERVER_CERT_BAD_FORMAT, -167) // Certificate Transparency: Received a signed tree head that failed to parse. NET_ERROR(CT_STH_PARSING_FAILED, -168) // Certificate Transparency: Received a signed tree head whose JSON parsing was // OK but was missing some of the fields. NET_ERROR(CT_STH_INCOMPLETE, -169) // The attempt to reuse a connection to send proxy auth credentials failed // before the AuthController was used to generate credentials. The caller should // reuse the controller with a new connection. This error is only used // internally by the network stack. NET_ERROR(UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH, -170) // Certificate Transparency: Failed to parse the received consistency proof. NET_ERROR(CT_CONSISTENCY_PROOF_PARSING_FAILED, -171) // The SSL server required an unsupported cipher suite that has since been // removed. This error will temporarily be signaled on a fallback for one or two // releases immediately following a cipher suite's removal, after which the // fallback will be removed. NET_ERROR(SSL_OBSOLETE_CIPHER, -172) // Certificate error codes // // The values of certificate error codes must be consecutive. // The server responded with a certificate whose common name did not match // the host name. This could mean: // // 1. An attacker has redirected our traffic to their server and is // presenting a certificate for which they know the private key. // // 2. The server is misconfigured and responding with the wrong cert. // // 3. The user is on a wireless network and is being redirected to the // network's login page. // // 4. The OS has used a DNS search suffix and the server doesn't have // a certificate for the abbreviated name in the address bar. // NET_ERROR(CERT_COMMON_NAME_INVALID, -200) // The server responded with a certificate that, by our clock, appears to // either not yet be valid or to have expired. This could mean: // // 1. An attacker is presenting an old certificate for which they have // managed to obtain the private key. // // 2. The server is misconfigured and is not presenting a valid cert. // // 3. Our clock is wrong. // NET_ERROR(CERT_DATE_INVALID, -201) // The server responded with a certificate that is signed by an authority // we don't trust. The could mean: // // 1. An attacker has substituted the real certificate for a cert that // contains their public key and is signed by their cousin. // // 2. The server operator has a legitimate certificate from a CA we don't // know about, but should trust. // // 3. The server is presenting a self-signed certificate, providing no // defense against active attackers (but foiling passive attackers). // NET_ERROR(CERT_AUTHORITY_INVALID, -202) // The server responded with a certificate that contains errors. // This error is not recoverable. // // MSDN describes this error as follows: // "The SSL certificate contains errors." // NOTE: It's unclear how this differs from ERR_CERT_INVALID. For consistency, // use that code instead of this one from now on. // NET_ERROR(CERT_CONTAINS_ERRORS, -203) // The certificate has no mechanism for determining if it is revoked. In // effect, this certificate cannot be revoked. NET_ERROR(CERT_NO_REVOCATION_MECHANISM, -204) // Revocation information for the security certificate for this site is not // available. This could mean: // // 1. An attacker has compromised the private key in the certificate and is // blocking our attempt to find out that the cert was revoked. // // 2. The certificate is unrevoked, but the revocation server is busy or // unavailable. // NET_ERROR(CERT_UNABLE_TO_CHECK_REVOCATION, -205) // The server responded with a certificate has been revoked. // We have the capability to ignore this error, but it is probably not the // thing to do. NET_ERROR(CERT_REVOKED, -206) // The server responded with a certificate that is invalid. // This error is not recoverable. // // MSDN describes this error as follows: // "The SSL certificate is invalid." // NET_ERROR(CERT_INVALID, -207) // The server responded with a certificate that is signed using a weak // signature algorithm. NET_ERROR(CERT_WEAK_SIGNATURE_ALGORITHM, -208) // -209 is availible: was CERT_NOT_IN_DNS. // The host name specified in the certificate is not unique. NET_ERROR(CERT_NON_UNIQUE_NAME, -210) // The server responded with a certificate that contains a weak key (e.g. // a too-small RSA key). NET_ERROR(CERT_WEAK_KEY, -211) // The certificate claimed DNS names that are in violation of name constraints. NET_ERROR(CERT_NAME_CONSTRAINT_VIOLATION, -212) // The certificate's validity period is too long. NET_ERROR(CERT_VALIDITY_TOO_LONG, -213) // Certificate Transparency was required for this connection, but the server // did not provide CT information that complied with the policy. NET_ERROR(CERTIFICATE_TRANSPARENCY_REQUIRED, -214) // Add new certificate error codes here. // // Update the value of CERT_END whenever you add a new certificate error // code. // The value immediately past the last certificate error code. NET_ERROR(CERT_END, -215) // The URL is invalid. NET_ERROR(INVALID_URL, -300) // The scheme of the URL is disallowed. NET_ERROR(DISALLOWED_URL_SCHEME, -301) // The scheme of the URL is unknown. NET_ERROR(UNKNOWN_URL_SCHEME, -302) // Attempting to load an URL resulted in too many redirects. NET_ERROR(TOO_MANY_REDIRECTS, -310) // Attempting to load an URL resulted in an unsafe redirect (e.g., a redirect // to file:// is considered unsafe). NET_ERROR(UNSAFE_REDIRECT, -311) // Attempting to load an URL with an unsafe port number. These are port // numbers that correspond to services, which are not robust to spurious input // that may be constructed as a result of an allowed web construct (e.g., HTTP // looks a lot like SMTP, so form submission to port 25 is denied). NET_ERROR(UNSAFE_PORT, -312) // The server's response was invalid. NET_ERROR(INVALID_RESPONSE, -320) // Error in chunked transfer encoding. NET_ERROR(INVALID_CHUNKED_ENCODING, -321) // The server did not support the request method. NET_ERROR(METHOD_NOT_SUPPORTED, -322) // The response was 407 (Proxy Authentication Required), yet we did not send // the request to a proxy. NET_ERROR(UNEXPECTED_PROXY_AUTH, -323) // The server closed the connection without sending any data. NET_ERROR(EMPTY_RESPONSE, -324) // The headers section of the response is too large. NET_ERROR(RESPONSE_HEADERS_TOO_BIG, -325) // The PAC requested by HTTP did not have a valid status code (non-200). NET_ERROR(PAC_STATUS_NOT_OK, -326) // The evaluation of the PAC script failed. NET_ERROR(PAC_SCRIPT_FAILED, -327) // The response was 416 (Requested range not satisfiable) and the server cannot // satisfy the range requested. NET_ERROR(REQUEST_RANGE_NOT_SATISFIABLE, -328) // The identity used for authentication is invalid. NET_ERROR(MALFORMED_IDENTITY, -329) // Content decoding of the response body failed. NET_ERROR(CONTENT_DECODING_FAILED, -330) // An operation could not be completed because all network IO // is suspended. NET_ERROR(NETWORK_IO_SUSPENDED, -331) // FLIP data received without receiving a SYN_REPLY on the stream. NET_ERROR(SYN_REPLY_NOT_RECEIVED, -332) // Converting the response to target encoding failed. NET_ERROR(ENCODING_CONVERSION_FAILED, -333) // The server sent an FTP directory listing in a format we do not understand. NET_ERROR(UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT, -334) // Attempted use of an unknown SPDY stream id. NET_ERROR(INVALID_SPDY_STREAM, -335) // There are no supported proxies in the provided list. NET_ERROR(NO_SUPPORTED_PROXIES, -336) // There is a SPDY protocol error. NET_ERROR(SPDY_PROTOCOL_ERROR, -337) // Credentials could not be established during HTTP Authentication. NET_ERROR(INVALID_AUTH_CREDENTIALS, -338) // An HTTP Authentication scheme was tried which is not supported on this // machine. NET_ERROR(UNSUPPORTED_AUTH_SCHEME, -339) // Detecting the encoding of the response failed. NET_ERROR(ENCODING_DETECTION_FAILED, -340) // (GSSAPI) No Kerberos credentials were available during HTTP Authentication. NET_ERROR(MISSING_AUTH_CREDENTIALS, -341) // An unexpected, but documented, SSPI or GSSAPI status code was returned. NET_ERROR(UNEXPECTED_SECURITY_LIBRARY_STATUS, -342) // The environment was not set up correctly for authentication (for // example, no KDC could be found or the principal is unknown. NET_ERROR(MISCONFIGURED_AUTH_ENVIRONMENT, -343) // An undocumented SSPI or GSSAPI status code was returned. NET_ERROR(UNDOCUMENTED_SECURITY_LIBRARY_STATUS, -344) // The HTTP response was too big to drain. NET_ERROR(RESPONSE_BODY_TOO_BIG_TO_DRAIN, -345) // The HTTP response contained multiple distinct Content-Length headers. NET_ERROR(RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH, -346) // SPDY Headers have been received, but not all of them - status or version // headers are missing, so we're expecting additional frames to complete them. NET_ERROR(INCOMPLETE_SPDY_HEADERS, -347) // No PAC URL configuration could be retrieved from DHCP. This can indicate // either a failure to retrieve the DHCP configuration, or that there was no // PAC URL configured in DHCP. NET_ERROR(PAC_NOT_IN_DHCP, -348) // The HTTP response contained multiple Content-Disposition headers. NET_ERROR(RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION, -349) // The HTTP response contained multiple Location headers. NET_ERROR(RESPONSE_HEADERS_MULTIPLE_LOCATION, -350) // SPDY server refused the stream. Client should retry. This should never be a // user-visible error. NET_ERROR(SPDY_SERVER_REFUSED_STREAM, -351) // SPDY server didn't respond to the PING message. NET_ERROR(SPDY_PING_FAILED, -352) // Obsolete. Kept here to avoid reuse, as the old error can still appear on // histograms. // NET_ERROR(PIPELINE_EVICTION, -353) // The HTTP response body transferred fewer bytes than were advertised by the // Content-Length header when the connection is closed. NET_ERROR(CONTENT_LENGTH_MISMATCH, -354) // The HTTP response body is transferred with Chunked-Encoding, but the // terminating zero-length chunk was never sent when the connection is closed. NET_ERROR(INCOMPLETE_CHUNKED_ENCODING, -355) // There is a QUIC protocol error. NET_ERROR(QUIC_PROTOCOL_ERROR, -356) // The HTTP headers were truncated by an EOF. NET_ERROR(RESPONSE_HEADERS_TRUNCATED, -357) // The QUIC crytpo handshake failed. This means that the server was unable // to read any requests sent, so they may be resent. NET_ERROR(QUIC_HANDSHAKE_FAILED, -358) // Obsolete. Kept here to avoid reuse, as the old error can still appear on // histograms. // NET_ERROR(REQUEST_FOR_SECURE_RESOURCE_OVER_INSECURE_QUIC, -359) // Transport security is inadequate for the SPDY version. NET_ERROR(SPDY_INADEQUATE_TRANSPORT_SECURITY, -360) // The peer violated SPDY flow control. NET_ERROR(SPDY_FLOW_CONTROL_ERROR, -361) // The peer sent an improperly sized SPDY frame. NET_ERROR(SPDY_FRAME_SIZE_ERROR, -362) // Decoding or encoding of compressed SPDY headers failed. NET_ERROR(SPDY_COMPRESSION_ERROR, -363) // Proxy Auth Requested without a valid Client Socket Handle. NET_ERROR(PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION, -364) // HTTP_1_1_REQUIRED error code received on HTTP/2 session. NET_ERROR(HTTP_1_1_REQUIRED, -365) // HTTP_1_1_REQUIRED error code received on HTTP/2 session to proxy. NET_ERROR(PROXY_HTTP_1_1_REQUIRED, -366) // The PAC script terminated fatally and must be reloaded. NET_ERROR(PAC_SCRIPT_TERMINATED, -367) // Obsolete. Kept here to avoid reuse. // Request is throttled because of a Backoff header. // See: crbug.com/486891. // NET_ERROR(TEMPORARY_BACKOFF, -369) // The server was expected to return an HTTP/1.x response, but did not. Rather // than treat it as HTTP/0.9, this error is returned. NET_ERROR(INVALID_HTTP_RESPONSE, -370) // Initializing content decoding failed. NET_ERROR(CONTENT_DECODING_INIT_FAILED, -371) // The cache does not have the requested entry. NET_ERROR(CACHE_MISS, -400) // Unable to read from the disk cache. NET_ERROR(CACHE_READ_FAILURE, -401) // Unable to write to the disk cache. NET_ERROR(CACHE_WRITE_FAILURE, -402) // The operation is not supported for this entry. NET_ERROR(CACHE_OPERATION_NOT_SUPPORTED, -403) // The disk cache is unable to open this entry. NET_ERROR(CACHE_OPEN_FAILURE, -404) // The disk cache is unable to create this entry. NET_ERROR(CACHE_CREATE_FAILURE, -405) // Multiple transactions are racing to create disk cache entries. This is an // internal error returned from the HttpCache to the HttpCacheTransaction that // tells the transaction to restart the entry-creation logic because the state // of the cache has changed. NET_ERROR(CACHE_RACE, -406) // The cache was unable to read a checksum record on an entry. This can be // returned from attempts to read from the cache. It is an internal error, // returned by the SimpleCache backend, but not by any URLRequest methods // or members. NET_ERROR(CACHE_CHECKSUM_READ_FAILURE, -407) // The cache found an entry with an invalid checksum. This can be returned from // attempts to read from the cache. It is an internal error, returned by the // SimpleCache backend, but not by any URLRequest methods or members. NET_ERROR(CACHE_CHECKSUM_MISMATCH, -408) // Internal error code for the HTTP cache. The cache lock timeout has fired. NET_ERROR(CACHE_LOCK_TIMEOUT, -409) // Received a challenge after the transaction has read some data, and the // credentials aren't available. There isn't a way to get them at that point. NET_ERROR(CACHE_AUTH_FAILURE_AFTER_READ, -410) // The server's response was insecure (e.g. there was a cert error). NET_ERROR(INSECURE_RESPONSE, -501) // The server responded to a <keygen> with a generated client cert that we // don't have the matching private key for. NET_ERROR(NO_PRIVATE_KEY_FOR_CERT, -502) // An error adding to the OS certificate database (e.g. OS X Keychain). NET_ERROR(ADD_USER_CERT_FAILED, -503) // *** Code -600 is reserved (was FTP_PASV_COMMAND_FAILED). *** // A generic error for failed FTP control connection command. // If possible, please use or add a more specific error code. NET_ERROR(FTP_FAILED, -601) // The server cannot fulfill the request at this point. This is a temporary // error. // FTP response code 421. NET_ERROR(FTP_SERVICE_UNAVAILABLE, -602) // The server has aborted the transfer. // FTP response code 426. NET_ERROR(FTP_TRANSFER_ABORTED, -603) // The file is busy, or some other temporary error condition on opening // the file. // FTP response code 450. NET_ERROR(FTP_FILE_BUSY, -604) // Server rejected our command because of syntax errors. // FTP response codes 500, 501. NET_ERROR(FTP_SYNTAX_ERROR, -605) // Server does not support the command we issued. // FTP response codes 502, 504. NET_ERROR(FTP_COMMAND_NOT_SUPPORTED, -606) // Server rejected our command because we didn't issue the commands in right // order. // FTP response code 503. NET_ERROR(FTP_BAD_COMMAND_SEQUENCE, -607) // PKCS #12 import failed due to incorrect password. NET_ERROR(PKCS12_IMPORT_BAD_PASSWORD, -701) // PKCS #12 import failed due to other error. NET_ERROR(PKCS12_IMPORT_FAILED, -702) // CA import failed - not a CA cert. NET_ERROR(IMPORT_CA_CERT_NOT_CA, -703) // Import failed - certificate already exists in database. // Note it's a little weird this is an error but reimporting a PKCS12 is ok // (no-op). That's how Mozilla does it, though. NET_ERROR(IMPORT_CERT_ALREADY_EXISTS, -704) // CA import failed due to some other error. NET_ERROR(IMPORT_CA_CERT_FAILED, -705) // Server certificate import failed due to some internal error. NET_ERROR(IMPORT_SERVER_CERT_FAILED, -706) // PKCS #12 import failed due to invalid MAC. NET_ERROR(PKCS12_IMPORT_INVALID_MAC, -707) // PKCS #12 import failed due to invalid/corrupt file. NET_ERROR(PKCS12_IMPORT_INVALID_FILE, -708) // PKCS #12 import failed due to unsupported features. NET_ERROR(PKCS12_IMPORT_UNSUPPORTED, -709) // Key generation failed. NET_ERROR(KEY_GENERATION_FAILED, -710) // Error -711 was removed (ORIGIN_BOUND_CERT_GENERATION_FAILED) // Failure to export private key. NET_ERROR(PRIVATE_KEY_EXPORT_FAILED, -712) // Self-signed certificate generation failed. NET_ERROR(SELF_SIGNED_CERT_GENERATION_FAILED, -713) // The certificate database changed in some way. NET_ERROR(CERT_DATABASE_CHANGED, -714) // Error -715 was removed (CHANNEL_ID_IMPORT_FAILED) // DNS error codes. // DNS resolver received a malformed response. NET_ERROR(DNS_MALFORMED_RESPONSE, -800) // DNS server requires TCP NET_ERROR(DNS_SERVER_REQUIRES_TCP, -801) // DNS server failed. This error is returned for all of the following // error conditions: // 1 - Format error - The name server was unable to interpret the query. // 2 - Server failure - The name server was unable to process this query // due to a problem with the name server. // 4 - Not Implemented - The name server does not support the requested // kind of query. // 5 - Refused - The name server refuses to perform the specified // operation for policy reasons. NET_ERROR(DNS_SERVER_FAILED, -802) // DNS transaction timed out. NET_ERROR(DNS_TIMED_OUT, -803) // The entry was not found in cache, for cache-only lookups. NET_ERROR(DNS_CACHE_MISS, -804) // Suffix search list rules prevent resolution of the given host name. NET_ERROR(DNS_SEARCH_EMPTY, -805) // Failed to sort addresses according to RFC3484. NET_ERROR(DNS_SORT_ERROR, -806)
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/net/base/net_error_list.h
C
bsd-2-clause
30,152
export class Range { constructor( private l?: number, private r?: number ) {} get collapsed(): boolean { return true; } get commonAncestorContainer(): Element { return document.body; } get startContainer(): Node { return document.body; } get endContainer(): Node { return document.body; } get startOffset(): number { return this.l || 0; } get endOffset(): number { return this.r || 0; } }
clbond/angular-ssr
source/runtime/browser-emulation/range.ts
TypeScript
bsd-2-clause
455
from base64 import b64encode from datetime import ( datetime, timedelta, ) from hashlib import md5 import re import struct import zlib try: import simplejson as json except ImportError: import json from webob.byterange import ContentRange from webob.cachecontrol import ( CacheControl, serialize_cache_control, ) from webob.compat import ( PY3, bytes_, native_, text_type, url_quote, urlparse, ) from webob.cookies import ( Cookie, make_cookie, ) from webob.datetime_utils import ( parse_date_delta, serialize_date_delta, timedelta_to_seconds, ) from webob.descriptors import ( CHARSET_RE, SCHEME_RE, converter, date_header, header_getter, list_header, parse_auth, parse_content_range, parse_etag_response, parse_int, parse_int_safe, serialize_auth, serialize_content_range, serialize_etag_response, serialize_int, ) from webob.headers import ResponseHeaders from webob.request import BaseRequest from webob.util import status_reasons, status_generic_reasons, warn_deprecation __all__ = ['Response'] _PARAM_RE = re.compile(r'([a-z0-9]+)=(?:"([^"]*)"|([a-z0-9_.-]*))', re.I) _OK_PARAM_RE = re.compile(r'^[a-z0-9_.-]+$', re.I) _gzip_header = b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff' class Response(object): """ Represents a WSGI response """ default_content_type = 'text/html' default_charset = 'UTF-8' # TODO: deprecate unicode_errors = 'strict' # TODO: deprecate (why would response body have errors?) default_conditional_response = False request = None environ = None # # __init__, from_file, copy # def __init__(self, body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, **kw): if app_iter is None and body is None and ('json_body' in kw or 'json' in kw): if 'json_body' in kw: json_body = kw.pop('json_body') else: json_body = kw.pop('json') body = json.dumps(json_body, separators=(',', ':')) if content_type is None: content_type = 'application/json' if app_iter is None: if body is None: body = b'' elif body is not None: raise TypeError( "You may only give one of the body and app_iter arguments") if status is None: self._status = '200 OK' else: self.status = status if headerlist is None: self._headerlist = [] else: self._headerlist = headerlist self._headers = None if content_type is None: content_type = self.default_content_type charset = None if 'charset' in kw: charset = kw.pop('charset') elif self.default_charset: if (content_type and 'charset=' not in content_type and (content_type == 'text/html' or content_type.startswith('text/') or content_type.startswith('application/xml') or content_type.startswith('application/json') or (content_type.startswith('application/') and (content_type.endswith('+xml') or content_type.endswith('+json'))))): charset = self.default_charset if content_type and charset: content_type += '; charset=' + charset elif self._headerlist and charset: self.charset = charset if not self._headerlist and content_type: self._headerlist.append(('Content-Type', content_type)) if conditional_response is None: self.conditional_response = self.default_conditional_response else: self.conditional_response = bool(conditional_response) if app_iter is None: if isinstance(body, text_type): if charset is None: raise TypeError( "You cannot set the body to a text value without a " "charset") body = body.encode(charset) app_iter = [body] if headerlist is None: self._headerlist.append(('Content-Length', str(len(body)))) else: self.headers['Content-Length'] = str(len(body)) self._app_iter = app_iter for name, value in kw.items(): if not hasattr(self.__class__, name): # Not a basic attribute raise TypeError( "Unexpected keyword: %s=%r" % (name, value)) setattr(self, name, value) @classmethod def from_file(cls, fp): """Reads a response from a file-like object (it must implement ``.read(size)`` and ``.readline()``). It will read up to the end of the response, not the end of the file. This reads the response as represented by ``str(resp)``; it may not read every valid HTTP response properly. Responses must have a ``Content-Length``""" headerlist = [] status = fp.readline().strip() is_text = isinstance(status, text_type) if is_text: _colon = ':' _http = 'HTTP/' else: _colon = b':' _http = b'HTTP/' if status.startswith(_http): (http_ver, status_num, status_text) = status.split() status = '%s %s' % (native_(status_num), native_(status_text)) while 1: line = fp.readline().strip() if not line: # end of headers break try: header_name, value = line.split(_colon, 1) except ValueError: raise ValueError('Bad header line: %r' % line) value = value.strip() headerlist.append(( native_(header_name, 'latin-1'), native_(value, 'latin-1') )) r = cls( status=status, headerlist=headerlist, app_iter=(), ) body = fp.read(r.content_length or 0) if is_text: r.text = body else: r.body = body return r def copy(self): """Makes a copy of the response""" # we need to do this for app_iter to be reusable app_iter = list(self._app_iter) iter_close(self._app_iter) # and this to make sure app_iter instances are different self._app_iter = list(app_iter) return self.__class__( content_type=False, status=self._status, headerlist=self._headerlist[:], app_iter=app_iter, conditional_response=self.conditional_response) # # __repr__, __str__ # def __repr__(self): return '<%s at 0x%x %s>' % (self.__class__.__name__, abs(id(self)), self.status) def __str__(self, skip_body=False): parts = [self.status] if not skip_body: # Force enumeration of the body (to set content-length) self.body parts += map('%s: %s'.__mod__, self.headerlist) if not skip_body and self.body: parts += ['', self.text if PY3 else self.body] return '\r\n'.join(parts) # # status, status_code/status_int # def _status__get(self): """ The status string """ return self._status def _status__set(self, value): try: code = int(value) except (ValueError, TypeError): pass else: self.status_code = code return if PY3: # pragma: no cover if isinstance(value, bytes): value = value.decode('ascii') elif isinstance(value, text_type): value = value.encode('ascii') if not isinstance(value, str): raise TypeError( "You must set status to a string or integer (not %s)" % type(value)) # Attempt to get the status code itself, if this fails we should fail try: status_code = int(value.split()[0]) except ValueError: raise ValueError('Invalid status code, integer required.') self._status = value status = property(_status__get, _status__set, doc=_status__get.__doc__) def _status_code__get(self): """ The status as an integer """ return int(self._status.split()[0]) def _status_code__set(self, code): try: self._status = '%d %s' % (code, status_reasons[code]) except KeyError: self._status = '%d %s' % (code, status_generic_reasons[code // 100]) status_code = status_int = property(_status_code__get, _status_code__set, doc=_status_code__get.__doc__) # # headerslist, headers # def _headerlist__get(self): """ The list of response headers """ return self._headerlist def _headerlist__set(self, value): self._headers = None if not isinstance(value, list): if hasattr(value, 'items'): value = value.items() value = list(value) self._headerlist = value def _headerlist__del(self): self.headerlist = [] headerlist = property(_headerlist__get, _headerlist__set, _headerlist__del, doc=_headerlist__get.__doc__) def _headers__get(self): """ The headers in a dictionary-like object """ if self._headers is None: self._headers = ResponseHeaders.view_list(self.headerlist) return self._headers def _headers__set(self, value): if hasattr(value, 'items'): value = value.items() self.headerlist = value self._headers = None headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__) # # body # def _body__get(self): """ The body of the response, as a ``str``. This will read in the entire app_iter if necessary. """ app_iter = self._app_iter # try: # if len(app_iter) == 1: # return app_iter[0] # except: # pass if isinstance(app_iter, list) and len(app_iter) == 1: return app_iter[0] if app_iter is None: raise AttributeError("No body has been set") try: body = b''.join(app_iter) finally: iter_close(app_iter) if isinstance(body, text_type): raise _error_unicode_in_app_iter(app_iter, body) self._app_iter = [body] if len(body) == 0: # if body-length is zero, we assume it's a HEAD response and # leave content_length alone pass # pragma: no cover (no idea why necessary, it's hit) elif self.content_length is None: self.content_length = len(body) elif self.content_length != len(body): raise AssertionError( "Content-Length is different from actual app_iter length " "(%r!=%r)" % (self.content_length, len(body)) ) return body def _body__set(self, value=b''): if not isinstance(value, bytes): if isinstance(value, text_type): msg = ("You cannot set Response.body to a text object " "(use Response.text)") else: msg = ("You can only set the body to a binary type (not %s)" % type(value)) raise TypeError(msg) if self._app_iter is not None: self.content_md5 = None self._app_iter = [value] self.content_length = len(value) # def _body__del(self): # self.body = '' # #self.content_length = None body = property(_body__get, _body__set, _body__set) def _json_body__get(self): """Access the body of the response as JSON""" # Note: UTF-8 is a content-type specific default for JSON: return json.loads(self.body.decode(self.charset or 'UTF-8')) def _json_body__set(self, value): self.body = json.dumps(value, separators=(',', ':')).encode(self.charset or 'UTF-8') def _json_body__del(self): del self.body json = json_body = property(_json_body__get, _json_body__set, _json_body__del) # # text, unicode_body, ubody # def _text__get(self): """ Get/set the text value of the body (using the charset of the Content-Type) """ if not self.charset: raise AttributeError( "You cannot access Response.text unless charset is set") body = self.body return body.decode(self.charset, self.unicode_errors) def _text__set(self, value): if not self.charset: raise AttributeError( "You cannot access Response.text unless charset is set") if not isinstance(value, text_type): raise TypeError( "You can only set Response.text to a unicode string " "(not %s)" % type(value)) self.body = value.encode(self.charset) def _text__del(self): del self.body text = property(_text__get, _text__set, _text__del, doc=_text__get.__doc__) unicode_body = ubody = property(_text__get, _text__set, _text__del, "Deprecated alias for .text") # # body_file, write(text) # def _body_file__get(self): """ A file-like object that can be used to write to the body. If you passed in a list app_iter, that app_iter will be modified by writes. """ return ResponseBodyFile(self) def _body_file__set(self, file): self.app_iter = iter_file(file) def _body_file__del(self): del self.body body_file = property(_body_file__get, _body_file__set, _body_file__del, doc=_body_file__get.__doc__) def write(self, text): if not isinstance(text, bytes): if not isinstance(text, text_type): msg = "You can only write str to a Response.body_file, not %s" raise TypeError(msg % type(text)) if not self.charset: msg = ("You can only write text to Response if charset has " "been set") raise TypeError(msg) text = text.encode(self.charset) app_iter = self._app_iter if not isinstance(app_iter, list): try: new_app_iter = self._app_iter = list(app_iter) finally: iter_close(app_iter) app_iter = new_app_iter self.content_length = sum(len(chunk) for chunk in app_iter) app_iter.append(text) if self.content_length is not None: self.content_length += len(text) # # app_iter # def _app_iter__get(self): """ Returns the app_iter of the response. If body was set, this will create an app_iter from that body (a single-item list) """ return self._app_iter def _app_iter__set(self, value): if self._app_iter is not None: # Undo the automatically-set content-length self.content_length = None self.content_md5 = None self._app_iter = value def _app_iter__del(self): self._app_iter = [] self.content_length = None app_iter = property(_app_iter__get, _app_iter__set, _app_iter__del, doc=_app_iter__get.__doc__) # # headers attrs # allow = list_header('Allow', '14.7') # TODO: (maybe) support response.vary += 'something' # TODO: same thing for all listy headers vary = list_header('Vary', '14.44') content_length = converter( header_getter('Content-Length', '14.17'), parse_int, serialize_int, 'int') content_encoding = header_getter('Content-Encoding', '14.11') content_language = list_header('Content-Language', '14.12') content_location = header_getter('Content-Location', '14.14') content_md5 = header_getter('Content-MD5', '14.14') content_disposition = header_getter('Content-Disposition', '19.5.1') accept_ranges = header_getter('Accept-Ranges', '14.5') content_range = converter( header_getter('Content-Range', '14.16'), parse_content_range, serialize_content_range, 'ContentRange object') date = date_header('Date', '14.18') expires = date_header('Expires', '14.21') last_modified = date_header('Last-Modified', '14.29') _etag_raw = header_getter('ETag', '14.19') etag = converter(_etag_raw, parse_etag_response, serialize_etag_response, 'Entity tag' ) @property def etag_strong(self): return parse_etag_response(self._etag_raw, strong=True) location = header_getter('Location', '14.30') pragma = header_getter('Pragma', '14.32') age = converter( header_getter('Age', '14.6'), parse_int_safe, serialize_int, 'int') retry_after = converter( header_getter('Retry-After', '14.37'), parse_date_delta, serialize_date_delta, 'HTTP date or delta seconds') server = header_getter('Server', '14.38') # TODO: the standard allows this to be a list of challenges www_authenticate = converter( header_getter('WWW-Authenticate', '14.47'), parse_auth, serialize_auth, ) # # charset # def _charset__get(self): """ Get/set the charset (in the Content-Type) """ header = self.headers.get('Content-Type') if not header: return None match = CHARSET_RE.search(header) if match: return match.group(1) return None def _charset__set(self, charset): if charset is None: del self.charset return header = self.headers.pop('Content-Type', None) if header is None: raise AttributeError("You cannot set the charset when no " "content-type is defined") match = CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] header += '; charset=%s' % charset self.headers['Content-Type'] = header def _charset__del(self): header = self.headers.pop('Content-Type', None) if header is None: # Don't need to remove anything return match = CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] self.headers['Content-Type'] = header charset = property(_charset__get, _charset__set, _charset__del, doc=_charset__get.__doc__) # # content_type # def _content_type__get(self): """ Get/set the Content-Type header (or None), *without* the charset or any parameters. If you include parameters (or ``;`` at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved. """ header = self.headers.get('Content-Type') if not header: return None return header.split(';', 1)[0] def _content_type__set(self, value): if not value: self._content_type__del() return if ';' not in value: header = self.headers.get('Content-Type', '') if ';' in header: params = header.split(';', 1)[1] value += ';' + params self.headers['Content-Type'] = value def _content_type__del(self): self.headers.pop('Content-Type', None) content_type = property(_content_type__get, _content_type__set, _content_type__del, doc=_content_type__get.__doc__) # # content_type_params # def _content_type_params__get(self): """ A dictionary of all the parameters in the content type. (This is not a view, set to change, modifications of the dict would not be applied otherwise) """ params = self.headers.get('Content-Type', '') if ';' not in params: return {} params = params.split(';', 1)[1] result = {} for match in _PARAM_RE.finditer(params): result[match.group(1)] = match.group(2) or match.group(3) or '' return result def _content_type_params__set(self, value_dict): if not value_dict: del self.content_type_params return params = [] for k, v in sorted(value_dict.items()): if not _OK_PARAM_RE.search(v): v = '"%s"' % v.replace('"', '\\"') params.append('; %s=%s' % (k, v)) ct = self.headers.pop('Content-Type', '').split(';', 1)[0] ct += ''.join(params) self.headers['Content-Type'] = ct def _content_type_params__del(self): self.headers['Content-Type'] = self.headers.get( 'Content-Type', '').split(';', 1)[0] content_type_params = property( _content_type_params__get, _content_type_params__set, _content_type_params__del, _content_type_params__get.__doc__ ) # # set_cookie, unset_cookie, delete_cookie, merge_cookies # def set_cookie(self, name=None, value='', max_age=None, path='/', domain=None, secure=False, httponly=False, comment=None, expires=None, overwrite=False, key=None): """ Set (add) a cookie for the response. Arguments are: ``name`` The cookie name. ``value`` The cookie value, which should be a string or ``None``. If ``value`` is ``None``, it's equivalent to calling the :meth:`webob.response.Response.unset_cookie` method for this cookie key (it effectively deletes the cookie on the client). ``max_age`` An integer representing a number of seconds, ``datetime.timedelta``, or ``None``. This value is used as the ``Max-Age`` of the generated cookie. If ``expires`` is not passed and this value is not ``None``, the ``max_age`` value will also influence the ``Expires`` value of the cookie (``Expires`` will be set to now + max_age). If this value is ``None``, the cookie will not have a ``Max-Age`` value (unless ``expires`` is set). If both ``max_age`` and ``expires`` are set, this value takes precedence. ``path`` A string representing the cookie ``Path`` value. It defaults to ``/``. ``domain`` A string representing the cookie ``Domain``, or ``None``. If domain is ``None``, no ``Domain`` value will be sent in the cookie. ``secure`` A boolean. If it's ``True``, the ``secure`` flag will be sent in the cookie, if it's ``False``, the ``secure`` flag will not be sent in the cookie. ``httponly`` A boolean. If it's ``True``, the ``HttpOnly`` flag will be sent in the cookie, if it's ``False``, the ``HttpOnly`` flag will not be sent in the cookie. ``comment`` A string representing the cookie ``Comment`` value, or ``None``. If ``comment`` is ``None``, no ``Comment`` value will be sent in the cookie. ``expires`` A ``datetime.timedelta`` object representing an amount of time, ``datetime.datetime`` or ``None``. A non-``None`` value is used to generate the ``Expires`` value of the generated cookie. If ``max_age`` is not passed, but this value is not ``None``, it will influence the ``Max-Age`` header. If this value is ``None``, the ``Expires`` cookie value will be unset (unless ``max_age`` is set). If ``max_age`` is set, it will be used to generate the ``expires`` and this value is ignored. ``overwrite`` If this key is ``True``, before setting the cookie, unset any existing cookie. """ # Backwards compatibility for the old name "key", remove this in 1.7 if name is None and key is not None: warn_deprecation('Argument "key" was renamed to "name".', 1.7, 1) name = key if name is None: raise TypeError('set_cookie() takes at least 1 argument') if overwrite: self.unset_cookie(name, strict=False) # If expires is set, but not max_age we set max_age to expires if not max_age and isinstance(expires, timedelta): max_age = expires # expires can also be a datetime if not max_age and isinstance(expires, datetime): max_age = expires - datetime.utcnow() value = bytes_(value, 'utf-8') cookie = make_cookie(name, value, max_age=max_age, path=path, domain=domain, secure=secure, httponly=httponly, comment=comment) self.headerlist.append(('Set-Cookie', cookie)) def delete_cookie(self, name, path='/', domain=None): """ Delete a cookie from the client. Note that path and domain must match how the cookie was originally set. This sets the cookie to the empty string, and max_age=0 so that it should expire immediately. """ self.set_cookie(name, None, path=path, domain=domain) def unset_cookie(self, name, strict=True): """ Unset a cookie with the given name (remove it from the response). """ existing = self.headers.getall('Set-Cookie') if not existing and not strict: return cookies = Cookie() for header in existing: cookies.load(header) if isinstance(name, text_type): name = name.encode('utf8') if name in cookies: del cookies[name] del self.headers['Set-Cookie'] for m in cookies.values(): self.headerlist.append(('Set-Cookie', m.serialize())) elif strict: raise KeyError("No cookie has been set with the name %r" % name) def merge_cookies(self, resp): """Merge the cookies that were set on this response with the given `resp` object (which can be any WSGI application). If the `resp` is a :class:`webob.Response` object, then the other object will be modified in-place. """ if not self.headers.get('Set-Cookie'): return resp if isinstance(resp, Response): for header in self.headers.getall('Set-Cookie'): resp.headers.add('Set-Cookie', header) return resp else: c_headers = [h for h in self.headerlist if h[0].lower() == 'set-cookie'] def repl_app(environ, start_response): def repl_start_response(status, headers, exc_info=None): return start_response(status, headers+c_headers, exc_info=exc_info) return resp(environ, repl_start_response) return repl_app # # cache_control # _cache_control_obj = None def _cache_control__get(self): """ Get/set/modify the Cache-Control header (`HTTP spec section 14.9 <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_) """ value = self.headers.get('cache-control', '') if self._cache_control_obj is None: self._cache_control_obj = CacheControl.parse( value, updates_to=self._update_cache_control, type='response') self._cache_control_obj.header_value = value if self._cache_control_obj.header_value != value: new_obj = CacheControl.parse(value, type='response') self._cache_control_obj.properties.clear() self._cache_control_obj.properties.update(new_obj.properties) self._cache_control_obj.header_value = value return self._cache_control_obj def _cache_control__set(self, value): # This actually becomes a copy if not value: value = "" if isinstance(value, dict): value = CacheControl(value, 'response') if isinstance(value, text_type): value = str(value) if isinstance(value, str): if self._cache_control_obj is None: self.headers['Cache-Control'] = value return value = CacheControl.parse(value, 'response') cache = self.cache_control cache.properties.clear() cache.properties.update(value.properties) def _cache_control__del(self): self.cache_control = {} def _update_cache_control(self, prop_dict): value = serialize_cache_control(prop_dict) if not value: if 'Cache-Control' in self.headers: del self.headers['Cache-Control'] else: self.headers['Cache-Control'] = value cache_control = property( _cache_control__get, _cache_control__set, _cache_control__del, doc=_cache_control__get.__doc__) # # cache_expires # def _cache_expires(self, seconds=0, **kw): """ Set expiration on this request. This sets the response to expire in the given seconds, and any other attributes are used for cache_control (e.g., private=True, etc). """ if seconds is True: seconds = 0 elif isinstance(seconds, timedelta): seconds = timedelta_to_seconds(seconds) cache_control = self.cache_control if seconds is None: pass elif not seconds: # To really expire something, you have to force a # bunch of these cache control attributes, and IE may # not pay attention to those still so we also set # Expires. cache_control.no_store = True cache_control.no_cache = True cache_control.must_revalidate = True cache_control.max_age = 0 cache_control.post_check = 0 cache_control.pre_check = 0 self.expires = datetime.utcnow() if 'last-modified' not in self.headers: self.last_modified = datetime.utcnow() self.pragma = 'no-cache' else: cache_control.properties.clear() cache_control.max_age = seconds self.expires = datetime.utcnow() + timedelta(seconds=seconds) self.pragma = None for name, value in kw.items(): setattr(cache_control, name, value) cache_expires = property(lambda self: self._cache_expires, _cache_expires) # # encode_content, decode_content, md5_etag # def encode_content(self, encoding='gzip', lazy=False): """ Encode the content with the given encoding (only gzip and identity are supported). """ assert encoding in ('identity', 'gzip'), \ "Unknown encoding: %r" % encoding if encoding == 'identity': self.decode_content() return if self.content_encoding == 'gzip': return if lazy: self.app_iter = gzip_app_iter(self._app_iter) self.content_length = None else: self.app_iter = list(gzip_app_iter(self._app_iter)) self.content_length = sum(map(len, self._app_iter)) self.content_encoding = 'gzip' def decode_content(self): content_encoding = self.content_encoding or 'identity' if content_encoding == 'identity': return if content_encoding not in ('gzip', 'deflate'): raise ValueError( "I don't know how to decode the content %s" % content_encoding) if content_encoding == 'gzip': from gzip import GzipFile from io import BytesIO gzip_f = GzipFile(filename='', mode='r', fileobj=BytesIO(self.body)) self.body = gzip_f.read() self.content_encoding = None gzip_f.close() else: # Weird feature: http://bugs.python.org/issue5784 self.body = zlib.decompress(self.body, -15) self.content_encoding = None def md5_etag(self, body=None, set_content_md5=False): """ Generate an etag for the response object using an MD5 hash of the body (the body parameter, or ``self.body`` if not given) Sets ``self.etag`` If ``set_content_md5`` is True sets ``self.content_md5`` as well """ if body is None: body = self.body md5_digest = md5(body).digest() md5_digest = b64encode(md5_digest) md5_digest = md5_digest.replace(b'\n', b'') md5_digest = native_(md5_digest) self.etag = md5_digest.strip('=') if set_content_md5: self.content_md5 = md5_digest # # __call__, conditional_response_app # def __call__(self, environ, start_response): """ WSGI application interface """ if self.conditional_response: return self.conditional_response_app(environ, start_response) headerlist = self._abs_headerlist(environ) start_response(self.status, headerlist) if environ['REQUEST_METHOD'] == 'HEAD': # Special case here... return EmptyResponse(self._app_iter) return self._app_iter def _abs_headerlist(self, environ): """Returns a headerlist, with the Location header possibly made absolute given the request environ. """ headerlist = list(self.headerlist) for i, (name, value) in enumerate(headerlist): if name.lower() == 'location': if SCHEME_RE.search(value): break new_location = urlparse.urljoin(_request_uri(environ), value) headerlist[i] = (name, new_location) break return headerlist _safe_methods = ('GET', 'HEAD') def conditional_response_app(self, environ, start_response): """ Like the normal __call__ interface, but checks conditional headers: * If-Modified-Since (304 Not Modified; only on GET, HEAD) * If-None-Match (304 Not Modified; only on GET, HEAD) * Range (406 Partial Content; only on GET, HEAD) """ req = BaseRequest(environ) headerlist = self._abs_headerlist(environ) method = environ.get('REQUEST_METHOD', 'GET') if method in self._safe_methods: status304 = False if req.if_none_match and self.etag: status304 = self.etag in req.if_none_match elif req.if_modified_since and self.last_modified: status304 = self.last_modified <= req.if_modified_since if status304: start_response('304 Not Modified', filter_headers(headerlist)) return EmptyResponse(self._app_iter) if (req.range and self in req.if_range and self.content_range is None and method in ('HEAD', 'GET') and self.status_code == 200 and self.content_length is not None ): content_range = req.range.content_range(self.content_length) if content_range is None: iter_close(self._app_iter) body = bytes_("Requested range not satisfiable: %s" % req.range) headerlist = [ ('Content-Length', str(len(body))), ('Content-Range', str(ContentRange(None, None, self.content_length))), ('Content-Type', 'text/plain'), ] + filter_headers(headerlist) start_response('416 Requested Range Not Satisfiable', headerlist) if method == 'HEAD': return () return [body] else: app_iter = self.app_iter_range(content_range.start, content_range.stop) if app_iter is not None: # the following should be guaranteed by # Range.range_for_length(length) assert content_range.start is not None headerlist = [ ('Content-Length', str(content_range.stop - content_range.start)), ('Content-Range', str(content_range)), ] + filter_headers(headerlist, ('content-length',)) start_response('206 Partial Content', headerlist) if method == 'HEAD': return EmptyResponse(app_iter) return app_iter start_response(self.status, headerlist) if method == 'HEAD': return EmptyResponse(self._app_iter) return self._app_iter def app_iter_range(self, start, stop): """ Return a new app_iter built from the response app_iter, that serves up only the given ``start:stop`` range. """ app_iter = self._app_iter if hasattr(app_iter, 'app_iter_range'): return app_iter.app_iter_range(start, stop) return AppIterRange(app_iter, start, stop) def filter_headers(hlist, remove_headers=('content-length', 'content-type')): return [h for h in hlist if (h[0].lower() not in remove_headers)] def iter_file(file, block_size=1<<18): # 256Kb while True: data = file.read(block_size) if not data: break yield data class ResponseBodyFile(object): mode = 'wb' closed = False def __init__(self, response): self.response = response self.write = response.write def __repr__(self): return '<body_file for %r>' % self.response encoding = property( lambda self: self.response.charset, doc="The encoding of the file (inherited from response.charset)" ) def writelines(self, seq): for item in seq: self.write(item) def close(self): raise NotImplementedError("Response bodies cannot be closed") def flush(self): pass class AppIterRange(object): """ Wraps an app_iter, returning just a range of bytes """ def __init__(self, app_iter, start, stop): assert start >= 0, "Bad start: %r" % start assert stop is None or (stop >= 0 and stop >= start), ( "Bad stop: %r" % stop) self.app_iter = iter(app_iter) self._pos = 0 # position in app_iter self.start = start self.stop = stop def __iter__(self): return self def _skip_start(self): start, stop = self.start, self.stop for chunk in self.app_iter: self._pos += len(chunk) if self._pos < start: continue elif self._pos == start: return b'' else: chunk = chunk[start-self._pos:] if stop is not None and self._pos > stop: chunk = chunk[:stop-self._pos] assert len(chunk) == stop - start return chunk else: raise StopIteration() def next(self): if self._pos < self.start: # need to skip some leading bytes return self._skip_start() stop = self.stop if stop is not None and self._pos >= stop: raise StopIteration chunk = next(self.app_iter) self._pos += len(chunk) if stop is None or self._pos <= stop: return chunk else: return chunk[:stop-self._pos] __next__ = next # py3 def close(self): iter_close(self.app_iter) class EmptyResponse(object): """An empty WSGI response. An iterator that immediately stops. Optionally provides a close method to close an underlying app_iter it replaces. """ def __init__(self, app_iter=None): if app_iter is not None and hasattr(app_iter, 'close'): self.close = app_iter.close def __iter__(self): return self def __len__(self): return 0 def next(self): raise StopIteration() __next__ = next # py3 def _request_uri(environ): """Like wsgiref.url.request_uri, except eliminates :80 ports Return the full request URI""" url = environ['wsgi.url_scheme']+'://' if environ.get('HTTP_HOST'): url += environ['HTTP_HOST'] else: url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT'] if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http': url = url[:-3] elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https': url = url[:-4] if PY3: # pragma: no cover script_name = bytes_(environ.get('SCRIPT_NAME', '/'), 'latin-1') path_info = bytes_(environ.get('PATH_INFO', ''), 'latin-1') else: script_name = environ.get('SCRIPT_NAME', '/') path_info = environ.get('PATH_INFO', '') url += url_quote(script_name) qpath_info = url_quote(path_info) if not 'SCRIPT_NAME' in environ: url += qpath_info[1:] else: url += qpath_info return url def iter_close(iter): if hasattr(iter, 'close'): iter.close() def gzip_app_iter(app_iter): size = 0 crc = zlib.crc32(b"") & 0xffffffff compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0) yield _gzip_header for item in app_iter: size += len(item) crc = zlib.crc32(item, crc) & 0xffffffff # The compress function may return zero length bytes if the input is # small enough; it buffers the input for the next iteration or for a # flush. result = compress.compress(item) if result: yield result # Similarly, flush may also not yield a value. result = compress.flush() if result: yield result yield struct.pack("<2L", crc, size & 0xffffffff) def _error_unicode_in_app_iter(app_iter, body): app_iter_repr = repr(app_iter) if len(app_iter_repr) > 50: app_iter_repr = ( app_iter_repr[:30] + '...' + app_iter_repr[-10:]) raise TypeError( 'An item of the app_iter (%s) was text, causing a ' 'text body: %r' % (app_iter_repr, body))
Suwmlee/XX-Net
lib/noarch/webob/response.py
Python
bsd-2-clause
43,354
<?php /** * ImdbData retrieval tools * * @package ImdbData * @copyright Copyright (c) 2013 Coen Zimmerman * @license http://www.tabun.nl/LICENSE.TXT Simplified BSD License * @version Release: @package_version@ * @link http://www.github.com/CJZimmerman/ImdbData */ // cakephp doesn't support namespaces //namespace ImdbData; //use ImdbData\RawWebData\RawWebDataInterface; //use ImdbData\ImdbDataInterpreter\ImdbDataInterpreterInterface; // cakephp including App::uses('RawWebDataInterface', 'ImdbData/RawWebData'); App::uses('ImdbDataInterpreterInterface', 'ImdbData/ImdbDataInterpreter'); /** * Retrieves and Provides data for a movie with a given IMDb Code * Created by ImdbDataFactory * * @package ImdbData */ class ImdbData { /** * @var string */ private $_imdbCode; /** * @var RawWebDataInterface */ private $_rawData; /** * @var ImdbDataInterpreterInterface */ private $_interpreter; /** * @var string */ public $error; /** * @var array */ private $_data = array( 'imdb_code' => null, 'title' => null, 'year' => null, 'rating' => null, 'duration' => null, 'directors' => array(), 'writers' => array(), 'cast' => array(), 'trivia' => array(), 'genres' => array(), 'countries' => array(), 'languages' => array(), 'colors' => array(), ); // array with organized imdb data /** * @param string $imdbCode * @param RawWebDataInterface $rawData * @param ImdbDataInterpreterInterface $interpreter */ public function __construct($imdbCode, RawWebDataInterface $rawData, ImdbDataInterpreterInterface $interpreter) { $this->_imdbCode = $imdbCode; $this->_rawData = $rawData; $this->_interpreter = $interpreter; $this->_data['imdb_code'] = $imdbCode; } /** * @return boolean whether any data was correctly retrieved */ public function getAndInterpretData() { $this->error = false; $data = $this->_rawData->getData($this->_imdbCode); if (empty($data)) { $this->error = "No data retrieved."; return false; } $this->_data = $this->_interpreter->interpretData($data); if (empty($this->_data) || !is_array($this->_data)) { $this->error = "Data could not be interpreted."; return false; } return true; } /** * @param string $type data type to retrieve, should be an index in the _data array * @return mixed data property (string or array), or null if property not found */ public function getProperty($type) { if (is_array($this->_data) && !empty($this->_data[$type])) { return $this->_data[$type]; } else { return null; } } /** * @return array */ public function getAllData() { return $this->_data; } }
djkost85/FilmsCakeApp
Lib/ImdbData/ImdbData.php
PHP
bsd-2-clause
3,269
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Part of CoreAudio Utility Classes */ #if !defined(__CADebugMacros_h__) #define __CADebugMacros_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include "CoreAudioTypes.h" #endif //============================================================================= // CADebugMacros //============================================================================= //#define CoreAudio_StopOnFailure 1 //#define CoreAudio_TimeStampMessages 1 //#define CoreAudio_ThreadStampMessages 1 //#define CoreAudio_FlushDebugMessages 1 #if TARGET_RT_BIG_ENDIAN #define CA4CCToCString(the4CC) { ((char*)&the4CC)[0], ((char*)&the4CC)[1], ((char*)&the4CC)[2], ((char*)&the4CC)[3], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[0]; theCString[1] = ((char*)&the4CC)[1]; theCString[2] = ((char*)&the4CC)[2]; theCString[3] = ((char*)&the4CC)[3]; theCString[4] = 0; } #else #define CA4CCToCString(the4CC) { ((char*)&the4CC)[3], ((char*)&the4CC)[2], ((char*)&the4CC)[1], ((char*)&the4CC)[0], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[3]; theCString[1] = ((char*)&the4CC)[2]; theCString[2] = ((char*)&the4CC)[1]; theCString[3] = ((char*)&the4CC)[0]; theCString[4] = 0; } #endif // This is a macro that does a sizeof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning a sizeof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define SizeOf32(X) ((UInt32)sizeof(X)) // This is a macro that does a offsetof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning an offsetof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define OffsetOf32(X, Y) ((UInt32)offsetof(X, Y)) // This macro casts the expression to a UInt32. It is called out specially to allow us to track casts // that have been added purely to avert -wshorten64-32 warnings on 64 bit platforms. // For want of a better place to park this, we'll park it here. #define ToUInt32(X) ((UInt32)(X)) #pragma mark Basic Definitions #if DEBUG || CoreAudio_Debug // can be used to break into debugger immediately, also see CADebugger #define BusError() { long* p=NULL; *p=0; } // basic debugging print routines #if TARGET_OS_MAC && !TARGET_API_MAC_CARBON extern void DebugStr(const unsigned char* debuggerMsg); #define DebugMessage(msg) DebugStr("\p"msg) #define DebugMessageN1(msg, N1) #define DebugMessageN2(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) #else #include "CADebugPrintf.h" #if (CoreAudio_FlushDebugMessages && !CoreAudio_UseSysLog) || defined(CoreAudio_UseSideFile) #define FlushRtn ,fflush(DebugPrintfFile) #else #define FlushRtn #endif #if CoreAudio_ThreadStampMessages #include <pthread.h> #include "CAHostTimeBase.h" #if TARGET_RT_64_BIT #define DebugPrintfThreadIDFormat "%16p" #else #define DebugPrintfThreadIDFormat "%8p" #endif #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " DebugPrintfThreadIDFormat " " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), pthread_self(), ## __VA_ARGS__) FlushRtn #elif CoreAudio_TimeStampMessages #include "CAHostTimeBase.h" #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), ## __VA_ARGS__) FlushRtn #else #define DebugMsg(inFormat, ...) DebugPrintf(inFormat, ## __VA_ARGS__) FlushRtn #endif #endif void DebugPrint(const char *fmt, ...); // can be used like printf #ifndef DEBUGPRINT #define DEBUGPRINT(msg) DebugPrint msg // have to double-parenthesize arglist (see Debugging.h) #endif #if VERBOSE #define vprint(msg) DEBUGPRINT(msg) #else #define vprint(msg) #endif // Original macro keeps its function of turning on and off use of CADebuggerStop() for both asserts and throws. // For backwards compat, it overrides any setting of the two sub-macros. #if CoreAudio_StopOnFailure #include "CADebugger.h" #undef CoreAudio_StopOnAssert #define CoreAudio_StopOnAssert 1 #undef CoreAudio_StopOnThrow #define CoreAudio_StopOnThrow 1 #define STOP CADebuggerStop() #else #define STOP #endif #if CoreAudio_StopOnAssert #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __ASSERT_STOP CADebuggerStop() #else #define __ASSERT_STOP #endif #if CoreAudio_StopOnThrow #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __THROW_STOP CADebuggerStop() #else #define __THROW_STOP #endif #else #define DebugMsg(inFormat, ...) #ifndef DEBUGPRINT #define DEBUGPRINT(msg) #endif #define vprint(msg) #define STOP #define __ASSERT_STOP #define __THROW_STOP #endif // Old-style numbered DebugMessage calls are implemented in terms of DebugMsg() now #define DebugMessage(msg) DebugMsg(msg) #define DebugMessageN1(msg, N1) DebugMsg(msg, N1) #define DebugMessageN2(msg, N1, N2) DebugMsg(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) DebugMsg(msg, N1, N2, N3) #define DebugMessageN4(msg, N1, N2, N3, N4) DebugMsg(msg, N1, N2, N3, N4) #define DebugMessageN5(msg, N1, N2, N3, N4, N5) DebugMsg(msg, N1, N2, N3, N4, N5) #define DebugMessageN6(msg, N1, N2, N3, N4, N5, N6) DebugMsg(msg, N1, N2, N3, N4, N5, N6) #define DebugMessageN7(msg, N1, N2, N3, N4, N5, N6, N7) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7) #define DebugMessageN8(msg, N1, N2, N3, N4, N5, N6, N7, N8) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8) #define DebugMessageN9(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) void LogError(const char *fmt, ...); // writes to syslog (and stderr if debugging) void LogWarning(const char *fmt, ...); // writes to syslog (and stderr if debugging) #define NO_ACTION (void)0 #if DEBUG || CoreAudio_Debug #pragma mark Debug Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessageN3("%s, line %d: %s", __FILE__, __LINE__, inMessage); \ __ASSERT_STOP; \ } #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %ld (%s)", (long int)__Err, __4CC); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ DebugMessageN2(inMessage ", Code: %d, Facility: 0x%X", HRESULT_CODE(__Err), HRESULT_FACILITY(__Err)); \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ DebugMessage(inMethodName": Subclasses must implement this method"); \ Throw(inException); \ } #endif // defined(__cplusplus) #else #pragma mark Release Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) Assert(inCondition, inMessage) #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ if((inKernelError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ if((inError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ Throw(inException); \ } #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ Throw(inException); \ } #endif // defined(__cplusplus) #endif // DEBUG || CoreAudio_Debug #endif
Norad-Eduapp4syria/Norad-Eduapp4syria
Sima/Kukua/Classes/RecorderScene/AQFoundation/CADebugMacros.h
C
bsd-2-clause
17,669
module Database.VCache.Open ( openVCache ) where import Control.Monad import Control.Exception import System.FileLock (FileLock) import qualified System.FileLock as FileLock import qualified System.EasyFile as EasyFile import qualified System.IO.Error as IOE import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Ptr import Data.Bits import Data.IORef import Data.Maybe import qualified Data.Map.Strict as Map import qualified Data.ByteString as BS import qualified Data.List as L import Control.Concurrent.MVar import Control.Concurrent.STM.TVar import Control.Concurrent import qualified System.IO as Sys import qualified System.Exit as Sys import Database.LMDB.Raw import Database.VCache.Types import Database.VCache.RWLock import Database.VCache.Aligned import Database.VCache.Write import Database.VCache.Clean -- | Open a VCache with a given database file. -- -- In most cases, a Haskell process should open VCache in the Main -- module then pass it as an argument to the different libraries, -- frameworks, plugins, and other software components that require -- persistent storage. Use vcacheSubdir to progect against namespace -- collisions. -- -- When opening VCache, developers decide the maximum size and the file -- name. For example: -- -- > vc <- openVCache 100 "db" -- -- This would open a VCache whose file-size limit is 100 megabytes, -- with the name "db", plus an additional "db-lock" lockfile. An -- exception will be raised if these files cannot be created, locked, -- or opened. The size limit is passed to LMDB and is separate from -- setVRefsCacheSize. -- -- Once opened, VCache typically remains open until process halt. -- If errors are detected, e.g. due to writing an undefined value -- to a PVar or running out of space, VCache will attempt to halt -- the process. -- openVCache :: Int -> FilePath -> IO VCache openVCache nMB fp = do let (fdir,fn) = EasyFile.splitFileName fp let eBadFile = fp ++ " not recognized as a file name" when (L.null fn) (fail $ "openVCache: " ++ eBadFile) EasyFile.createDirectoryIfMissing True fdir let fpLock = fp ++ "-lock" let nBytes = max 1 nMB * 1024 * 1024 mbLock <- FileLock.tryLockFile fpLock FileLock.Exclusive case mbLock of Nothing -> ioError $ IOE.mkIOError IOE.alreadyInUseErrorType "openVCache lockfile" Nothing (Just fpLock) Just fl -> openVC' nBytes fl fp `onException` FileLock.unlockFile fl vcFlags :: [MDB_EnvFlag] vcFlags = [MDB_NOSUBDIR -- open file name, not directory name ,MDB_NOLOCK -- leave lock management to VCache ] -- -- I'm providing a non-empty root bytestring. There are a few reasons -- for this. LMDB doesn't support zero-sized keys. And the empty -- bytestring will indicate anonymous PVars in the allocator. And if -- I ever want PVar roots within VCache, I can use a different prefix. -- -- The maximum path, including the PVar name, is 511 bytes. That is -- enough for almost any use case, especially since roots should not -- depend on domain data. Too large a path results in runtime error. vcRootPath :: BS.ByteString vcRootPath = BS.singleton 47 -- Default address for allocation. We start this high to help -- regulate serialization sizes and simplify debugging. vcAllocStart :: Address vcAllocStart = 999999999 -- Default cache size is somewhat arbitrary. I've chosen to set it -- to about ten megabytes (as documented in the Cache module). vcDefaultCacheLimit :: Int vcDefaultCacheLimit = 10 * 1000 * 1000 -- initial cache size vcInitCacheSizeEst :: CacheSizeEst vcInitCacheSizeEst = CacheSizeEst { csze_addr_size = sz -- err likely on high side to start , csze_addr_sqsz = sz * sz } where sz = 2048 -- err likely on high side to start -- Checking for a `-threaded` runtime threaded :: Bool threaded = rtsSupportsBoundThreads openVC' :: Int -> FileLock -> FilePath -> IO VCache openVC' nBytes fl fp = do unless threaded (fail "VCache needs -threaded runtime") dbEnv <- mdb_env_create mdb_env_set_mapsize dbEnv nBytes mdb_env_set_maxdbs dbEnv 5 mdb_env_open dbEnv fp vcFlags flip onException (mdb_env_close dbEnv) $ do -- initial transaction to grab database handles and init allocator txnInit <- mdb_txn_begin dbEnv Nothing False dbiMemory <- mdb_dbi_open' txnInit (Just "@") [MDB_CREATE, MDB_INTEGERKEY] dbiRoots <- mdb_dbi_open' txnInit (Just "/") [MDB_CREATE] dbiHashes <- mdb_dbi_open' txnInit (Just "#") [MDB_CREATE, MDB_INTEGERKEY, MDB_DUPSORT, MDB_DUPFIXED, MDB_INTEGERDUP] dbiRefct <- mdb_dbi_open' txnInit (Just "^") [MDB_CREATE, MDB_INTEGERKEY] dbiRefct0 <- mdb_dbi_open' txnInit (Just "%") [MDB_CREATE, MDB_INTEGERKEY] allocEnd <- findLastAddrAllocated txnInit dbiMemory mdb_txn_commit txnInit -- ephemeral resources let allocStart = nextAllocAddress allocEnd memory <- newMVar (initMemory allocStart) tvWrites <- newTVarIO (Writes Map.empty []) mvSignal <- newMVar () cLimit <- newIORef vcDefaultCacheLimit cSize <- newIORef vcInitCacheSizeEst cVRefs <- newMVar Map.empty gcStart <- newIORef Nothing gcCount <- newIORef 0 rwLock <- newRWLock -- finalizer, in unlikely event of closure _ <- mkWeakMVar mvSignal $ do mdb_env_close dbEnv FileLock.unlockFile fl let vc = VCache { vcache_path = vcRootPath , vcache_space = VSpace { vcache_lockfile = fl , vcache_db_env = dbEnv , vcache_db_memory = dbiMemory , vcache_db_vroots = dbiRoots , vcache_db_caddrs = dbiHashes , vcache_db_refcts = dbiRefct , vcache_db_refct0 = dbiRefct0 , vcache_memory = memory , vcache_signal = mvSignal , vcache_writes = tvWrites , vcache_rwlock = rwLock , vcache_climit = cLimit , vcache_csize = cSize , vcache_cvrefs = cVRefs , vcache_alloc_init = allocStart , vcache_gc_start = gcStart , vcache_gc_count = gcCount } } initVCacheThreads (vcache_space vc) return $! vc -- our allocator should be set for the next *even* address. nextAllocAddress :: Address -> Address nextAllocAddress addr | 0 == (addr .&. 1) = 2 + addr | otherwise = 1 + addr -- Determine the last VCache VRef address allocated, based on the -- actual database contents. If nothing is findLastAddrAllocated :: MDB_txn -> MDB_dbi' -> IO Address findLastAddrAllocated txn dbiMemory = alloca $ \ pKey -> mdb_cursor_open' txn dbiMemory >>= \ crs -> mdb_cursor_get' MDB_LAST crs pKey nullPtr >>= \ bFound -> mdb_cursor_close' crs >> if not bFound then return vcAllocStart else peek pKey >>= \ key -> let bBadSize = fromIntegral (sizeOf vcAllocStart) /= mv_size key in if bBadSize then fail "VCache memory table corrupted" else peekAligned (castPtr (mv_data key)) -- initialize memory based on initial allocation position initMemory :: Address -> Memory initMemory addr = m0 where af = AllocFrame Map.empty Map.empty [] addr ac = Allocator addr af af af gcf = GCFrame Map.empty gc = GC gcf gcf m0 = Memory Map.empty Map.empty gc ac -- | Create background threads needed by VCache. initVCacheThreads :: VSpace -> IO () initVCacheThreads vc = begin where begin = do task (writeStep vc) task (cleanStep vc) return () task step = void (forkIO (forever step `catch` onE)) onE :: SomeException -> IO () onE e | isBlockedOnMVar e = return () -- full GC of VCache onE e = do putErrLn "VCache background thread has failed." putErrLn (indent " " (show e)) putErrLn "Halting program." Sys.exitFailure isBlockedOnMVar :: (Exception e) => e -> Bool isBlockedOnMVar = isJust . test . toException where test :: SomeException -> Maybe BlockedIndefinitelyOnMVar test = fromException putErrLn :: String -> IO () putErrLn = Sys.hPutStrLn Sys.stderr indent :: String -> String -> String indent ws = (ws ++) . indent' where indent' ('\n':s) = '\n' : ws ++ indent' s indent' (c:s) = c : indent' s indent' [] = []
dmbarbour/haskell-vcache
hsrc_lib/Database/VCache/Open.hs
Haskell
bsd-2-clause
8,591
#!/usr/bin/python3 import beautifulScrap import xlsGenerate #Generate PHPUnit cheatsheet assertions rslt = [] rslt.append(("PHPunit CheatSheet Assert",)) rslt.append(("",)) rslt.append(("https://phpunit.de/",)) rslt.append(("https://github.com/sebastianbergmann/phpunit",)) rslt.append(("",)) rslt.append(("Support for PHPUnit 5 ends on February 2, 2018.","PHPUnit 5.7 is supported on PHP 5.6, PHP 7.0, and PHP 7.1.","https://phar.phpunit.de/phpunit-5.7.phar")) rslt.append(("Support for PHPUnit 6 ends on February 8, 2019.","PHPUnit 6.1 is supported on PHP 7.0 and PHP 7.1.","https://phar.phpunit.de/phpunit-6.1.phar")) rslt.append(("",)) rslt = rslt + beautifulScrap.beautifulScrap() xlsGenerate.scrapXls(rslt, "PHPUnit", "PHPUnit.xls")
Gu1Hub/CheatSheet_PHPUnit_Assertions
mainGenerate.py
Python
bsd-2-clause
745
@import 'FBEditor-all_1.css'; @import 'FBEditor-all_2.css';
Litres/FB3Editor
Frontend/b/production/FBEditor/resources/FBEditor-all.css
CSS
bsd-2-clause
60
package barsan.opengl.resources; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import barsan.opengl.Yeti; import barsan.opengl.rendering.materials.Material; import barsan.opengl.util.Color; public class MTLLoader { public static List<Material> load(String fileName) { Yeti.debug("Loading materials from MTL file:" + fileName); File file = new File(ResourceLoader.RESBASE + "models/" + fileName); List<Material> results = new ArrayList<>(); Scanner s = null; try { s = new Scanner(file); Material current = null; while(s.hasNextLine()) { String line = s.nextLine(); if(line.startsWith("#") || line.trim().startsWith("#")) continue; String tokens[] = line.trim().split("\\s+"); if(tokens.length == 0 || tokens[0].length() == 0) { if(current != null) { results.add(current); } } String cmd = tokens[0]; String[] params = Arrays.copyOfRange(tokens, 1, tokens.length); if(cmd.equals("newmtl")) { current = new Material(); current.setName(tokens[1]); } else if(cmd.equals("Ka")) { current.setAmbient(parseColor(params)); } else if(cmd.equals("Kd")) { current.setDiffuse(parseColor(params)); } else if(cmd.equals("Ks")) { current.setSpecular(parseColor(params)); } else if(cmd.equals("Ns")) { current.setSpecularIntensity(Float.parseFloat(params[0])); } else if(tokens[0].equals("map_Kd")) { String textureName = tokens[1]; Yeti.debug(String.format("Loading texture dependency of material %s: %s", current.getName(), textureName)); ResourceLoader.loadTexture(textureName); current.setDiffuseMap(ResourceLoader.texture( textureName.substring(0, textureName.lastIndexOf('.')) )); Yeti.debug("Done loading texture."); } else if(tokens[0].equals("map_Bump") || tokens[0].equals("map_bump")) { String textureName = tokens[1]; Yeti.debug(String.format("Loading texture dependency of material %s: %s", current.getName(), textureName)); ResourceLoader.loadTexture(textureName); current.setNormalMap(ResourceLoader.texture( textureName.substring(0, textureName.lastIndexOf('.')) )); } } if(current != null) { results.add(current); } } catch (FileNotFoundException e) { Yeti.screwed("Tried to load non-existent .mtl file: " + file.getAbsolutePath()); } finally { if(null != s) { s.close(); } } return results; } private static Color parseColor(String[] in) { return new Color( Float.parseFloat(in[0]), Float.parseFloat(in[1]), Float.parseFloat(in[2]) ); } }
AndreiBarsan/Yeti
src/barsan/opengl/resources/MTLLoader.java
Java
bsd-2-clause
2,789
/* * File: * System: * Module: * Author: * Copyright: * Source: $HeadURL: $ * Last modified by: $Author: $ * Date: $Date: $ * Version: $Revision: $ * Description: * Preconditions: */ package stallone.algebra; import static stallone.api.API.*; import stallone.api.doubles.IDoubleArray; import stallone.api.algebra.*; /** * LU Decomposition. * * <p>For an m-by-n matrix A with m &gt;= n, the LU decomposition is an m-by-n unit lower triangular matrix L, an n-by-n * upper triangular matrix U, and a permutation vector piv of length m so that<br/> * </p> * * <pre> A(piv,:) = L*U. * </pre> * * <p>If m &lt; n, then L is m-by-m and U is m-by-n.</p> * * <p>The LU decompostion with pivoting always exists, even if the matrix is singular, so the constructor will never * fail. The primary use of the LU decomposition is in the solution of square systems of simultaneous linear equations. * This will fail if isNonsingular() returns false.</p> * * @author Martin Senne */ public class RealLUDecomposition implements ILUDecomposition { /** matrix for storage of decomposition. */ private IDoubleArray luMatrix; /** row dimensions of A. */ private int m; /** column dimensions of A. */ private int n; /** pivot sign. */ private int pivotSign; /** pivot vector. */ private int[] pivots; /** * LU Decomposition. */ public RealLUDecomposition() { } /** * Set matrix A, for which to perform LU-Decomposition. * * @param matrixA */ @Override public void setMatrix(final IDoubleArray matrixA) { luMatrix = doublesNew.matrix(matrixA.rows(), matrixA.columns()); luMatrix.copyFrom(matrixA); m = matrixA.rows(); n = matrixA.columns(); } @Override public void perform() { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. pivots = new int[m]; for (int i = 0; i < m; i++) { pivots[i] = i; } pivotSign = 1; IDoubleArray LUrowi; IDoubleArray LUcolj; for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. LUcolj = luMatrix.viewColumn(j).copy(); // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = luMatrix.viewRow(i); // Most of the time is spent in the following dot product. final int kmax = Math.min(i, j); double s = 0.0d; for (int k = 0; k < kmax; k++) { s += LUrowi.get(k) * LUcolj.get(k); } LUcolj.set(i, LUcolj.get(i) - s); LUrowi.set(j, LUcolj.get(i)); } // Find pivot and exchange if necessary. int p = j; for (int i = j + 1; i < m; i++) { if (Math.abs(LUcolj.get(i)) > Math.abs(LUcolj.get(p))) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { final double t = luMatrix.get(p, k); luMatrix.set(p, k, luMatrix.get(j, k)); luMatrix.set(j, k, t); } final int k = pivots[p]; pivots[p] = pivots[j]; pivots[j] = k; pivotSign = -pivotSign; } // Compute multipliers. if ((j < m) && (luMatrix.get(j, j) != 0.0d)) { final double r = luMatrix.get(j, j); for (int i = j + 1; i < m; i++) { luMatrix.set(i, j, luMatrix.get(i, j) / r); } } } // end for } /** * Check for matrix nonsingularity. * * @return true if U, and hence A, is nonsingular. */ @Override public boolean isNonsingular() { for (int j = 0; j < n; j++) { if (luMatrix.get(j, j) == 0.0d) { return false; } } return true; } /** * Return lower triangular factor in new matrix. * * @return L */ @Override public IDoubleArray getL() { final IDoubleArray X = doublesNew.matrix(m, n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { X.set(i, j, luMatrix.get(i, j)); } else if (i == j) { X.set(i, j, 1.0d); } else { X.set(i, j, 0.0d); } } } return X; } /** * Get upper triangular factor in new matrix. * * @return U */ @Override public IDoubleArray getU() { final IDoubleArray X = doublesNew.matrix(n, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i <= j) { X.set(i, j, luMatrix.get(i, j)); } else { X.set(i, j, 0.0d); } } } return X; } /** * Return pivot permutation vector as int array. * * @return piv */ public int[] getPivot() { final int[] p = new int[m]; System.arraycopy(pivots, 0, p, 0, m); return p; } /** * Calculate determinant. * * @return deteterminant of A * * @exception IllegalArgumentException Matrix must be square */ @Override public double det() { if (m != n) { throw new IllegalArgumentException("Matrix must be square."); } double d = pivotSign; for (int j = 0; j < n; j++) { d *= luMatrix.get(j, j); } return d; } /** * Solve A*X = B. * * @param B A Matrix with as many rows as A and any number of columns. * * @return X so that L*U*X = B(piv,:) * * @exception IllegalArgumentException if matrix row dimensions do not agree. * @exception RuntimeException if matrix is singular. */ public IDoubleArray solve(final IDoubleArray B) { final int b_rows = B.rows(); final int b_cols = B.columns(); if (b_rows != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!isNonsingular()) { throw new RuntimeException("Matrix is singular."); } // copy right hand side in pivot order final IDoubleArray X = doublesNew.matrix(b_rows, b_cols); for (int i = 0; i < b_rows; i++) { final int pivotedRow = pivots[i]; for (int j = 0; j < b_cols; j++) { X.set(i, j, B.get(pivotedRow, j)); } } // solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k + 1; i < n; i++) { final double lu_ik = luMatrix.get(i, k); for (int j = 0; j < b_cols; j++) { final double a = X.get(k, j) * lu_ik; X.set(i, j, X.get(i, j) - a); } } } // solve U*X = Y; for (int k = n - 1; k >= 0; k--) { final double lu_kk = luMatrix.get(k, k); for (int j = 0; j < b_cols; j++) { X.set(k, j, X.get(k, j) / lu_kk); } for (int i = 0; i < k; i++) { final double lu_ik = luMatrix.get(i, k); for (int j = 0; j < b_cols; j++) { final double a = X.get(k, j) * lu_ik; X.set(i, j, X.get(i, j) - a); } } } return X; } }
markovmodel/stallone
src/stallone/algebra/RealLUDecomposition.java
Java
bsd-2-clause
8,378
// Copyright © 2011, Université catholique de Louvain // 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. // // 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 HOLDER 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. #ifndef __BOOSTENV_H #define __BOOSTENV_H #include "boostenv-decl.hh" #include "boostenvutils.hh" #include "boostenvtcp.hh" #include "boostenvpipe.hh" #ifndef MOZART_GENERATOR namespace mozart { namespace boostenv { ////////////////// // BoostBasedVM // ////////////////// ProtectedNode BoostBasedVM::allocAsyncIONode(StableNode* node) { _asyncIONodeCount++; return vm->protect(*node); } void BoostBasedVM::releaseAsyncIONode(const ProtectedNode& node) { assert(_asyncIONodeCount > 0); _asyncIONodeCount--; } ProtectedNode BoostBasedVM::createAsyncIOFeedbackNode(UnstableNode& readOnly) { StableNode* stable = new (vm) StableNode; stable->init(vm, Variable::build(vm)); readOnly = ReadOnly::newReadOnly(vm, *stable); return allocAsyncIONode(stable); } template <class LT, class... Args> void BoostBasedVM::bindAndReleaseAsyncIOFeedbackNode( const ProtectedNode& ref, LT&& label, Args&&... args) { UnstableNode rhs = buildTuple(vm, std::forward<LT>(label), std::forward<Args>(args)...); DataflowVariable(*ref).bind(vm, rhs); releaseAsyncIONode(ref); } template <class LT, class... Args> void BoostBasedVM::raiseAndReleaseAsyncIOFeedbackNode( const ProtectedNode& ref, LT&& label, Args&&... args) { UnstableNode exception = buildTuple(vm, std::forward<LT>(label), std::forward<Args>(args)...); bindAndReleaseAsyncIOFeedbackNode( ref, FailedValue::build(vm, RichNode(exception).getStableRef(vm))); } void BoostBasedVM::postVMEvent(std::function<void()> callback) { { boost::unique_lock<boost::mutex> lock(_conditionWorkToDoInVMMutex); _vmEventsCallbacks.push(callback); } vm->requestExitRun(); _conditionWorkToDoInVM.notify_all(); } /////////////// // Utilities // /////////////// atom_t systemStrToAtom(VM vm, const char* str) { size_t len = std::strlen(str); auto ustr = std::unique_ptr<nchar[]>(new nchar[len+1]); for (size_t i = 0; i <= len; i++) ustr[i] = (nchar) str[i]; return vm->getAtom(len, ustr.get()); } atom_t systemStrToAtom(VM vm, const std::string& str) { size_t len = str.length(); auto ustr = std::unique_ptr<nchar[]>(new nchar[len+1]); for (size_t i = 0; i <= len; i++) ustr[i] = (nchar) str[i]; return vm->getAtom(len, ustr.get()); } template <typename T> void raiseOSError(VM vm, const nchar* function, nativeint errnum, T&& message) { raiseSystem(vm, MOZART_STR("os"), MOZART_STR("os"), function, errnum, std::forward<T>(message)); } void raiseOSError(VM vm, const nchar* function, int errnum) { raiseOSError(vm, function, errnum, systemStrToAtom(vm, std::strerror(errnum))); } void raiseLastOSError(VM vm, const nchar* function) { raiseOSError(vm, function, errno); } void raiseOSError(VM vm, const nchar* function, boost::system::error_code& ec) { raiseOSError(vm, function, ec.value(), systemStrToAtom(vm, ec.message())); } void raiseOSError(VM vm, const nchar* function, const boost::system::system_error& error) { raiseOSError(vm, function, error.code().value(), systemStrToAtom(vm, error.what())); } } } #endif #if !defined(MOZART_GENERATOR) && !defined(MOZART_BUILTIN_GENERATOR) namespace mozart { namespace boostenv { namespace builtins { #include "boostenvbuiltins.hh" } } } #endif #endif // __BOOSTENV_H
amautave/mozart2-vm
boostenv/main/boostenv.hh
C++
bsd-2-clause
4,767
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Process; use Symfony\Component\Process\Exception\InvalidArgumentException; /** * ProcessUtils is a bunch of utility methods. * * This class contains static methods only and is not meant to be instantiated. * * @author Martin Hasoň <[email protected]> */ class ProcessUtils { /** * This class should not be instantiated. */ private function __construct() { } /** * Escapes a string to be used as a shell argument. * * @param string $argument The argument that will be escaped * * @return string The escaped argument */ public static function escapeArgument( $argument ) { //Fix for PHP bug #43784 escapeshellarg removes % from given string //Fix for PHP bug #49446 escapeshellarg doesn't work on Windows //@see https://bugs.php.net/bug.php?id=43784 //@see https://bugs.php.net/bug.php?id=49446 if ('\\' === DIRECTORY_SEPARATOR) { if ('' === $argument) { return escapeshellarg( $argument ); } $escapedArgument = ''; $quote = false; foreach (preg_split( '/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ) as $part) { if ('"' === $part) { $escapedArgument .= '\\"'; } elseif (self::isSurroundedBy( $part, '%' )) { // Avoid environment variable expansion $escapedArgument .= '^%"'.substr( $part, 1, -1 ).'"^%'; } else { // escape trailing backslash if ('\\' === substr( $part, -1 )) { $part .= '\\'; } $quote = true; $escapedArgument .= $part; } } if ($quote) { $escapedArgument = '"'.$escapedArgument.'"'; } return $escapedArgument; } return escapeshellarg( $argument ); } private static function isSurroundedBy( $arg, $char ) { return 2 < strlen( $arg ) && $char === $arg[0] && $char === $arg[strlen( $arg ) - 1]; } /** * Validates and normalizes a Process input. * * @param string $caller The name of method call that validates the input * @param mixed $input The input to validate * * @return string The validated input * * @throws InvalidArgumentException In case the input is not valid */ public static function validateInput( $caller, $input ) { if (null !== $input) { if (is_resource( $input )) { return $input; } if (is_scalar( $input )) { return (string)$input; } // deprecated as of Symfony 2.5, to be removed in 3.0 if (is_object( $input ) && method_exists( $input, '__toString' )) { return (string)$input; } throw new InvalidArgumentException( sprintf( '%s only accepts strings or stream resources.', $caller ) ); } return $input; } }
TheTypoMaster/SPHERE-Framework
Library/MOC-V/Core/SecureKernel/Vendor/PhpSecLib/0.3.9/vendor/symfony/process/Symfony/Component/Process/ProcessUtils.php
PHP
bsd-2-clause
3,425
#!/bin/sh # # Virtualmin Installation Bootstrapper for FreeBSD # # Copyright (c) 2015, Daniel Morante # 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. # # 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 HOLDER 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. set -e # FreeBSD should have fetch installed by default. export FETCH=$(which fetch) export TAR=$(which tar) # Continue to support versions older than 10-RELEASE (for now) if $(which freebsd-version > /dev/null); then export OS_VERSION=$(/bin/freebsd-version | awk -F '-' '{ print $1}') export PRE10_RELEASE=false else export OS_VERSION=$(uname -r | cut -d'-' -f1) export PRE10_RELEASE=true fi export LOG=~/virtualmin-install.log ############################ # Sanity Checks ############################ # Make sure we are on FreeBSD if [ "$OSTYPE" != "FreeBSD" ]; then echo "Fatal Error: This Virtualmin install script is for FreeBSD" exit 1 fi # Currently we support FreeBSD 9.x thru 12.x if [ $(echo $OS_VERSION | awk -F '.' '{ print $1 }') -lt "9" ]; then echo "Fatal Error: This script requires at least FreeBSD version 9.x" exit 1 fi # Only root can run this if [ $(id -u) -ne 0 ]; then echo "Fatal Error: The Virtualmin install script must be run as root" exit 1 fi # Check for localhost in /etc/hosts grep localhost /etc/hosts >/dev/null if [ "$?" != 0 ]; then echo "There is no localhost entry in /etc/hosts. Installation cannot continue." exit 1 fi # Find system temporary directory if [ "$TMPDIR" = "" ]; then TMPDIR=/tmp fi # Check whether TMPDIR is mounted noexec (everything will fail, if so) if [ ! -z "$(mount | grep ${TMPDIR} | grep noexec)" ]; then echo "${TMPDIR} directory is mounted noexec. Installation cannot continue." exit 1 fi # Support overrides via env variables. # TODO: Move elsewhere? [ -z "${LDAP_URI}" ] || [ -z "${LDAP_BASE_DN}" ] SKIP_LDAP_SERVER_INSTALL=$? ########################## # Initializtion ########################## # Temporary directory to store supporting libs TMPDIR=$TMPDIR/.virtualmin-$$ if [ -e "$TMPDIR" ]; then rm -rf $TMPDIR fi mkdir -p $TMPDIR/files srcdir=$TMPDIR/files cd $srcdir # Download and extract libraries $FETCH -o $TMPDIR http://ftp.morante.net/pub/FreeBSD/extra/virtualmin/freebsd-virtualmin.tar.xz $TAR -xzf $TMPDIR/freebsd-virtualmin.tar.xz -C $srcdir chmod +x $srcdir/spinner # Load Libraries . $srcdir/packages.subr . $srcdir/util.subr . $srcdir/system.subr . $srcdir/install.subr ########################## # System Setup ########################## set +e setup_pkg_repos init_logging generate_self_signed_ssl_certificate ########################## # Begin Install ########################## logger_info "FreeBSD Operating system version: $OS_VERSION" setup_hostname config_discovery_ldap install_core_services install_core_utilities disable_sendmail disable_sendmail_tasks setup_apache setup_postfix setup_dovecot setup_mysql setup_postgresql setup_openldap setup_webmin setup_usermin webmin_configure_bind webmin_configure_apache webmin_configure_dovecot webmin_configure_mysql webmin_configure_postgresql webmin_configure_openldap install_virtualmin_modules enable_services ########################## # Complete ########################## start_services resolvconf_local_nameserver_ip logger_info "Installation is complete. You may now login to Virtualmin at https://$(hostname -f):10000 (https://$(getent hosts $(hostname -f) | awk '{ print $1 }'):10000)" ########################## # Clean Up ########################## if [ -e "$TMPDIR" ]; then rm -rf $TMPDIR fi
tuaris/freebsd-virtualmin
installer/install.sh
Shell
bsd-2-clause
4,705
// See the COPYRIGHT file for copyright and license information package org.znerd.util.text; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.znerd.util.Preconditions; /** * Text string utility functions. */ public class TextUtils { private static final String NULL_STRING = "(null)"; /** * Puts quote characters around the string representation of an object, escaping all backslash and quote characters inside the string. Returns <code>"(null)"</code> if the object is * <code>null</code> or if the object's <code>toString()</code> method returns <code>null</code>. */ public static final String quote(Object o) { if (o == null) { return NULL_STRING; } String s = o.toString(); if (s == null) { return NULL_STRING; } s = s.replaceAll("\\\\", Matcher.quoteReplacement("\\\\")); s = s.replaceAll("\"", Matcher.quoteReplacement("\\\"")); return '"' + s + '"'; } /** * Checks if the specified string is either <code>null</code> or empty or contains only whitespace. */ public static final boolean isEmpty(String s) { return s == null || "".equals(s.trim()); } /** * Checks if the specified string matches the specified regular expression. * <p> * This method differs from {@link String#matches(String)} in that this method also supports partial matches. To give an example: * * <pre> * &quot;bla bla&quot;.match(&quot;bla$&quot;); // returns false * TextUtils.matches(&quot;bla bla&quot;, &quot;bla$&quot;); // returns true * </pre> */ public static final boolean matches(String s, String regex) { Preconditions.checkArgument(s == null, "s == null"); Preconditions.checkArgument(regex == null, "regex == null"); return Pattern.compile(regex).matcher(s).find(); } /** * Compares the specified strings for equality, after normalizing whitespace and ignoring case. * * @param s1 * the first string, or <code>null</code>. * @param s2 * the second string, or <code>null</code>. * @return if <code>s1</code> and <code>s2</code> are considered equal, normalizing whitespace and ignoring case. */ public static boolean fuzzyEquals(String s1, String s2) { s1 = normalizeWhitespace(s1); s2 = normalizeWhitespace(s2); return s1.equalsIgnoreCase(s2); } /** * Removes all leading and trailing whitespace from a string, and replaces all internal whitespace with a single space character. If <code>null</code> is passed, then <code>""</code> is returned. * * @param s * the string, or <code>null</code>. * @return the string with all leading and trailing whitespace removed and all internal whitespace normalized, never <code>null</code>. */ public static String normalizeWhitespace(String s) { String normalized = ""; if (s != null) { s = s.trim(); boolean prevIsWhitespace = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean thisIsWhitespace = (c <= 0x20); if (!(thisIsWhitespace && prevIsWhitespace)) { if (thisIsWhitespace) { normalized += ' '; prevIsWhitespace = true; } else { normalized += c; prevIsWhitespace = false; } } } } return normalized; } private TextUtils() { } }
znerd/znerd-util
src/main/java/org/znerd/util/text/TextUtils.java
Java
bsd-2-clause
3,723
class Orbit < Formula desc "CORBA 2.4-compliant object request broker (ORB)" homepage "https://projects.gnome.org/ORBit2" url "https://download.gnome.org/sources/ORBit2/2.14/ORBit2-2.14.19.tar.bz2" sha256 "55c900a905482992730f575f3eef34d50bda717c197c97c08fa5a6eafd857550" bottle do sha256 "11bb24fb06daef1ccea017470e23e56706c24265a4f7551a14d99e4f88121781" => :el_capitan sha256 "adf8c93736bee9ceede9f65ae9e4d6d10529a085315ec522bfd661a7b6fcd94a" => :yosemite sha256 "ae04763dcb6ea680fba27e49b01235d65204cd9240a871b429095fa414fda4fb" => :mavericks sha256 "9f987a2d8be82cf391d2903872cfe20ce304cbc91fbe638820c41b00a3ecb4cc" => :mountain_lion end depends_on "pkg-config" => :build depends_on "glib" depends_on "libidl" # per MacPorts, re-enable use of deprecated glib functions patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/6b7eaf2b/orbit/patch-linc2-src-Makefile.in.diff" sha256 "572771ea59f841d74ac361d51f487cc3bcb2d75dacc9c20a8bd6cbbaeae8f856" end patch :p0 do url "https://raw.githubusercontent.com/Homebrew/formula-patches/6b7eaf2b/orbit/patch-configure.diff" sha256 "34d068df8fc9482cf70b291032de911f0e75a30994562d4cf56b0cc2a8e28e42" end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do assert_match /#{version}/, shell_output("#{bin}/orbit2-config --prefix --version") end end
ShivaHuang/homebrew-core
Formula/orbit.rb
Ruby
bsd-2-clause
1,516
/** * \file * * \brief Instance description for PM * * Copyright (c) 2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * 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. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #ifndef _SAMC21_PM_INSTANCE_ #define _SAMC21_PM_INSTANCE_ /* ========== Register definition for PM peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_PM_SLEEPCFG (0x40000401U) /**< \brief (PM) Sleep Configuration */ #define REG_PM_STDBYCFG (0x40000408U) /**< \brief (PM) Standby Configuration */ #else #define REG_PM_SLEEPCFG (*(RwReg8 *)0x40000401U) /**< \brief (PM) Sleep Configuration */ #define REG_PM_STDBYCFG (*(RwReg16*)0x40000408U) /**< \brief (PM) Standby Configuration */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ /* ========== Instance parameters for PM peripheral ========== */ #define PM_BIAS_RAM_HS 1 // one if RAM HS can be back biased #define PM_PD_NUM 0 // Number of switchable Power Domain #endif /* _SAMC21_PM_INSTANCE_ */
sam-geek/ArduinoModule-CMSIS-Atmel
CMSIS-Atmel/CMSIS/Device/ATMEL/samc21/include/instance/pm.h
C
bsd-2-clause
2,659
import unittest from porunga import get_manager from porunga.commands.test import PorungaTestCommand class TestManager(unittest.TestCase): def test_manager_has_proper_commands(self): manager = get_manager() commands = manager.get_commands() self.assertTrue('test' in commands) test_command = commands['test'] self.assertTrue(isinstance(test_command, PorungaTestCommand))
lukaszb/porunga
porunga/tests/test_main.py
Python
bsd-2-clause
420
<?php /** * Navigator: a geographic calculation library for PHP * @link http://navigator.simonholywell.com * @license http://www.opensource.org/licenses/bsd-license.php BSD 2-Clause License * @copyright 2012, Simon Holywell * @author Simon Holywell <[email protected]> */ use Treffynnon\Navigator as N; use Treffynnon\Navigator\CelestialBody as CB; class CalculatorAbstractTest extends PHPUnit_Framework_TestCase { public function testGetCelestialBody() { $stub = $this->getMockForAbstractClass('Treffynnon\Navigator\Distance\Calculator\CalculatorAbstract'); $stub->expects($this->any()) ->method('__construct') ->will($this->returnValue(true)); $this->assertInstanceOf('Treffynnon\Navigator\CelestialBody\Earth', $stub->getCelestialBody()); } }
treffynnon/Navigator
tests/Treffynnon/Navigator/Distance/Calculator/CalculatorAbstractTest.php
PHP
bsd-2-clause
814
/*++ Copyright (C) 2015 Microsoft Corporation (Original Author) Copyright (C) 2015 netfabb 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: 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 HOLDER 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. Abstract: NMR_ModelWriter_ColorMappingContainer.cpp implements the Model Writer Color Mapping Container Class. --*/ #include "Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.h" #include "Common/NMR_Exception.h" #include "Common/NMR_Exception_Windows.h" #include "Common/NMR_Types.h" namespace NMR { CModelWriter_TexCoordMappingContainer::CModelWriter_TexCoordMappingContainer() { } CModelWriter_TexCoordMappingContainer::~CModelWriter_TexCoordMappingContainer() { } nfBool CModelWriter_TexCoordMappingContainer::hasTexture(_In_ ModelResourceID nTextureID) { auto iIterator = m_TextureMappings.find(nTextureID); return (iIterator != m_TextureMappings.end()); } PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::findTexture(_In_ ModelResourceID nTextureID) { auto iIterator = m_TextureMappings.find(nTextureID); if (iIterator != m_TextureMappings.end()) { return iIterator->second; } else { return nullptr; } } PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::addTexture(_In_ ModelResourceID nTextureID, _In_ ModelResourceID nResourceID) { if (hasTexture(nTextureID)) throw CNMRException(NMR_ERROR_DUPLICATETEXTURE); PModelWriter_TexCoordMapping pTexture = std::make_shared<CModelWriter_TexCoordMapping>(nResourceID, nTextureID); m_TextureMappings.insert(std::make_pair(nTextureID, pTexture)); m_TextureMappingVector.push_back(pTexture); return pTexture; } nfUint32 CModelWriter_TexCoordMappingContainer::getCount() { return (nfUint32)m_TextureMappingVector.size(); } PModelWriter_TexCoordMapping CModelWriter_TexCoordMappingContainer::getMapping(_In_ nfUint32 nIndex) { return m_TextureMappingVector[nIndex]; } }
3DGEOM/lib3mf
Source/Model/Writer/NMR_ModelWriter_TexCoordMappingContainer.cpp
C++
bsd-2-clause
3,091
############################################################################### # ntplib - Python NTP library. # Copyright (C) 2009 Charles-Francois Natali <[email protected]> # # ntplib is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA ############################################################################### """Python NTP library. Implementation of client-side NTP (RFC-1305), and useful NTP-related functions. """ import datetime import socket import struct import time class NTPException(Exception): """Exception raised by this module.""" pass class NTP: """Helper class defining constants.""" _SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3]) """system epoch""" _NTP_EPOCH = datetime.date(1900, 1, 1) """NTP epoch""" NTP_DELTA = (_SYSTEM_EPOCH - _NTP_EPOCH).days * 24 * 3600 """delta between system and NTP time""" REF_ID_TABLE = { 'DNC': "DNC routing protocol", 'NIST': "NIST public modem", 'TSP': "TSP time protocol", 'DTS': "Digital Time Service", 'ATOM': "Atomic clock (calibrated)", 'VLF': "VLF radio (OMEGA, etc)", 'callsign': "Generic radio", 'LORC': "LORAN-C radionavidation", 'GOES': "GOES UHF environment satellite", 'GPS': "GPS UHF satellite positioning", } """reference identifier table""" STRATUM_TABLE = { 0: "unspecified", 1: "primary reference", } """stratum table""" MODE_TABLE = { 0: "unspecified", 1: "symmetric active", 2: "symmetric passive", 3: "client", 4: "server", 5: "broadcast", 6: "reserved for NTP control messages", 7: "reserved for private use", } """mode table""" LEAP_TABLE = { 0: "no warning", 1: "last minute has 61 seconds", 2: "last minute has 59 seconds", 3: "alarm condition (clock not synchronized)", } """leap indicator table""" class NTPPacket: """NTP packet class. This represents an NTP packet. """ _PACKET_FORMAT = "!B B B b 11I" """packet format to pack/unpack""" def __init__(self, version=2, mode=3, tx_timestamp=0): """Constructor. Parameters: version -- NTP version mode -- packet mode (client, server) tx_timestamp -- packet transmit timestamp """ self.leap = 0 """leap second indicator""" self.version = version """version""" self.mode = mode """mode""" self.stratum = 0 """stratum""" self.poll = 0 """poll interval""" self.precision = 0 """precision""" self.root_delay = 0 """root delay""" self.root_dispersion = 0 """root dispersion""" self.ref_id = 0 """reference clock identifier""" self.ref_timestamp = 0 """reference timestamp""" self.orig_timestamp = 0 """originate timestamp""" self.recv_timestamp = 0 """receive timestamp""" self.tx_timestamp = tx_timestamp """tansmit timestamp""" def to_data(self): """Convert this NTPPacket to a buffer that can be sent over a socket. Returns: buffer representing this packet Raises: NTPException -- in case of invalid field """ try: packed = struct.pack(NTPPacket._PACKET_FORMAT, (self.leap << 6 | self.version << 3 | self.mode), self.stratum, self.poll, self.precision, _to_int(self.root_delay) << 16 | _to_frac(self.root_delay, 16), _to_int(self.root_dispersion) << 16 | _to_frac(self.root_dispersion, 16), self.ref_id, _to_int(self.ref_timestamp), _to_frac(self.ref_timestamp), _to_int(self.orig_timestamp), _to_frac(self.orig_timestamp), _to_int(self.recv_timestamp), _to_frac(self.recv_timestamp), _to_int(self.tx_timestamp), _to_frac(self.tx_timestamp)) except struct.error: raise NTPException("Invalid NTP packet fields.") return packed def from_data(self, data): """Populate this instance from a NTP packet payload received from the network. Parameters: data -- buffer payload Raises: NTPException -- in case of invalid packet format """ try: unpacked = struct.unpack(NTPPacket._PACKET_FORMAT, data[0:struct.calcsize(NTPPacket._PACKET_FORMAT)]) except struct.error: raise NTPException("Invalid NTP packet.") self.leap = unpacked[0] >> 6 & 0x3 self.version = unpacked[0] >> 3 & 0x7 self.mode = unpacked[0] & 0x7 self.stratum = unpacked[1] self.poll = unpacked[2] self.precision = unpacked[3] self.root_delay = float(unpacked[4])/2**16 self.root_dispersion = float(unpacked[5])/2**16 self.ref_id = unpacked[6] self.ref_timestamp = _to_time(unpacked[7], unpacked[8]) self.orig_timestamp = _to_time(unpacked[9], unpacked[10]) self.recv_timestamp = _to_time(unpacked[11], unpacked[12]) self.tx_timestamp = _to_time(unpacked[13], unpacked[14]) class NTPStats(NTPPacket): """NTP statistics. Wrapper for NTPPacket, offering additional statistics like offset and delay, and timestamps converted to system time. """ def __init__(self): """Constructor.""" NTPPacket.__init__(self) self.dest_timestamp = 0 """destination timestamp""" @property def offset(self): """offset""" return ((self.recv_timestamp - self.orig_timestamp) + (self.tx_timestamp - self.dest_timestamp))/2 @property def delay(self): """round-trip delay""" return ((self.dest_timestamp - self.orig_timestamp) - (self.tx_timestamp - self.recv_timestamp)) @property def tx_time(self): """Transmit timestamp in system time.""" return ntp_to_system_time(self.tx_timestamp) @property def recv_time(self): """Receive timestamp in system time.""" return ntp_to_system_time(self.recv_timestamp) @property def orig_time(self): """Originate timestamp in system time.""" return ntp_to_system_time(self.orig_timestamp) @property def ref_time(self): """Reference timestamp in system time.""" return ntp_to_system_time(self.ref_timestamp) @property def dest_time(self): """Destination timestamp in system time.""" return ntp_to_system_time(self.dest_timestamp) class NTPClient: """NTP client session.""" def __init__(self): """Constructor.""" pass def request(self, host, version=2, port='ntp', timeout=5): """Query a NTP server. Parameters: host -- server name/address version -- NTP version to use port -- server port timeout -- timeout on socket operations Returns: NTPStats object """ # lookup server address addrinfo = socket.getaddrinfo(host, port)[0] family, sockaddr = addrinfo[0], addrinfo[4] # create the socket s = socket.socket(family, socket.SOCK_DGRAM) try: s.settimeout(timeout) # create the request packet - mode 3 is client query_packet = NTPPacket(mode=3, version=version, tx_timestamp=system_to_ntp_time(time.time())) # send the request s.sendto(query_packet.to_data(), sockaddr) # wait for the response - check the source address src_addr = None, while src_addr[0] != sockaddr[0]: response_packet, src_addr = s.recvfrom(256) # build the destination timestamp dest_timestamp = system_to_ntp_time(time.time()) except socket.timeout: raise NTPException("No response received from %s." % host) finally: s.close() # construct corresponding statistics stats = NTPStats() stats.from_data(response_packet) stats.dest_timestamp = dest_timestamp return stats def _to_int(timestamp): """Return the integral part of a timestamp. Parameters: timestamp -- NTP timestamp Retuns: integral part """ return int(timestamp) def _to_frac(timestamp, n=32): """Return the fractional part of a timestamp. Parameters: timestamp -- NTP timestamp n -- number of bits of the fractional part Retuns: fractional part """ return int(abs(timestamp - _to_int(timestamp)) * 2**n) def _to_time(integ, frac, n=32): """Return a timestamp from an integral and fractional part. Parameters: integ -- integral part frac -- fractional part n -- number of bits of the fractional part Retuns: timestamp """ return integ + float(frac)/2**n def ntp_to_system_time(timestamp): """Convert a NTP time to system time. Parameters: timestamp -- timestamp in NTP time Returns: corresponding system time """ return timestamp - NTP.NTP_DELTA def system_to_ntp_time(timestamp): """Convert a system time to a NTP time. Parameters: timestamp -- timestamp in system time Returns: corresponding NTP time """ return timestamp + NTP.NTP_DELTA def leap_to_text(leap): """Convert a leap indicator to text. Parameters: leap -- leap indicator value Returns: corresponding message Raises: NTPException -- in case of invalid leap indicator """ if leap in NTP.LEAP_TABLE: return NTP.LEAP_TABLE[leap] else: raise NTPException("Invalid leap indicator.") def mode_to_text(mode): """Convert a NTP mode value to text. Parameters: mode -- NTP mode Returns: corresponding message Raises: NTPException -- in case of invalid mode """ if mode in NTP.MODE_TABLE: return NTP.MODE_TABLE[mode] else: raise NTPException("Invalid mode.") def stratum_to_text(stratum): """Convert a stratum value to text. Parameters: stratum -- NTP stratum Returns: corresponding message Raises: NTPException -- in case of invalid stratum """ if stratum in NTP.STRATUM_TABLE: return NTP.STRATUM_TABLE[stratum] elif 1 < stratum < 255: return "secondary reference (NTP)" else: raise NTPException("Invalid stratum.") def ref_id_to_text(ref_id, stratum=2): """Convert a reference clock identifier to text according to its stratum. Parameters: ref_id -- reference clock indentifier stratum -- NTP stratum Returns: corresponding message Raises: NTPException -- in case of invalid stratum """ fields = (ref_id >> 24 & 0xff, ref_id >> 16 & 0xff, ref_id >> 8 & 0xff, ref_id & 0xff) # return the result as a string or dot-formatted IP address if 0 <= stratum <= 1 : text = '%c%c%c%c' % fields if text in NTP.REF_ID_TABLE: return NTP.REF_ID_TABLE[text] else: return text elif 2 <= stratum < 255: return '%d.%d.%d.%d' % fields else: raise NTPException("Invalid stratum.")
mikeh77/mi-instrument
mi/platform/util/ntplib.py
Python
bsd-2-clause
12,376
var psc = require('primus-sinon-chai'); global.expect = psc.chai.expect; global.sinon = psc.sinon; global.sparkSpy = psc.spark;
netpocket/relay
test/spec_helper.js
JavaScript
bsd-2-clause
129
package picasso.graph //Warning: the iterator skips the first location class Trace[A,B](val start: A, val transitions: List[(B,A)]) extends Iterable[(B,A)] { /** Returns the number of transition in the trace (#state -1) */ def length = transitions.length def states = start :: transitions.map(_._2) def labels = transitions.map(_._1) def stop = if (transitions.length == 0) start else transitions.last._2 def step = { if (transitions.isEmpty) { throw new java.util.NoSuchElementException("step called on an empty trace") } val (t,b) = transitions.head ((start, t), new Trace(b, transitions.tail)) } override def iterator = transitions.iterator private def mkTriple(acc: List[(A,B,A)], current: A, rest: List[(B,A)]): List[(A,B,A)] = rest match { case (b,a)::xs => mkTriple( (current,b,a)::acc, a, xs) case Nil => acc.reverse } def extremities: (A,A) = (start, stop) def innerStates: List[A] = transitions.map(_._2).dropRight(1) def triples: List[(A,B,A)] = mkTriple(Nil, start, transitions) def append(s: A, t: B) = new Trace(start, transitions ::: List((t,s))) def concat(t: B, trc: Trace[A,B]) = new Trace(start, transitions ::: List(t -> trc.start) ::: trc.transitions) def prepend(s: A, t: B) = new Trace(s, (t,start) :: transitions ) def reverse = new Trace(stop, triples.reverse map ( t => (t._2, t._1))) def split(at: A => Boolean): List[Trace[A,B]] = { var acc: List[Trace[A,B]] = Nil var current = this while (!current.transitions.isEmpty) { val t1Prefix = current.transitions.takeWhile(elt => !at(elt._2)) val t2Augmented = current.transitions.drop(t1Prefix.length) if(t2Augmented.isEmpty) { acc = current :: acc current = new Trace(current.stop, Nil) } else { acc = new Trace(current.start, t1Prefix :+ t2Augmented.head) :: acc current = new Trace(t2Augmented.head._2, t2Augmented.tail) } } assert(current.transitions.isEmpty) acc.reverse } def split(at: A): List[Trace[A,B]] = split(_ == at) def splitAfter(n: Int): (Trace[A,B],Trace[A,B]) = { val (t1, t2) = transitions.splitAt(n) val part1 = new Trace(start, t1) val part2 = new Trace(part1.stop, t2) (part1, part2) } override def toString = start + transitions.map( p => (p._1 + " => "+p._2)).mkString(" => ", " => ", "") override def equals(any: Any) = any match { case t: Trace[_,_] => start == t.start && transitions == t.transitions case _ => false } } object Trace { def apply[A,B](start: A, transitions: (B,A)*) = new Trace[A,B](start, transitions.toList) } trait Traceable[A,B] { def isTraceValid(t: Trace[A,B]): Boolean }
dzufferey/picasso
core/src/main/scala/picasso/graph/Traceable.scala
Scala
bsd-2-clause
2,721
using System; using System.Collections.Generic; using MeidoCommon.ExtensionMethods; namespace MeidoCommon { public class TopicHelp : BaseHelp { public readonly string Topic; TopicHelp(string topic, DynamicHelp dHelp) : base(dHelp) { if (topic == null) throw new ArgumentNullException(nameof(topic)); Topic = topic; } public TopicHelp(string topic, string documentation) : this(topic, new DynamicHelp(documentation)) {} public TopicHelp(string topic, IEnumerable<string> documentation) : this(topic, new DynamicHelp(documentation)) {} public TopicHelp(string topic, Func<string> documentation) : this(topic, new DynamicHelp(documentation)) {} } }
IvionSauce/MeidoBot
MeidoCommon/Help/TopicHelp.cs
C#
bsd-2-clause
812
/* Copyright (c) 2008 nemesis Developers Association. All rights reserved. Governed by the nemesis License 3.0 the full text of which is contained in the file License.txt included in nemesis binary and source code distribution packages. */ #ifndef TC_HEADER_Platform_Unix_Process #define TC_HEADER_Platform_Unix_Process #include "Platform/PlatformBase.h" #include "Platform/Buffer.h" #include "Platform/Functor.h" namespace nemesis { struct ProcessExecFunctor { virtual ~ProcessExecFunctor () { } virtual void operator() (int argc, char *argv[]) = 0; }; class Process { public: Process (); virtual ~Process (); static string Execute (const string &processName, const list <string> &arguments, int timeOut = -1, ProcessExecFunctor *execFunctor = nullptr, const Buffer *inputData = nullptr); protected: private: Process (const Process &); Process &operator= (const Process &); }; } #endif // TC_HEADER_Platform_Unix_Process
adouble42/nemesis-current
Platform/Unix/Process.h
C
bsd-2-clause
959
import math import os import io import os from ctypes import c_void_p from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GL.shaders import * from PIL import Image, ImageDraw, ImageFont, ImageFilter import numpy as np from PyEngine3D.Common import logger from PyEngine3D.Common.Constants import * from PyEngine3D.Utilities import * SIMPLE_VERTEX_SHADER = ''' #version 430 core struct VERTEX_INPUT { layout(location=0) vec3 position; layout(location=1) vec2 tex_coord; }; struct VERTEX_OUTPUT { vec2 tex_coord; vec3 position; }; in VERTEX_INPUT vs_input; out VERTEX_OUTPUT vs_output; void main() { vs_output.tex_coord = vs_input.tex_coord; vs_output.position = vs_input.position; gl_Position = vec4(vs_input.position, 1.0); }''' SIMPLE_PIXEL_SHADER = ''' #version 430 core uniform sampler2D texture_font; uniform float font_size; struct VERTEX_OUTPUT { vec2 tex_coord; vec3 position; }; in VERTEX_OUTPUT vs_output; out vec4 fs_output; void main(void) { vec2 texture_font_size = textureSize(texture_font, 0); float min_dist = 1.0; vec2 font_count = ceil(texture_font_size / font_size); vec2 start_tex_coord = floor(vs_output.tex_coord.xy * font_count) / font_count; const float diff = 0.9; float value = texture(texture_font, vs_output.tex_coord.xy).x; if(value < diff) { for(float y=0.0; y<font_size; y+=1.0) { for(float x=0.0; x<font_size; x+=1.0) { vec2 other_tex_coord = start_tex_coord + vec2(x, y) / texture_font_size; float other_value = texture(texture_font, other_tex_coord).x; if((other_value - value) > (1.0 - diff)) { float dist = length(other_tex_coord - vs_output.tex_coord.xy); if(dist < min_dist) { min_dist = dist; } } } } } else { min_dist = 0.0; } //fs_output.xyz = vec3(1.0 - min_dist * max(font_count.x, font_count.y)); fs_output.xyz = vec3(1.0 - min_dist); fs_output.w = 1.0; } ''' def DistanceField(font_size, image_width, image_height, image_mode, image_data): # GL setting glFrontFace(GL_CCW) glEnable(GL_TEXTURE_2D) glDisable(GL_DEPTH_TEST) glDisable(GL_CULL_FACE) glDisable(GL_LIGHTING) glDisable(GL_BLEND) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # Create Shader vertex_shader = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertex_shader, SIMPLE_VERTEX_SHADER) glCompileShader(vertex_shader) if glGetShaderiv(vertex_shader, GL_COMPILE_STATUS) != 1 or True: infoLogs = glGetShaderInfoLog(vertex_shader) if infoLogs: if type(infoLogs) == bytes: infoLogs = infoLogs.decode("utf-8") print(infoLogs) fragment_shader = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragment_shader, SIMPLE_PIXEL_SHADER) glCompileShader(fragment_shader) if glGetShaderiv(fragment_shader, GL_COMPILE_STATUS) != 1 or True: infoLogs = glGetShaderInfoLog(fragment_shader) if infoLogs: if type(infoLogs) == bytes: infoLogs = infoLogs.decode("utf-8") print(infoLogs) # Create Program program = glCreateProgram() # Link Shaders glAttachShader(program, vertex_shader) glAttachShader(program, fragment_shader) glLinkProgram(program) # delete shader glDetachShader(program, vertex_shader) glDetachShader(program, fragment_shader) glDeleteShader(vertex_shader) glDeleteShader(fragment_shader) # Vertex Array Data dtype = np.float32 positions = np.array([(-1, 1, 0), (-1, -1, 0), (1, -1, 0), (1, 1, 0)], dtype=np.float32) texcoords = np.array([(0, 1), (0, 0), (1, 0), (1, 1)], dtype=np.float32) indices = np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32) # data serialize vertex_datas = np.hstack([positions, texcoords]).astype(dtype) # crate vertex array vertex_array = glGenVertexArrays(1) glBindVertexArray(vertex_array) vertex_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, vertex_datas, GL_STATIC_DRAW) index_buffer_size = indices.nbytes index_buffer = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer) glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_buffer_size, indices, GL_STATIC_DRAW) # Create Texture texture_format = GL_RGBA if image_mode == 'RGB': texture_format = GL_RGB texture_buffer = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture_buffer) glTexImage2D(GL_TEXTURE_2D, 0, texture_format, image_width, image_height, 0, texture_format, GL_UNSIGNED_BYTE, image_data) glGenerateMipmap(GL_TEXTURE_2D) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glBindTexture(GL_TEXTURE_2D, 0) # Create RenderTarget render_target_buffer = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, render_target_buffer) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL_POINTER) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glBindTexture(GL_TEXTURE_2D, 0) # Create FrameBuffer frame_buffer = glGenFramebuffers(1) gl_error = glCheckFramebufferStatus(GL_FRAMEBUFFER) if gl_error != GL_FRAMEBUFFER_COMPLETE: logger.error("glCheckFramebufferStatus error %d." % gl_error) # Bind Frame Buffer glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, render_target_buffer, 0) glReadBuffer(GL_COLOR_ATTACHMENT0) glDrawBuffers(1, [GL_COLOR_ATTACHMENT0, ]) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0) glViewport(0, 0, image_width, image_height) glClearColor(1.0, 1.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) # bind program glUseProgram(program) font_size_location = glGetUniformLocation(program, "font_size") glUniform1f(font_size_location, font_size) # bind texture texture_location = glGetUniformLocation(program, "texture_font") glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture_buffer) glUniform1i(texture_location, 0) # Bind Vertex Array glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) vertex_position_size = positions[0].nbytes vertex_texcoord_size = texcoords[0].nbytes vertex_buffer_size = vertex_position_size + vertex_texcoord_size location = 0 offset = 0 stride = len(positions[0]) glEnableVertexAttribArray(location) glVertexAttribPointer(location, stride, GL_FLOAT, GL_FALSE, vertex_buffer_size, c_void_p(offset)) location = 1 offset += vertex_position_size stride = len(texcoords[0]) glEnableVertexAttribArray(1) glVertexAttribPointer(location, stride, GL_FLOAT, GL_FALSE, vertex_buffer_size, c_void_p(offset)) # bind index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer) # Draw Quad glDrawElements(GL_TRIANGLES, index_buffer_size, GL_UNSIGNED_INT, NULL_POINTER) # Save glBindTexture(GL_TEXTURE_2D, render_target_buffer) save_image_data = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE) glBindTexture(GL_TEXTURE_2D, 0) return save_image_data def generate_font_data(resource_name, distance_field_font, anti_aliasing, font_size, padding, unicode_block_name, range_min, range_max, source_filepath, preview_path=''): logger.info("Convert Font %s %s : %s" % (resource_name, unicode_block_name, source_filepath)) back_ground_color = (0, 0, 0) font_color = (255, 255, 255) count = abs(range_max - range_min) + 1 count_of_side = int(math.ceil(math.sqrt(count))) # make texture size to power of 2. # texture_size = (2 ** math.ceil(math.log2(texture_size))) if 4 < texture_size else 4 try: unicode_font = ImageFont.truetype(source_filepath, font_size - padding * 2) except: logger.error(traceback.format_exc()) return None max_font_size = font_size for unicode_index in range(range_min, range_max + 1): unicode_text = chr(unicode_index) # u"\u2605" + u"\u2606" + u"Текст на русском" + u"파이썬" width, height = unicode_font.getsize(unicode_text) max_font_size = max(max_font_size, max(width, height)) font_size = max_font_size texture_size = font_size * count_of_side if texture_size > 8096: logger.error("%s texture size is too large. %d" % (unicode_block_name, texture_size)) return None image = Image.new("RGB", (texture_size, texture_size), back_ground_color) draw = ImageDraw.Draw(image) if anti_aliasing: draw.fontmode = "L" else: draw.fontmode = "1" unicode_index = range_min for y in range(count_of_side): for x in range(count_of_side): unicode_text = chr(unicode_index) # u"\u2605" + u"\u2606" + u"Текст на русском" + u"파이썬" draw.text((x * font_size, y * font_size), unicode_text, font=unicode_font, fill=font_color) unicode_index += 1 if unicode_index >= range_max: break else: continue break # Flip Vertical # image = image.transpose(Image.FLIP_TOP_BOTTOM) image_data = image.tobytes("raw", image.mode, 0, -1) if distance_field_font: image_data = DistanceField(font_size, image.size[0], image.size[1], image.mode, image_data) # save for preview if preview_path: texture_name = "_".join([resource_name, unicode_block_name]) image = Image.frombytes(image.mode, image.size, image_data) image.save(os.path.join(preview_path, texture_name + ".png")) # image.show() font_data = dict( unicode_block_name=unicode_block_name, range_min=range_min, range_max=range_max, text_count=count, font_size=font_size, count_of_side=count_of_side, image_mode=image.mode, image_width=image.size[0], image_height=image.size[1], image_data=image_data, texture=None ) return font_data
ubuntunux/GuineaPig
PyEngine3D/ResourceManager/FontLoader.py
Python
bsd-2-clause
10,842
{% extends "clancy/authorization/base.html" %} {% load i18n %} {% block content %} <div class="container login-container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-primary"> <div class="panel-heading centered"> <i class="fa fa-key fa-5x"></i> </div> <div class="panel-body"> {% if messages %} <ul class="messages"> {% for message in messages %} <span class="label {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} label-danger {% else %} label-success {% endif %}"> {{ message }} </span> {% endfor %} </ul> {% endif %} <form class="form-resetpass" action="{% url 'auth:reset-password' user_id uuid %}" method="post"> {% csrf_token %} <div {% if form.password.errors %} class="form-group has-error" {% endif %}> {% if form.password.errors %} {% for error in form.password.errors %} <span class="label label-danger">{{ error }}</span> {% endfor %} {% endif %} <label for="{{ form.password.id_for_label }}" class="sr-only">{{ form.password.label }}</label> <input type="password" id="{{ form.password.id_for_label }}" class="form-control" placeholder="{{ form.password.label }}" {% if form.password.value %} value="{{ form.password.value }}" {% endif %} name="{{ form.password.name }}" required autofocus > </div> <div {% if form.password.errors %} class="form-group has-error" {% endif %}> {% if form.password2.errors %} {% for error in form.password2.errors %} <span class="label label-danger">{{ error }}</span> {% endfor %} {% endif %} <label for="{{ form.password2.id_for_label }}" class="sr-only">{{ form.password2.label }}</label> <input type="password" id="{{ form.password2.id_for_label }}" class="form-control" placeholder="{{ form.password2.label }}" {% if form.password2.value %} value="{{ form.password2.value }}" {% endif %} name="{{ form.password2.name }}" required> </div> <input id="{{ form.redirect_uri.id_for_label }}" name="{{ form.redirect_uri.name }}" type="hidden" value="{{ form.redirect_uri.value }}"> <button class="btn btn-lg btn-primary btn-block btn-default" type="submit">{% trans "reset password" %}</button> </form> </div> </div> </div> </div> </div> <!-- /container --> {% endblock content %}
qdqmedia/wiggum
wiggum/themes/templates/clancy/authorization/reset_password.html
HTML
bsd-3-clause
3,121
package org.tolweb.tapestry.xml.taxaimport.beans; import java.util.ArrayList; import java.util.List; /* document structure will look something like this: tree-of-life-web nodes node page contributors -> contributor accessorypages -> accessorypage mediafiles -> mediafile othernames -> othername */ /** * @author lenards */ public class OMRoot { private String xmlns; private String id; private Long basalNodeId; private List<OMNode> nodes; public OMRoot() { this.nodes = new ArrayList<OMNode>(); } public void addNode(OMNode node) { getNodes().add(node); } /** * @return the node */ public List<OMNode> getNodes() { return nodes; } /** * @param node the node to set */ public void setNodes(List<OMNode> nodes) { this.nodes = nodes; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the basalNodeId */ public Long getBasalNodeId() { return basalNodeId; } /** * @param basalNodeId the basalNodeId to set */ public void setBasalNodeId(Long basalNodeId) { this.basalNodeId = basalNodeId; } /** * @return the xmlns */ public String getXmlNamespace() { return xmlns; } /** * @param xmlns the xmlns to set */ public void setXmlNamespace(String ns) { this.xmlns = ns; } }
tolweb/tolweb-app
OnlineContributors/src/org/tolweb/tapestry/xml/taxaimport/beans/OMRoot.java
Java
bsd-3-clause
1,394
using System; using System.Collections.Generic; using System.IO; using Coevery.Caching; using Coevery.FileSystems.WebSite; namespace Coevery.Tests.DisplayManagement.Descriptors { public class InMemoryWebSiteFolder : IWebSiteFolder { public InMemoryWebSiteFolder() { Contents = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } public IDictionary<string, string> Contents { get; set; } public IEnumerable<string> ListDirectories(string virtualPath) { throw new NotImplementedException(); } public IEnumerable<string> ListFiles(string virtualPath, bool recursive) { throw new NotImplementedException(); } public bool FileExists(string virtualPath) { throw new NotImplementedException(); } public string ReadFile(string virtualPath) { string result; return Contents.TryGetValue(virtualPath, out result) ? result : null; } public string ReadFile(string virtualPath, bool actualContent) { throw new NotImplementedException(); } public void CopyFileTo(string virtualPath, Stream destination) { throw new NotImplementedException(); } public void CopyFileTo(string virtualPath, Stream destination, bool actualContent) { throw new NotImplementedException(); } public IVolatileToken WhenPathChanges(string virtualPath) { return new Token { IsCurrent = true }; } public class Token : IVolatileToken { public bool IsCurrent { get; set; } } } }
Coevery/Coevery-Framework
src/Coevery.Tests/DisplayManagement/Descriptors/InMemoryWebSiteFolder.cs
C#
bsd-3-clause
1,671
// 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. #ifndef COMPONENTS_TAB_GROUPS_TAB_GROUP_COLOR_H_ #define COMPONENTS_TAB_GROUPS_TAB_GROUP_COLOR_H_ #include <stddef.h> #include <map> #include <string> #include "base/component_export.h" #include "base/containers/flat_map.h" #include "third_party/skia/include/core/SkColor.h" namespace tab_groups { // IMPORTANT: Do not change or reuse the values of any item in this enum. // These values are written to and read from disk for session and tab restore. // // Any changes to the tab group color set should be made in the map returned by // GetColorSet(). The set of valid colors is contained in the keys of that map. // Do not add or delete items in this enum without also reflecting that change // in the map. // // Any code that reads an enum value from disk should check it against the map // from GetColorSet(). If the value is not contained in the map's keys, default // to kGrey. enum class TabGroupColorId { kGrey = 0, kBlue = 1, kRed = 2, kYellow = 3, kGreen = 4, kPink = 5, kPurple = 6, kCyan = 7, // Next value: 8 }; using ColorLabelMap = base::flat_map<TabGroupColorId, std::u16string>; // Returns a map of TabGroupColorIds to their string labels. // When reading color IDs from disk, always verify against the keys in this // map for valid values. COMPONENT_EXPORT(TAB_GROUPS) const ColorLabelMap& GetTabGroupColorLabelMap(); } // namespace tab_groups #endif // COMPONENTS_TAB_GROUPS_TAB_GROUP_COLOR_H_
scheib/chromium
components/tab_groups/tab_group_color.h
C
bsd-3-clause
1,606
Spree::Core::Engine.routes.draw do resources :callback, controller: :call_backs, only: [:new, :create] do get 'notice' end namespace :admin do resources :callback, controller: :callbacks end # Add your extension routes here end
artem-russkikh/spree_call_me
config/routes.rb
Ruby
bsd-3-clause
246
#ifndef SHILL_DATA_H #define SHILL_DATA_H /* cap data */ struct shill_session; struct shill_cap { uint32_t sc_flags; struct shill_cap *sc_lookup; struct shill_cap *sc_createfile; struct shill_cap *sc_createdir; LIST_ENTRY(shill_cap) sc_session_list; }; struct shill_label { struct shill_session *sl_session; struct shill_cap *sl_cap; LIST_ENTRY(shill_label) sl_label_list; LIST_ENTRY(shill_label) sl_session_list; }; LIST_HEAD(shill_cap_list, shill_cap); LIST_HEAD(shill_label_list, shill_label); /* network cap data */ struct shill_network_cap { int snc_af_family; int snc_socket_type; uint64_t snc_permissions; /* a back pointer to the session, used when checking permissions for a given * thread */ struct shill_session *snc_session; LIST_ENTRY(shill_network_cap) snc_session_list; LIST_ENTRY(shill_network_cap) snc_socket_list; }; LIST_HEAD(shill_network_cap_list, shill_network_cap); /* session data */ struct shill_session { uint64_t ss_refcount; struct shill_cap_list ss_cap_root; struct shill_label_list ss_label_root; uint8_t ss_state; struct shill_session *ss_parent; struct shill_network_cap_list ss_network_cap_list; struct shill_cap *ss_pipefactory_cap; }; #define SESSIONPTR(session) ((((uintptr_t)(session)) & 1) ? NULL : (session)) #define SESSION_INIT 1 #define SESSION_START 3 #define SESSION_DEBUG 5 #endif /* SHILL_DATA_H */
HarvardPL/shill
kmod/shill-data.h
C
bsd-3-clause
1,409
<!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>isTypeSupported method - MediaKeys class - polymer_app_layout.behaviors 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 isTypeSupported method from the MediaKeys 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">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys-class.html">MediaKeys</a></li> <li class="self-crumb">isTypeSupported</li> </ol> <div class="self-name">isTypeSupported</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys-class.html">MediaKeys</a></li> <li class="self-crumb">isTypeSupported</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">method</div> isTypeSupported </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> <li><a href="polymer_app_layout.behaviors/MediaKeys/isTypeSupported.html#source">Source</a></li> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">polymer_app_layout_template</a></h5> <h5><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></h5> <h5><a href="polymer_app_layout.behaviors/MediaKeys-class.html">MediaKeys</a></h5> <ol> <li class="section-title"><a href="polymer_app_layout.behaviors/MediaKeys-class.html#static-methods">Static methods</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys/create.html">create</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys/isTypeSupported.html">isTypeSupported</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/MediaKeys-class.html#instance-properties">Properties</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys/keySystem.html">keySystem</a> </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <div> <ol class="comma-separated metadata-annotations"> <li class="metadata-annotation">@DomName(&apos;MediaKeys.isTypeSupported&apos;)</li> <li class="metadata-annotation">@DocsEditable()</li> <li class="metadata-annotation">@Experimental()</li> </ol> </div> <span class="returntype">bool</span> <span class="name ">isTypeSupported</span>( <br> <div class="parameters"> <span class="parameter" id="isTypeSupported-param-keySystem"><span class="type-annotation">String</span> <span class="parameter-name">keySystem</span></span>,<br><span class="parameter" id="isTypeSupported-param-contentType"><span class="type-annotation">String</span> <span class="parameter-name">contentType</span></span> </div> ) </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> <section class="summary source-code" id="source"> <h2>Source</h2> <pre><code class="prettyprint lang-dart">@DomName(&apos;MediaKeys.isTypeSupported&apos;) @DocsEditable() @Experimental() // untriaged static bool isTypeSupported(String keySystem, String contentType) =&gt; _blink.BlinkMediaKeys.instance.isTypeSupported_Callback_2_(keySystem, contentType);</code></pre> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> polymer_app_layout_template 0.1.0 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>
lejard-h/polymer_app_layout_templates
doc/api/polymer_app_layout.behaviors/MediaKeys/isTypeSupported.html
HTML
bsd-3-clause
6,204
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrYUVtoRGBEffect.h" #include "GrCoordTransform.h" #include "GrEffect.h" #include "gl/GrGLEffect.h" #include "gl/GrGLShaderBuilder.h" #include "GrTBackendEffectFactory.h" namespace { class YUVtoRGBEffect : public GrEffect { public: static GrEffect* Create(GrTexture* yTexture, GrTexture* uTexture, GrTexture* vTexture) { return SkNEW_ARGS(YUVtoRGBEffect, (yTexture, uTexture, vTexture)); } static const char* Name() { return "YUV to RGB"; } virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE { return GrTBackendEffectFactory<YUVtoRGBEffect>::getInstance(); } virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const SK_OVERRIDE { // YUV is opaque *color = 0xFF; *validFlags = kA_GrColorComponentFlag; } class GLEffect : public GrGLEffect { public: // this class always generates the same code. static EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&) { return 0; } GLEffect(const GrBackendEffectFactory& factory, const GrDrawEffect&) : INHERITED(factory) { } virtual void emitCode(GrGLShaderBuilder* builder, const GrDrawEffect&, EffectKey, const char* outputColor, const char* inputColor, const TransformedCoordsArray& coords, const TextureSamplerArray& samplers) SK_OVERRIDE { const char* yuvMatrix = "yuvMatrix"; builder->fsCodeAppendf("\tconst mat4 %s = mat4(1.0, 0.0, 1.402, -0.701,\n\t\t\t" "1.0, -0.344, -0.714, 0.529,\n\t\t\t" "1.0, 1.772, 0.0, -0.886,\n\t\t\t" "0.0, 0.0, 0.0, 1.0);\n", yuvMatrix); builder->fsCodeAppendf("\t%s = vec4(\n\t\t", outputColor); builder->fsAppendTextureLookup(samplers[0], coords[0].c_str(), coords[0].type()); builder->fsCodeAppend(".r,\n\t\t"); builder->fsAppendTextureLookup(samplers[1], coords[0].c_str(), coords[0].type()); builder->fsCodeAppend(".r,\n\t\t"); builder->fsAppendTextureLookup(samplers[2], coords[0].c_str(), coords[0].type()); builder->fsCodeAppendf(".r,\n\t\t1.0) * %s;\n", yuvMatrix); } typedef GrGLEffect INHERITED; }; private: YUVtoRGBEffect(GrTexture* yTexture, GrTexture* uTexture, GrTexture* vTexture) : fCoordTransform(kLocal_GrCoordSet, MakeDivByTextureWHMatrix(yTexture), yTexture) , fYAccess(yTexture) , fUAccess(uTexture) , fVAccess(vTexture) { this->addCoordTransform(&fCoordTransform); this->addTextureAccess(&fYAccess); this->addTextureAccess(&fUAccess); this->addTextureAccess(&fVAccess); this->setWillNotUseInputColor(); } virtual bool onIsEqual(const GrEffect& sBase) const { const YUVtoRGBEffect& s = CastEffect<YUVtoRGBEffect>(sBase); return fYAccess.getTexture() == s.fYAccess.getTexture() && fUAccess.getTexture() == s.fUAccess.getTexture() && fVAccess.getTexture() == s.fVAccess.getTexture(); } GrCoordTransform fCoordTransform; GrTextureAccess fYAccess; GrTextureAccess fUAccess; GrTextureAccess fVAccess; typedef GrEffect INHERITED; }; } ////////////////////////////////////////////////////////////////////////////// GrEffect* GrYUVtoRGBEffect::Create(GrTexture* yTexture, GrTexture* uTexture, GrTexture* vTexture) { return YUVtoRGBEffect::Create(yTexture, uTexture, vTexture); }
zhangyongfei/StudySkia
src/gpu/effects/GrYUVtoRGBEffect.cpp
C++
bsd-3-clause
4,046
<!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/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>IOSS: src/Ioss_Bar2.C File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">IOSS &#160;<span id="projectnumber">2.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('Ioss__Bar2_8C.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Namespaces</a> </div> <div class="headertitle"> <div class="title">Ioss_Bar2.C File Reference</div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><code>#include &quot;<a class="el" href="Ioss__CodeTypes_8h_source.html">Ioss_CodeTypes.h</a>&quot;</code><br /> <code>#include &quot;<a class="el" href="Ioss__ElementTopology_8h_source.html">Ioss_ElementTopology.h</a>&quot;</code><br /> <code>#include &lt;<a class="el" href="Ioss__Bar2_8h_source.html">Ioss_Bar2.h</a>&gt;</code><br /> <code>#include &lt;<a class="el" href="Ioss__ElementVariableType_8h_source.html">Ioss_ElementVariableType.h</a>&gt;</code><br /> <code>#include &lt;cassert&gt;</code><br /> <code>#include &lt;cstddef&gt;</code><br /> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classIoss_1_1St__Bar2.html">Ioss::St_Bar2</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structanonymous__namespace_02Ioss__Bar2_8C_03_1_1Constants.html">anonymous_namespace{Ioss_Bar2.C}::Constants</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Namespaces</h2></td></tr> <tr class="memitem:namespaceIoss"><td class="memItemLeft" align="right" valign="top"> &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceIoss.html">Ioss</a></td></tr> <tr class="memdesc:namespaceIoss"><td class="mdescLeft">&#160;</td><td class="mdescRight">The main namespace for the <a class="el" href="namespaceIoss.html" title="The main namespace for the Ioss library. ">Ioss</a> library. <br /></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:namespaceanonymous__namespace_02Ioss__Bar2_8C_03"><td class="memItemLeft" align="right" valign="top"> &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceanonymous__namespace_02Ioss__Bar2_8C_03.html">anonymous_namespace{Ioss_Bar2.C}</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="Ioss__Bar2_8C.html">Ioss_Bar2.C</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
nschloe/seacas
docs/ioss_html/Ioss__Bar2_8C.html
HTML
bsd-3-clause
6,168
#include "mex.h" #include "RigidBodyConstraint.h" #include "drakeUtil.h" #include "../RigidBodyManipulator.h" #include <cstring> /* * [lower_bound,upper_bound] = testPostureConstraintmex(postureConstraint_ptr,t) * @param postureConstraint_ptr A pointer to a PostureConstraint object * @param t A double scalar, the time to evaluate the lower and upper bounds, This is optional if the constraint is time-invariant * @retval lower_bound The lower bound of the joints at time t * @retval upper_bound The upper bound of the joints at time t * */ void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray *prhs[]) { if(nrhs != 2 && nrhs != 1) { mexErrMsgIdAndTxt("Drake:testPostureConstraintmex:BadInputs","Usage [lb,ub] = testPostureConstraintmex(pc_ptr,t)"); } double t; double* t_ptr; if(nrhs == 1) { t_ptr = nullptr; } else { t = mxGetScalar(prhs[1]); t_ptr = &t; } PostureConstraint* pc = (PostureConstraint*) getDrakeMexPointer(prhs[0]); int nq = pc->getRobotPointer()->num_dof; VectorXd lb,ub; pc->bounds(t_ptr,lb,ub); plhs[0] = mxCreateDoubleMatrix(nq,1,mxREAL); plhs[1] = mxCreateDoubleMatrix(nq,1,mxREAL); memcpy(mxGetPr(plhs[0]),lb.data(),sizeof(double)*nq); memcpy(mxGetPr(plhs[1]),ub.data(),sizeof(double)*nq); }
manuelli/drake
systems/plants/constraint/testPostureConstraintmex.cpp
C++
bsd-3-clause
1,356
// // TimerTest.h // // $Id$ // // Definition of the TimerTest class. // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef TimerTest_INCLUDED #define TimerTest_INCLUDED #include "Poco/Foundation.h" #include "CppUnit/TestCase.h" #include "Poco/Timer.h" #include "Poco/Event.h" class TimerTest: public CppUnit::TestCase { public: TimerTest(const std::string& name); ~TimerTest(); void testTimer(); void testDuplicateStop(); void setUp(); void tearDown(); static CppUnit::Test* suite(); protected: void onTimer(Poco::Timer& t); private: Poco::Event _event; }; #endif // TimerTest_INCLUDED
nocnokneo/MITK
Utilities/Poco/Foundation/testsuite/src/TimerTest.h
C
bsd-3-clause
2,011
<?php /** * models/SiteGlobal.php * Contains the SiteGlobal class * * @author Cory Gehr */ namespace EocCap; class SiteGlobal extends \Thinker\Framework\Model { // Properties public $name; public $value; /** * create() * Creates a new Site Global variable in the database * * @access public * @static * @param mixed[] $data Data to commit * @return string Name of the global */ public static function create($data) { global $_DB; $query = "INSERT INTO globals(name, value) VALUES(?, ?)"; if($_DB['eoc_cap_mgmt']->doQuery($query, $data)) { // Provide Name of variable return $data[0]; } return false; } /** * fetch() * Fetches a global's value from the database * * @access public * @static * @param string $name Name of the variable * @return string Global Value */ public static function fetch($name) { global $_DB; $query = "SELECT value FROM globals WHERE name = ? LIMIT 1"; $value = $_DB['eoc_cap_mgmt']->doQueryAns($query, array($name)); if($value !== null) { return $value; } else { trigger_error("Global '$name' does not exist in database."); } } /** * update() * Commits the updated object to the database * * @access public * @param string $name Variable Name * @param mixed $value New Value * @return True on Success, False on Failure */ public static function update($name, $value) { global $_DB; $query = "UPDATE globals SET value = ?, update_user = ? WHERE name = ? LIMIT 1"; return $_DB['eoc_cap_mgmt']->doQuery($query, array($value, $_SESSION['USER']->username, $name)); } }
corygehr/ECAP
eoccap/models/SiteGlobal.php
PHP
bsd-3-clause
1,687
package org.scalajs.testsuite.javalib.time.temporal import java.time.DateTimeException import java.time.temporal._ trait TemporalTest extends TemporalAccessorTest { val dateBasedUnits = ChronoUnit.values.filter(_.isDateBased) val timeBasedUnits = ChronoUnit.values.filter(_.isTimeBased) def testTemporal(actual: => Temporal)(expected: => Temporal): Unit = { try { val e = expected expectNoException(actual) expect(e == actual).toBeTruthy } catch { case _: UnsupportedTemporalTypeException => expectThrows[UnsupportedTemporalTypeException](actual) case _: DateTimeException => expectThrows[DateTimeException](actual) case _: ArithmeticException => expectThrows[ArithmeticException](actual) } } def testTemporalApi(samples: Temporal*): Unit = { testTemporalAccessorApi(samples:_*) it("should respond with false to `isSupported(null: TemporalUnit)`") { for (temporal <- samples) expect(temporal.isSupported(null: TemporalUnit)).toBeFalsy } it("should throw at `with` for unsupported fields") { val values = Seq(Long.MinValue, Int.MinValue.toLong, -1L, 0L, 1L, Int.MaxValue.toLong, Long.MaxValue) for { temporal <- samples field <- ChronoField.values if !temporal.isSupported(field) n <- values } { expectThrows[UnsupportedTemporalTypeException](temporal.`with`(field, n)) } } it("should throw at `plus` for unsupported units") { for { temporal <- samples unit <- ChronoUnit.values() if !temporal.isSupported(unit) n <- Seq(Long.MinValue, Int.MinValue.toLong, -1L, 0L, 1L, Int.MaxValue.toLong, Long.MaxValue) } { expectThrows[UnsupportedTemporalTypeException](temporal.plus(n, unit)) } } it("should respond to `minus`") { for { temporal <- samples unit <- ChronoUnit.values() if temporal.isSupported(unit) n <- Seq( Long.MinValue, Int.MinValue.toLong, -1000000000L, -86400L, -3600L, -366L, -365L, -60L, -24L, -7L, -1L, 0L, 1L, 7L, 24L, 60L, 365L, 366L, 3600L, 86400L, 1000000000L, Int.MaxValue.toLong, Long.MaxValue) } { testTemporal(temporal.minus(n, unit)) { if (n != Long.MinValue) temporal.plus(-n, unit) else temporal.plus(Long.MaxValue, unit).plus(1, unit) } } } it("should throw at `minus` for unsupported units") { for { temporal <- samples unit <- ChronoUnit.values() if !temporal.isSupported(unit) n <- Seq(Long.MinValue, Int.MinValue.toLong, -1L, 0L, 1L, Int.MaxValue.toLong, Long.MaxValue) } { expectThrows[UnsupportedTemporalTypeException](temporal.minus(n, unit)) } } it("should throw at `until` for unsupported units") { for { temporal1 <- samples temporal2 <- samples unit <- ChronoUnit.values() if !temporal1.isSupported(unit) } { expectThrows[UnsupportedTemporalTypeException]( temporal1.until(temporal2, unit)) } } } }
jasonchaffee/scala-js
test-suite/js/src/test/require-jdk8/org/scalajs/testsuite/javalib/time/temporal/TemporalTest.scala
Scala
bsd-3-clause
3,176
/** * Controller for url related to champions * @author hycariss * @module champion * @class Champion */ var Champion = require('../model/champion'), express = require('express') ; var app = express(); /** * Replace the url parameter :id to a champion */ app.param('id', function(req, res, next, id) { Champion.find(id).then(function(champion) { if (!champion) { res.status(404).send('Not Found'); } else { req.champion = champion; next(); } }, function(error) { res.status(500).send(error); }); }); /** * @api {get} /api/champion Get all the champions * @apiName GetChampions * @apiGroup Champion */ app.get('/', function(req, res) { Champion.findAll().then(function(champions) { res.json(champions); }); }); /** * @api {get} /api/champion/:id Get a champion by id * @apiName GetChampion * @apiGroup Champion * @apiParam {integer} id Id of the champion * @apiError {404} NotFound The id of the champion was not found. * */ app.get('/:id', function(req, res) { res.json(req.champion); }); /** * Return the controller configuration */ module.exports = { app: app, base: '/champion' };
Gollwu/LoLManager
app/controller/champion.controller.js
JavaScript
bsd-3-clause
1,225
var searchData= [ ['deprecated_20list',['Deprecated List',['../a00481.html',1,'']]] ];
malcolmreynolds/GTSAM
doc/html/search/pages_64.js
JavaScript
bsd-3-clause
89
![Monotable](https://github.com/imikimi/monotable/raw/gh-pages/images/monotable.png) ## What is it? Monotable aims to provide a reliable distributed key-value data store, intended primarily for storing large numbers of small files. Monotable is implemented in a combination of Ruby and C. ## Current status *Monotable is in "proof-of-concept" stage, in which we are translating our design on paper into a working prototype.* ## FAQ ### Why another data store? Given that there are plenty of good data stores, why undertake writing another one? Our primary goals are: * Store approximately a petabyte of data * Store billions of records * Store binary records (files) 10kB-10mB * Flexible administration, indexing, replication, and growth The ecosystem of existing data stores offered no clear winners. ### Why Ruby? Systems languages reign supreme for implementing a data store, so Ruby is an uncommon language choice. Here are the pros and cons for choosing ruby: * Pros * Ruby is a productive language. Ease of use translates to fewer bugs and quicker development. * A data store will ideally be disk or network IO bound, which narrows the performance disparity between systems languages and higher-level languages such as Ruby. * Ruby has excellent network daemon support in the form of [EventMachine](http://rubyeventmachine.com/). * Cons * The official ruby interpreter (MRI) has some notable performance limitations, including a non-generational garbage collector and a global interpreter lock (GIL), which prevents truly simultaneous execution. *How to overcome it*: There are alternative ruby interpreters which are not subject to these limitations, such as [JRuby](http://jruby.org/) and [Rubinius](http://rubini.us/). * The high level nature of ruby means it will be significantly slower for lower level operations. *How to overcome it*: For insurmountable CPU performance bottlenecks in Ruby, break out of ruby down to C, using [RubyInline](http://www.zenspider.com/ZSS/Products/RubyInline/) or external libraries with [FFI](http://wiki.github.com/ffi/ffi). ### Why is it called "Monotable"? It is a "table" in that it has a primary key sort, like many other databases. It is "mono" in that it only has *one* primary key sort. Multiple tables can be logically created by namespacing keys. To be clear, though it is a single table, it can span a large number of machines. ### What do you mean by "flexible"? From the client's perspective, a data store should appear to be "one giant disk". To best satisfy this requirement, a data store will need the following: * Adding a node to the cluster should just require starting a single daemon and pointing it to an existing cluster. * Removing a node should be as simple as turning it off. * Removing a node should not leave the cluster in a degenerate state. * A node should have a single daemon. * A cluster should have no single point of failure. * You can access any data in the cluster by accessing any node in the cluster. * No cluster restarts for configuration changes. ## Contributing Development is in the early stages. Please message us via Github if you'd like to help out.
Imikimi-LLC/monotable
README.md
Markdown
bsd-3-clause
3,180