repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
sladewinter/UVa-Online-Judge
Ch 7 Geometry/Shapes/uva-10005-PolygonInCircle.cpp
//UVa - 10005 - Packing polygons //Check if possible to fit polygon in circle with radius r #include <iostream> #include <cmath> #include <tuple> using namespace std; struct point { double x, y; }; using tpp = tuple<point, point>; //Checks if point p in inside circle with centre r bool inside(point p, point c, double r) { return hypot(p.x - c.x, p.y - c.y) > r ? false : true; } //Returns 2 centres given 2 points and radius tpp centres( point p1, point p2, double r ) { //Square of distance between p1 & p2 double d2{ (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) }; double det{ r * r / d2 - 0.25 }; //Not possible if( det < 0.0 ) throw -1; double h{ sqrt(det) }; point c1; c1.x = (p1.x + p2.x) * 0.5 + (p1.y - p2.y) * h; c1.y = (p1.y + p2.y) * 0.5 + (p2.x - p1.x) * h; point c2; c2.x = (p2.x + p1.x) * 0.5 + (p2.y - p1.y) * h; c2.y = (p2.y + p1.y) * 0.5 + (p1.x - p2.x) * h; return {c1, c2}; } int main() { point v[100]; //Polygon vertices double r; //Radius of circle int n; //No of vertices while( scanf( "%d", &n ), n ) { for( int i{0}; i < n; ++i ) scanf( "%lf %lf", &v[i].x, &v[i].y ); scanf( "%lf", &r ); bool pos{ n == 1 }; //Possible if 1 vertex //Try all combination of vertices for( int i{0}; i < n - 1 && !pos; ++i ) for( int j{i + 1}; j < n && !pos; ++j ) { point c1, c2; try { //Returns 2 centres given 2 points and radius tie(c1, c2) = centres( v[i], v[j], r ); } catch( int e ) //Error if not possible { continue; } //Try with 1 centre pos = true; for( int k{ 0 }; k < n && pos; ++k ) if( k != i && k != j ) pos = inside( v[k], c1, r ); if(pos) break; //if succeeds break //Else try with the other centre pos = true; for( int k{ 0 }; k < n && pos; ++k ) if( k != i && k != j ) pos = inside( v[k], c2, r ); } pos ? printf("The polygon can be packed in the circle.\n") : printf("There is no way of packing that polygon.\n"); } return 0; }
sambacha/0x-tracker-client
src/features/fills/components/trade-count-widget.js
<reponame>sambacha/0x-tracker-client import _ from 'lodash'; import PropTypes from 'prop-types'; import React from 'react'; import { summarizeNumber } from '../../../util'; import LoadingIndicator from '../../../components/loading-indicator'; import sharedPropTypes from '../../../prop-types'; import StatWidget from '../../../components/stat-widget'; const loadingIndicator = <LoadingIndicator size="small" type="cylon" />; const createTooltip = (period) => { if (period === 'all') { return 'Total number of trades since 0x was launched. Only includes activity from known relayers.'; } return `Total number of trades in the last ${period}. Only includes activity from known relayers.`; }; const TradeCountWidget = ({ period, tradeCount, ...otherProps }) => ( <StatWidget period={period} title="Trades" tooltip={createTooltip(period)} {...otherProps} > {_.isNumber(tradeCount) ? summarizeNumber(tradeCount) : loadingIndicator} </StatWidget> ); TradeCountWidget.propTypes = { period: sharedPropTypes.timePeriod, tradeCount: PropTypes.number, }; TradeCountWidget.defaultProps = { period: undefined, tradeCount: undefined, }; export default TradeCountWidget;
refnum/Nano
Library/Source/Nano/System/NVersion.h
<filename>Library/Source/Nano/System/NVersion.h /* NAME: NVersion.h DESCRIPTION: Version number. COPYRIGHT: Copyright (c) 2006-2021, refNum Software All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 NSY_H #define NSY_H //============================================================================= // Includes //----------------------------------------------------------------------------- // Nano #include "NMixinComparable.h" #include "NString.h" #include "NanoMacros.h" #include "NanoTypes.h" // System #include <array> //============================================================================= // Types //----------------------------------------------------------------------------- // Forward declaration enum class NVersionPart; // Tags using NVersionTag = std::array<utf8_t, 12>; //============================================================================= // Class Declaration //----------------------------------------------------------------------------- class NN_EMPTY_BASE NVersion final : public NMixinComparable<NVersion> { public: NVersion(const NString& theVersion); NVersion(uint8_t theProduct, uint8_t verMajor, uint8_t verMinor, uint8_t verPatch, const NString& theTag); public: constexpr NVersion(uint8_t theProduct, uint8_t verMajor, uint8_t verMinor = 0, uint8_t verPatch = 0); constexpr NVersion(); // Is the version valid? constexpr bool IsValid() const; // Clear the version void Clear(); // Get/set the product // // The product value is meta-data used to group versions. constexpr uint8_t GetProduct() const; constexpr void SetProduct(uint8_t theValue); // Get/set the version components // // A version is composed of three integers: // // major.minor.patch constexpr uint8_t GetMajor() const; constexpr uint8_t GetMinor() const; constexpr uint8_t GetPatch() const; constexpr void SetMajor(uint8_t theValue); constexpr void SetMinor(uint8_t theValue); constexpr void SetPatch(uint8_t theValue); // Get/set the tag // // The tag is an arbitrary suffix used to identify pre-releases: // // "a1" "b3" "RC5" NString GetTag() const; void SetTag( const NString& theTag); // Get / set the version as a string // // A version string is structured as "major.minor.patch<tag>": // // "1.0" "1.0.1" "1.0.1b2" // // The product is never included. // // The major and minor components are always included, and the // patch component is included if it is not zero. // // The tag component is included if it is not empty. NString GetString() const; void SetString( const NString& theVersion); // Compare two version strings // // Strings may contain sequences of integers, strings, and periods: // // "1.0a1" < "1.0a2" < "1.0b1" < "1.0" < "1.0.1" // // String components are compared alphanumerically. static NComparison Compare(const NString& versionA, const NString& versionB); public: // NMixinComparable bool CompareEqual(const NVersion& theVersion) const; NComparison CompareOrder(const NVersion& theVersion) const; private: static NVectorString GetParts( const NString& theVersion); static NVersionPart GetPartType(const NString& thePart); private: uint8_t mProduct; uint8_t mMajor; uint8_t mMinor; uint8_t mPatch; NVersionTag mTag; }; //============================================================================= // Includes //----------------------------------------------------------------------------- #include "NVersion.inl" //============================================================================= // Constants //----------------------------------------------------------------------------- // OS versions // // Versions to represent the major.minor.patch release of an OS. // // These constants may be serialised - their values are fixed. inline constexpr uint8_t kNOSAndroid = 0x01; inline constexpr uint8_t kNOSiOS = 0x02; inline constexpr uint8_t kNOSLinux = 0x03; inline constexpr uint8_t kNOSmacOS = 0x04; inline constexpr uint8_t kNOStvOS = 0x05; inline constexpr uint8_t kNOSWindows = 0x06; inline constexpr NVersion kNOSAndroid_8 = NVersion(kNOSAndroid, 8, 0, 0); inline constexpr NVersion kNOSAndroid_9 = NVersion(kNOSAndroid, 9); inline constexpr NVersion kNOSAndroid_10 = NVersion(kNOSAndroid, 10); inline constexpr NVersion kNOSAndroid_11 = NVersion(kNOSAndroid, 11); inline constexpr NVersion kNOSLinux_4 = NVersion(kNOSLinux, 4); inline constexpr NVersion kNOSLinux_5 = NVersion(kNOSLinux, 5); inline constexpr NVersion kNOSiOS_13 = NVersion(kNOSiOS, 13); inline constexpr NVersion kNOSiOS_14 = NVersion(kNOSiOS, 14); inline constexpr NVersion kNOSiOS_14_0_1 = NVersion(kNOSiOS, 14, 0, 1); inline constexpr NVersion kNOSiOS_14_1 = NVersion(kNOSiOS, 14, 1); inline constexpr NVersion kNOSiOS_14_2 = NVersion(kNOSiOS, 14, 2); inline constexpr NVersion kNOSiOS_14_2_1 = NVersion(kNOSiOS, 14, 2, 1); inline constexpr NVersion kNOSiOS_14_3 = NVersion(kNOSiOS, 14, 3); inline constexpr NVersion kNOSiOS_14_4 = NVersion(kNOSiOS, 14, 4); inline constexpr NVersion kNOSmacOS_10_14 = NVersion(kNOSmacOS, 10, 14); inline constexpr NVersion kNOSmacOS_10_15 = NVersion(kNOSmacOS, 10, 15); inline constexpr NVersion kNOSmacOS_11 = NVersion(kNOSmacOS, 11); inline constexpr NVersion kNOSmacOS_11_0_1 = NVersion(kNOSmacOS, 11, 0, 1); inline constexpr NVersion kNOSmacOS_11_1 = NVersion(kNOSmacOS, 11, 1); inline constexpr NVersion kNOSmacOS_11_2 = NVersion(kNOSmacOS, 11, 2); inline constexpr NVersion kNOStvOS_13 = NVersion(kNOStvOS, 13); inline constexpr NVersion kNOStvOS_14 = NVersion(kNOStvOS, 14); inline constexpr NVersion kNOStvOS_14_0_1 = NVersion(kNOStvOS, 14, 0, 1); inline constexpr NVersion kNOStvOS_14_0_2 = NVersion(kNOStvOS, 14, 0, 2); inline constexpr NVersion kNOStvOS_14_2 = NVersion(kNOStvOS, 14, 2); inline constexpr NVersion kNOStvOS_14_3 = NVersion(kNOStvOS, 14, 3); inline constexpr NVersion kNOStvOS_14_4 = NVersion(kNOStvOS, 14, 4); inline constexpr NVersion kNOSWindows_XP = NVersion(kNOSWindows, 5); inline constexpr NVersion kNOSWindows_Vista = NVersion(kNOSWindows, 6); inline constexpr NVersion kNOSWindows_7 = NVersion(kNOSWindows, 7); inline constexpr NVersion kNOSWindows_8 = NVersion(kNOSWindows, 8); inline constexpr NVersion kNOSWindows_10 = NVersion(kNOSWindows, 9); #endif // NSYSTEM_H
transposit/graalpython
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/call/special/LookupAndCallBinaryNode.java
<gh_stars>1-10 /* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must 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. */ package com.oracle.graal.python.nodes.call.special; import java.util.function.Supplier; import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.PNotImplemented; import com.oracle.graal.python.builtins.objects.function.PBuiltinFunction; import com.oracle.graal.python.builtins.objects.type.LazyPythonClass; import com.oracle.graal.python.builtins.objects.type.TypeNodes; import com.oracle.graal.python.nodes.PNodeWithContext; import com.oracle.graal.python.nodes.attributes.LookupAttributeInMRONode; import com.oracle.graal.python.nodes.attributes.LookupInheritedAttributeNode; import com.oracle.graal.python.nodes.classes.IsSubtypeNode; import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode; import com.oracle.graal.python.nodes.object.GetClassNode; import com.oracle.graal.python.nodes.object.GetLazyClassNode; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.UnexpectedResultException; import com.oracle.truffle.api.profiles.ConditionProfile; public abstract class LookupAndCallBinaryNode extends Node { public abstract static class NotImplementedHandler extends PNodeWithContext { public abstract Object execute(Object arg, Object arg2); } protected final String name; protected final String rname; protected final Supplier<NotImplementedHandler> handlerFactory; @Child private CallBinaryMethodNode dispatchNode; @Child private CallBinaryMethodNode reverseDispatchNode; @Child private NotImplementedHandler handler; public abstract boolean executeBool(VirtualFrame frame, boolean arg, boolean arg2) throws UnexpectedResultException; public abstract int executeInt(VirtualFrame frame, int arg, int arg2) throws UnexpectedResultException; public abstract int executeInt(VirtualFrame frame, Object arg, Object arg2) throws UnexpectedResultException; public abstract long executeLong(VirtualFrame frame, int arg, int arg2) throws UnexpectedResultException; public abstract long executeLong(VirtualFrame frame, long arg, long arg2) throws UnexpectedResultException; public abstract long executeLong(VirtualFrame frame, Object arg, Object arg2) throws UnexpectedResultException; public abstract double executeDouble(VirtualFrame frame, double arg, double arg2) throws UnexpectedResultException; public abstract boolean executeBool(VirtualFrame frame, int arg, int arg2) throws UnexpectedResultException; public abstract boolean executeBool(VirtualFrame frame, long arg, long arg2) throws UnexpectedResultException; public abstract boolean executeBool(VirtualFrame frame, double arg, double arg2) throws UnexpectedResultException; public abstract boolean executeBool(VirtualFrame frame, Object arg, Object arg2) throws UnexpectedResultException; public abstract Object executeObject(VirtualFrame frame, Object arg, Object arg2); LookupAndCallBinaryNode(String name, String rname, Supplier<NotImplementedHandler> handlerFactory) { this.name = name; this.rname = rname; this.handlerFactory = handlerFactory; } public static LookupAndCallBinaryNode create(String name) { return LookupAndCallBinaryNodeGen.create(name, null, null); } public static LookupAndCallBinaryNode createReversible(String name, Supplier<NotImplementedHandler> handlerFactory) { assert name.startsWith("__"); return LookupAndCallBinaryNodeGen.create(name, name.replaceFirst("__", "__r"), handlerFactory); } public static LookupAndCallBinaryNode create(String name, String rname) { return LookupAndCallBinaryNodeGen.create(name, rname, null); } public static LookupAndCallBinaryNode create(String name, String rname, Supplier<NotImplementedHandler> handlerFactory) { return LookupAndCallBinaryNodeGen.create(name, rname, handlerFactory); } protected Object getMethod(Object receiver, String methodName) { return LookupAttributeInMRONode.Dynamic.getUncached().execute(GetClassNode.getUncached().execute(receiver), methodName); } protected boolean isReversible() { return rname != null; } private CallBinaryMethodNode ensureDispatch() { // this also serves as a branch profile if (dispatchNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); dispatchNode = insert(CallBinaryMethodNode.create()); } return dispatchNode; } private CallBinaryMethodNode ensureReverseDispatch() { // this also serves as a branch profile if (reverseDispatchNode == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); reverseDispatchNode = insert(CallBinaryMethodNode.create()); } return reverseDispatchNode; } private UnexpectedResultException handleLeftURE(VirtualFrame frame, Object left, Object right, UnexpectedResultException e) throws UnexpectedResultException { if (isReversible() && e.getResult() == PNotImplemented.NOT_IMPLEMENTED) { throw new UnexpectedResultException(ensureReverseDispatch().executeObject(frame, getMethod(right, rname), right, left)); } else { throw e; } } protected PythonBinaryBuiltinNode getBuiltin(Object receiver) { assert receiver instanceof Boolean || receiver instanceof Integer || receiver instanceof Long || receiver instanceof Double || receiver instanceof String; Object attribute = LookupAttributeInMRONode.Dynamic.getUncached().execute(GetClassNode.getUncached().execute(receiver), name); if (attribute instanceof PBuiltinFunction) { PBuiltinFunction builtinFunction = (PBuiltinFunction) attribute; if (PythonBinaryBuiltinNode.class.isAssignableFrom(builtinFunction.getBuiltinNodeFactory().getNodeClass())) { return (PythonBinaryBuiltinNode) builtinFunction.getBuiltinNodeFactory().createNode(); } } return null; } // bool, bool @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) boolean callBoolean(VirtualFrame frame, boolean left, boolean right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeBool(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) int callInt(VirtualFrame frame, boolean left, boolean right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeInt(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } // int, int @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) int callInt(VirtualFrame frame, int left, int right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeInt(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) boolean callBoolean(VirtualFrame frame, int left, int right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeBool(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) long callLong(VirtualFrame frame, int left, int right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeLong(frame, left, right); // implicit conversion to long } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } // long, long @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) long callLong(VirtualFrame frame, long left, long right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeLong(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) boolean callBoolean(VirtualFrame frame, long left, long right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeBool(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } // double, double @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) double callDouble(VirtualFrame frame, double left, double right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeDouble(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } @Specialization(guards = "function != null", rewriteOn = UnexpectedResultException.class) boolean callBoolean(VirtualFrame frame, double left, double right, @Cached("getBuiltin(left)") PythonBinaryBuiltinNode function) throws UnexpectedResultException { try { return function.executeBool(frame, left, right); } catch (UnexpectedResultException e) { throw handleLeftURE(frame, left, right, e); } } // Object, Object @Specialization(guards = "!isReversible()") Object callObject(VirtualFrame frame, Object left, Object right, @Cached("create(name)") LookupInheritedAttributeNode getattr) { Object leftCallable = getattr.execute(left); if (leftCallable == PNone.NO_VALUE) { if (handlerFactory != null) { return runErrorHandler(left, right); } else { return PNotImplemented.NOT_IMPLEMENTED; } } return ensureDispatch().executeObject(frame, leftCallable, left, right); } @Specialization(guards = "isReversible()") Object callObject(VirtualFrame frame, Object left, Object right, @Cached("create(name)") LookupAttributeInMRONode getattr, @Cached("create(rname)") LookupAttributeInMRONode getattrR, @Cached("create()") GetLazyClassNode getClass, @Cached("create()") GetLazyClassNode getClassR, @Cached("create()") TypeNodes.IsSameTypeNode isSameTypeNode, @Cached("create()") IsSubtypeNode isSubtype, @Cached("createBinaryProfile()") ConditionProfile notImplementedBranch) { Object result = PNotImplemented.NOT_IMPLEMENTED; LazyPythonClass leftClass = getClass.execute(left); Object leftCallable = getattr.execute(leftClass); LazyPythonClass rightClass = getClassR.execute(right); Object rightCallable = getattrR.execute(rightClass); if (leftCallable == rightCallable) { rightCallable = PNone.NO_VALUE; } if (leftCallable != PNone.NO_VALUE) { if (rightCallable != PNone.NO_VALUE && !isSameTypeNode.execute(leftClass, rightClass) && isSubtype.execute(frame, rightClass, leftClass)) { result = ensureReverseDispatch().executeObject(frame, rightCallable, right, left); if (result != PNotImplemented.NOT_IMPLEMENTED) { return result; } rightCallable = PNone.NO_VALUE; } result = ensureDispatch().executeObject(frame, leftCallable, left, right); if (result != PNotImplemented.NOT_IMPLEMENTED) { return result; } } if (notImplementedBranch.profile(rightCallable != PNone.NO_VALUE)) { result = ensureReverseDispatch().executeObject(frame, rightCallable, right, left); } if (handlerFactory != null && result == PNotImplemented.NOT_IMPLEMENTED) { return runErrorHandler(left, right); } return result; } private Object runErrorHandler(Object left, Object right) { if (handler == null) { CompilerDirectives.transferToInterpreterAndInvalidate(); handler = insert(handlerFactory.get()); } return handler.execute(left, right); } public String getName() { return name; } public String getRname() { return rname; } }
PradyumnaNagendra/sunbird-functional-tests
sunbird_portal/src/test/java/org/sunbird/testscripts/FlagReviewer_TC01.java
package org.sunbird.testscripts; import org.testng.annotations.Test; import org.sunbird.pageobjects.FlagReviewerPageObj; import org.sunbird.pageobjects.SignUpObj; import org.sunbird.startup.BaseTest; import org.testng.annotations.Test; public class FlagReviewer_TC01 extends BaseTest { @Test(priority=1) public void flagReviewerTestCase01() throws Exception { //Login as creator SignUpObj creatorObj = new SignUpObj(); creatorObj.userLogin(FLAGREVIEWER); //Search for a course and content flag them FlagReviewerPageObj flagReviewer = new FlagReviewerPageObj(); flagReviewer.flagged_UpforReview(); } }
jkalloor3/bqskit
bqskit/ir/point.py
<filename>bqskit/ir/point.py """This module implements the CircuitPoint class.""" from __future__ import annotations import logging from typing import Any from typing import Tuple from typing import Union from typing_extensions import TypeGuard from bqskit.utils.typing import is_integer _logger = logging.getLogger(__name__) class CircuitPoint(Tuple[int, int]): """ A cycle and qudit index pair used to index a circuit. This is a subclass of a tuple, and therefore can be used where a tuple of two ints can be used. """ def __new__( cls, cycle_or_tuple: int | tuple[int, int], qudit: int | None = None, ) -> CircuitPoint: """ Construct a point. Args: cycle_or_tuple (int | tuple[int, int]): Either a cycle index given as an integer, or a tuple of a cycle index and qudit index. If an integer is given, then you will need to also specify the qudit index as the next argument. qudit (int | None): If `cycle_or_tuple` is an integer cycle index, then you will need to specify the qudit index here. Otherwise, leave this as None. Returns: CircuitPoint: The new point object. """ if qudit is not None and not is_integer(qudit): raise TypeError( f'Expected int or None for qudit, got {type(qudit)}.', ) if isinstance(cycle_or_tuple, tuple): if not CircuitPoint.is_point(cycle_or_tuple): raise TypeError('Expected two integer arguments.') if qudit is not None: raise ValueError('Unable to handle extra argument.') cycle = cycle_or_tuple[0] qudit = cycle_or_tuple[1] elif is_integer(cycle_or_tuple) and is_integer(qudit): cycle = cycle_or_tuple elif is_integer(cycle_or_tuple) and qudit is None: raise ValueError('Expected two integer arguments.') else: raise TypeError('Expected two integer arguments.') return super().__new__(cls, (cycle, qudit)) # type: ignore @property def cycle(self) -> int: """The point's cycle index.""" return self[0] @property def qudit(self) -> int: """The point's qudit index.""" return self[1] @staticmethod def is_point(point: Any) -> TypeGuard[CircuitPointLike]: """Return true if point is a CircuitPointLike.""" if isinstance(point, CircuitPoint): return True if not isinstance(point, tuple): _logger.debug('Point is not a tuple.') return False if len(point) != 2: _logger.debug( 'Expected point to contain two values, got %d.' % len(point), ) return False if not is_integer(point[0]): _logger.debug( 'Expected integer values in point, got %s.' % type(point[0]), ) return False if not is_integer(point[1]): _logger.debug( 'Expected integer values in point, got %s.' % type(point[1]), ) return False return True CircuitPointLike = Union[Tuple[int, int], CircuitPoint]
DVSR1966/par4all
packages/PIPS/validation/Scilab/Scilab2C-2/src/c/shilberta.c
<filename>packages/PIPS/validation/Scilab/Scilab2C-2/src/c/shilberta.c /* * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2008 - INRIA - <NAME> * * This file must be used under the terms of the CeCILL. * This source file is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at * http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt * */ #include "hilbert.h" #include "fft.h" #include "ifft.h" #include "multiplication.h" void shilberta (float* in, int rows, int cols, floatComplex *out){ int i; int size=rows*cols; for (i=0;i<rows*cols;i++) out[i]=FloatComplex(in[i],0); cfftma(out, rows, cols, out); for (i=0;i<size;i++){ if ((i>0)&&(i<(size+1)/2)) out[i] = cmuls(out[i],FloatComplex(2,0)); if (i>size/2) out[i] = cmuls(out[i],FloatComplex(0,0)); } cifftma(out, rows, cols,out); }
divebell/amazon-redshift-jdbc-driver
src/main/java/com/amazon/redshift/jdbc/RedshiftSavepoint.java
<filename>src/main/java/com/amazon/redshift/jdbc/RedshiftSavepoint.java /* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package com.amazon.redshift.jdbc; import com.amazon.redshift.core.Utils; import com.amazon.redshift.util.GT; import com.amazon.redshift.util.RedshiftException; import com.amazon.redshift.util.RedshiftState; import java.sql.SQLException; import java.sql.Savepoint; public class RedshiftSavepoint implements Savepoint { private boolean isValid; private final boolean isNamed; private int id; private String name; public RedshiftSavepoint(int id) { this.isValid = true; this.isNamed = false; this.id = id; } public RedshiftSavepoint(String name) { this.isValid = true; this.isNamed = true; this.name = name; } @Override public int getSavepointId() throws SQLException { if (!isValid) { throw new RedshiftException(GT.tr("Cannot reference a savepoint after it has been released."), RedshiftState.INVALID_SAVEPOINT_SPECIFICATION); } if (isNamed) { throw new RedshiftException(GT.tr("Cannot retrieve the id of a named savepoint."), RedshiftState.WRONG_OBJECT_TYPE); } return id; } @Override public String getSavepointName() throws SQLException { if (!isValid) { throw new RedshiftException(GT.tr("Cannot reference a savepoint after it has been released."), RedshiftState.INVALID_SAVEPOINT_SPECIFICATION); } if (!isNamed) { throw new RedshiftException(GT.tr("Cannot retrieve the name of an unnamed savepoint."), RedshiftState.WRONG_OBJECT_TYPE); } return name; } public void invalidate() { isValid = false; } public String getRSName() throws SQLException { if (!isValid) { throw new RedshiftException(GT.tr("Cannot reference a savepoint after it has been released."), RedshiftState.INVALID_SAVEPOINT_SPECIFICATION); } if (isNamed) { // We need to quote and escape the name in case it // contains spaces/quotes/etc. // return Utils.escapeIdentifier(null, name).toString(); } return "JDBC_SAVEPOINT_" + id; } }
karolba/fakturama
app/services/current-session.js
import Service from '@ember/service'; import { computed } from '@ember/object'; import { resolve, Promise as EmberPromise } from 'rsvp'; import FirebaseAuth from 'fakturama/lib/firebase_auth'; import User from 'fakturama/models/user'; // This service needs to be injected via app initializer under 'session' name. // This allow us to stub ad-hoc injection in in the acceptance tests. export default Service.extend({ init() { this._super(...arguments); const authClass = this.getWithDefault('authClass', FirebaseAuth); this.set('_auth', authClass.create()); }, setup() { if (this.getWithDefault('_setup', false)) { return resolve(); } return new EmberPromise(resolve => { const auth = this.get('_auth'); auth.onAuthStateChanged(user => { if (user) { return this._setUser(user).then(resolve); } else { return this.create().then(resolve); } }); this.set('_setup', true); }); }, currentUser: computed('userData.{user,token}', function() { const { user, token } = this.get('userData'); return User.create({ uid: user.uid, authToken: token, email: user.email, displayName: user.displayName, isAnonymous: user.isAnonymous }); }), create(method = 'anonymous') { const auth = this.get('_auth'); return new EmberPromise((resolve, reject) => { switch (method) { case 'anonymous': auth.signInAnonymously().then(resolve, reject); break; case 'google': auth.signInWithGoogle().then(resolve, reject); break; default: reject(`Session#create with ${method} is not supported`); } }); }, remove() { const auth = this.get('_auth'); return auth.signOut().then(() => this.create()); }, _setUser(user) { return user.getIdToken().then(token => { this.set('userData', { user, token }); }); } });
WarpWorks/warpjs-ipt
client/utils/class-by-key.js
<reponame>WarpWorks/warpjs-ipt const isMM = require('./is-mm'); module.exports = (key) => isMM(key) ? 'mm' : (key === 'ai' ? 'ai' : 'ipt');
hidlestone/spring-boot-aggregator
spring-boot-template-beetl/src/main/java/com/payn/template/beetl/model/User.java
<filename>spring-boot-template-beetl/src/main/java/com/payn/template/beetl/model/User.java package com.payn.template.beetl.model; import lombok.Data; /** * @author payn * @date 2020/9/16 8:36 */ @Data public class User { private String name; private String password; }
bach5000/XRS
XrsPalm/src/include/file_msg.h
<reponame>bach5000/XRS<filename>XrsPalm/src/include/file_msg.h<gh_stars>0 /boot/home/Desktop/XrsPalm/src/defs/file_msg.h
CU-NESS/pylinex
pylinex/expander/RepeatExpander.py
""" File: pylinex/expander/RepeatExpander.py Author: <NAME> Date: 3 Sep 2017 Description: File containing a class representing an Expander which expands vectors by repeating them multiple times. """ import numpy as np from ..util import int_types from .Expander import Expander class RepeatExpander(Expander): """ Class representing an Expander which expands vectors by repeating them multiple times. """ def __init__(self, nrepeats): """ Initializes a new RepeatExpander with the given number of repeats nrepeats: positive integer number of times input is repeated """ self.nrepeats = nrepeats @property def nrepeats(self): """ Property storing the positive integer number of times this Expander should repeat its input. """ if not hasattr(self, '_nrepeats'): raise AttributeError("nrepeats was referenced before it was set.") return self._nrepeats @nrepeats.setter def nrepeats(self, value): """ Setter for the number of times this Expander should repeat its input. value: positive integer number of times this Expander should repeat its input """ if type(value) in int_types: self._nrepeats = value else: raise TypeError("nrepeats was set to a non-integer.") def make_expansion_matrix(self, original_space_size): """ Computes the matrix of this expander. original_space_size: size of unexpanded space returns: expansion matrix of this expander """ return np.concatenate(\ [np.identity(original_space_size)] * self.nrepeats, axis=0) def copy(self): """ Finds and returns a deep copy of this expander. returns: copied RepeatExpander """ return RepeatExpander(self.nrepeats) def overlap(self, vectors, error=None): """ Computes Psi^T C^{-1} y for one or more vectors y and for a diagonal C defined by the given error. vectors: either a 1D array of length expanded_space_size or a 2D array of shape (nvectors, expanded_space_size) error: the standard deviations of the independent noise defining the dot product returns: if vectors is 1D, result is a 1D array of length original_space_size else, result is a 2D array of shape (nvectors, original_space_size) """ onedim = (vectors.ndim == 1) if onedim: vectors = vectors[np.newaxis,:] if type(error) is type(None): weighted_vectors = vectors else: weighted_vectors = vectors / (error ** 2)[np.newaxis,:] expanded_space_size = vectors.shape[-1] original_space_size = self.original_space_size(expanded_space_size) result = np.sum(np.reshape(weighted_vectors,\ (len(weighted_vectors), self.nrepeats, -1)), axis=1) if onedim: return result[0] else: return result def apply(self, vector): """ Expands vector from smaller original space to larger expanded space. vector: 1D vector from original space, must be numpy.ndarray so as not to waste time casting it here returns: 1D vector from expanded space """ return np.tile(vector, ((1,) * (vector.ndim - 1)) + (self.nrepeats,)) def contracted_covariance(self, error): """ Finds the covariance matrix associated with contracted noise. error: 1D vector from expanded space returns: 2D array of shape (original_space_size, original_space_size) """ return np.diag(self.contract_error(error) ** 2) def contract_error(self, error): """ Contracts error from full expanded space to smaller original space. error: 1D vector from expanded space returns: 1D vector from original space """ error_length = len(error) reshaped_error = np.reshape(error, (self.nrepeats, -1)) return 1 / np.sqrt(np.sum(np.power(reshaped_error, -2), axis=0)) def invert(self, data, error): """ (Pseudo-)Inverts this expander in order to infer an original-space curve from the given expanded-space data and error. data: data vector from which to imply an original space cause error: Gaussian noise level in data returns: most likely original-space curve to cause given data """ new_shape = (nrepeats, -1) reshaped_data = np.reshape(data, new_shape) reshaped_error = np.reshape(error, new_shape) squared_final_error = 1 / np.sum(np.power(reshaped_error, -2), axis=0) square_weighted_final_data =\ np.sum(reshaped_data / np.power(reshaped_error, 2), axis=0) return squared_final_error * square_weighted_final_data def is_compatible(self, original_space_size, expanded_space_size): """ Checks whether this Expander is compatible with the given sizes of the original expanded spaces. original_space_size: size of (typically smaller) original space expanded_space_size: size of (typically larger) expanded space returns: True iff the given sizes are compatible with this Expander """ return ((original_space_size * self.nrepeats) == expanded_space_size) def original_space_size(self, expanded_space_size): """ Finds the input space size from the output space size. expanded_space_size: positive integer compatible with this Expander returns: input space size """ if (expanded_space_size % self.nrepeats) == 0: return (expanded_space_size // self.nrepeats) else: raise ValueError("Given expanded_space_size was not compatible " +\ "as it was not a factor of the number of repeats of this " +\ "expander.") def expanded_space_size(self, original_space_size): """ Finds the output space size from the input space size. original_space_size: positive integer compatible with this Expander returns: output space size """ return original_space_size * self.nrepeats def channels_affected(self, original_space_size): """ Finds the indices of the data channels affected by data of the given size given to this Expander object. original_space_size: positive integer to assume as input size returns: 1D numpy.ndarray of indices of data channels possibly affected by data expanded by this Expander object """ return np.arange(self.expanded_space_size(original_space_size)) def fill_hdf5_group(self, group): """ Saves data about this in the given hdf5 file group. group: hdf5 file group to which to write """ group.attrs['class'] = 'RepeatExpander' group.attrs['nrepeats'] = self.nrepeats def __eq__(self, other): """ Checks for equality between this Expander and other. other: object with which to check for equality returns: True if this object and other are identical, False otherwise """ if isinstance(other, RepeatExpander): return (self.nrepeats == other.nrepeats) else: return False
Punzo/SlicerAstro
AstroVolume/qSlicerAstroVolumeModule.h
<filename>AstroVolume/qSlicerAstroVolumeModule.h /*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by <NAME>, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ #ifndef __qSlicerAstroVolumeModule_h #define __qSlicerAstroVolumeModule_h // CTK includes #include <ctkVTKObject.h> // SlicerQt includes #include "qSlicerLoadableModule.h" #include "qSlicerAstroVolumeModuleExport.h" class qSlicerAbstractModuleWidget; class qSlicerAstroVolumeModulePrivate; class vtkMRMLSliceLogic; class vtkObject; /// \ingroup SlicerAstro_QtModules_AstroVolume class Q_SLICERASTRO_QTMODULES_ASTROVOLUME_EXPORT qSlicerAstroVolumeModule : public qSlicerLoadableModule { Q_OBJECT QVTK_OBJECT #ifdef Slicer_HAVE_QT5 Q_PLUGIN_METADATA(IID "org.slicer.modules.loadable.qSlicerLoadableModule/1.0"); #endif Q_INTERFACES(qSlicerLoadableModule); public: typedef qSlicerLoadableModule Superclass; qSlicerAstroVolumeModule(QObject *parent=0); virtual ~qSlicerAstroVolumeModule(); qSlicerGetTitleMacro(QTMODULE_TITLE); /// Help to use the module virtual QString helpText()const; /// Return acknowledgments virtual QString acknowledgementText()const; /// Return the authors of the module virtual QStringList contributors()const; /// Return module dependencies virtual QStringList dependencies()const; /// Return a custom icon for the module virtual QIcon icon()const; /// Return the categories for the module virtual QStringList categories()const; /// Define associated node types virtual QStringList associatedNodeTypes()const; protected: /// Initialize the module. Register the AstroVolume reader/writer virtual void setup(); /// Create and return the widget representation associated to this module virtual qSlicerAbstractModuleRepresentation* createWidgetRepresentation(); /// Create and return the logic associated to this module virtual vtkMRMLAbstractLogic* createLogic(); QScopedPointer<qSlicerAstroVolumeModulePrivate> d_ptr; private: Q_DECLARE_PRIVATE(qSlicerAstroVolumeModule); Q_DISABLE_COPY(qSlicerAstroVolumeModule); }; #endif
TheLogicMaster/Tower-Defense-Galaxy
core/src/com/logicmaster63/tdgalaxy/map/region/RectangleRegion.java
package com.logicmaster63.tdgalaxy.map.region; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.collision.btBoxShape; import com.badlogic.gdx.physics.bullet.collision.btCollisionObject; public class RectangleRegion extends Region { private float width, height, depth; public RectangleRegion(Vector3 pos, float width, float height, float depth) { super(pos); this.height = height; this.width = width; this.depth = depth; } public RectangleRegion(float x, float y, float z, float width, float height, float depth) { this(new Vector3(x, y, z), width, height, depth); } @Override public btCollisionObject createCollisionObject() { btCollisionObject collisionObject = new btCollisionObject(); collisionObject.setCollisionShape(new btBoxShape(new Vector3(width, height, depth))); collisionObject.setWorldTransform(new Matrix4().setTranslation(pos)); return collisionObject; } @Override public boolean test(float x, float y, float z) { return x > pos.x - width / 2 && x < pos.x + width / 2 && y > pos.y - height / 2 && y < pos.y + height / 2 && z > pos.z - depth / 2 && z < pos.z + depth / 2; } }
WanpengQian/ConcurrencyFreaks
Java/com/concurrencyfreaks/queues/KoganPetrankQueue.java
package com.concurrencyfreaks.queues; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; /** * <h1> Kogan-Petrank Queue </h1> * * Based on the Wait-Free queue by <NAME> and <NAME> * https://offblast.org/stuff/books/lockfreequeues_ppopp11.pdf * http://www.cs.technion.ac.il/~erez/Papers/wfquque-ppopp.pdf * * This version has self-linking which we added ourselves * * enqueue algorithm: Kogan-Petrank, based on the consensus of Lamport's bakery * dequeue algorithm: Kogan-Petrank, based on the consensus of Lamport's bakery * Consistency: Linearizable * enqueue() progress: wait-free bounded O(N_threads) * dequeue() progress: wait-free bounded O(N_threads) * * @author <NAME> * @author <NAME> */ public class KoganPetrankQueue<E> { private static class Node<E> { E value; volatile Node<E> next; int enqTid; AtomicInteger deqTid; public Node(E val, int etid) { value = val; next = null; enqTid = etid; deqTid = new AtomicInteger(-1); } public boolean casNext(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long nextOffset; static { try { Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); UNSAFE = (sun.misc.Unsafe) f.get(null); Class<?> k = Node.class; nextOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("next")); } catch (Exception e) { throw new Error(e); } } } private static class OpDesc<E> { final long phase; final boolean pending; final boolean enqueue; final Node<E> node; public OpDesc (long ph, boolean pend, boolean enq, Node<E> n) { phase = ph; pending = pend; enqueue = enq; node = n; } } private static final int NUM_THREADS = 128; // Member variables volatile Node<E> head; volatile Node<E> tail; final AtomicReferenceArray<OpDesc<E>> state; public KoganPetrankQueue() { final Node<E> sentinel = new Node<E>(null, -1); head = sentinel; tail = sentinel; state = new AtomicReferenceArray<OpDesc<E>>(NUM_THREADS); for (int i = 0; i < state.length(); i++) { state.set(i, new OpDesc<E>(-1, false, true, null)); } } private void help(long phase) { for (int i = 0; i < state.length(); i++) { OpDesc<E> desc = state.get(i); if (desc.pending && desc.phase <= phase) { if (desc.enqueue) { help_enq(i, phase); } else { help_deq(i, phase); } } } } private long maxPhase() { long maxPhase = -1; for (int i = 0; i < state.length(); i++) { long phase = state.get(i).phase; if (phase > maxPhase) { maxPhase = phase; } } return maxPhase; } private boolean isStillPending(int tid, long ph) { return state.get(tid).pending && state.get(tid).phase <= ph; } public void enq(E value) { // We better have consecutive thread ids, otherwise this will blow up // TODO: replace this mechanism with something more flexible final int TID = (int)(Thread.currentThread().getId() % NUM_THREADS); long phase = maxPhase() + 1; state.set(TID, new OpDesc<E>(phase, true, true, new Node<E>(value, TID))); help(phase); help_finish_enq(); } private void help_enq(int tid, long phase) { while (isStillPending(tid, phase)) { Node<E> last = tail; Node<E> next = last.next; if (last == tail) { // If it's tail it can't be self-linked if (next == null) { if (isStillPending(tid, phase)) { if (last.casNext(next, state.get(tid).node)) { help_finish_enq(); return; } } } else { help_finish_enq(); } } } } private void help_finish_enq() { final Node<E> last = tail; final Node<E> next = last.next; if (next != null && next != last) { // Check for self-linking int tid = next.enqTid; final OpDesc<E> curDesc = state.get(tid); if (last == tail && state.get(tid).node == next) { final OpDesc<E> newDesc = new OpDesc<E>(state.get(tid).phase, false, true, next); state.compareAndSet(tid, curDesc, newDesc); casTail(last, next); } } } public E deq() { // We better have consecutive thread ids, otherwise this will blow up // TODO: replace this mechanism with something more flexible final int TID = (int)(Thread.currentThread().getId() % NUM_THREADS); long phase = maxPhase() + 1; state.set(TID, new OpDesc<E>(phase, true, false, null)); help(phase); help_finish_deq(); final Node<E> node = state.get(TID).node; if (node == null) return null; // We return null instead of throwing an exception final E value = node.next.value; node.next = node; // Self-link to help the GC return value; } private void help_deq(int tid, long phase) { while (isStillPending(tid, phase)) { Node<E> first = head; Node<E> last = tail; Node<E> next = first.next; if (first == head) { // If it's still head then it's not self-linked if (first == last) { if (next == null) { OpDesc<E> curDesc = state.get(tid); if (last == tail && isStillPending(tid, phase)) { OpDesc<E> newDesc = new OpDesc<E>(state.get(tid).phase, false, false, null); state.compareAndSet(tid, curDesc, newDesc); } } else { help_finish_enq(); } } else { OpDesc<E> curDesc = state.get(tid); Node<E> node = curDesc.node; if (!isStillPending(tid, phase)) break; if (first == head && node != first) { OpDesc<E> newDesc = new OpDesc<E>(state.get(tid).phase, true, false, first); if (!state.compareAndSet(tid, curDesc, newDesc)) { continue; } } first.deqTid.compareAndSet(-1, tid); help_finish_deq(); } } } } private void help_finish_deq() { final Node<E> first = head; final Node<E> next = first.next; int tid = first.deqTid.get(); if (tid != -1 && next != first) { final OpDesc<E> curDesc = state.get(tid); if (first == head && next != null) { final OpDesc<E> newDesc = new OpDesc<E>(state.get(tid).phase, false, false, state.get(tid).node); state.compareAndSet(tid, curDesc, newDesc); casHead(first, next); } } } private boolean casTail(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); } private boolean casHead(Node<E> cmp, Node<E> val) { return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long tailOffset; private static final long headOffset; static { try { Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); UNSAFE = (sun.misc.Unsafe) f.get(null); Class<?> k = KoganPetrankQueue.class; tailOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("tail")); headOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("head")); } catch (Exception e) { throw new Error(e); } } }
nickyc975/Database-SocialNetwork
src/main/java/database/entities/Reply.java
package database.entities; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; public class Reply extends Entity { private static PreparedStatement createStatement; private static PreparedStatement loadStatement; private static PreparedStatement deleteStatement; private static String createString = "INSERT INTO `social_network`.`reply` " + "(`user_id`, `post_id`, `content`) " + "VALUES (?, ?, ?);"; private static String loadString = "SELECT * FROM `social_network`.`reply` WHERE `reply_id` = ?;"; private static String deleteString = "DELETE FROM `social_network`.`reply` WHERE `reply_id` = ?;"; private Integer reply_id = null; private Integer user_id = null; private Integer post_id = null; private Integer replied_id = null; private String content = null; private Date reply_time = null; public Reply(Integer reply_id) { this.reply_id = reply_id; } public Reply(Integer user_id, Integer post_id, String content) { this.user_id = user_id; this.post_id = post_id; this.content = content; } /** * @return the user_id */ public Integer getUserID() { return user_id; } /** * @return the post_id */ public Integer getPostID() { return post_id; } /** * @return the replied_id */ public Integer getRepliedID() { return replied_id; } /** * @return the content */ public String getContent() { return content; } /** * @return the reply_time */ public Date getReplyTime() { return new Date(reply_time.getTime()); } @Override public String primaryKey() { return this.reply_id.toString(); } @Override public void create() throws SQLException { if (createStatement == null) { createStatement = connection.prepareStatement(createString, Statement.RETURN_GENERATED_KEYS); } createStatement.setInt(1, this.user_id); createStatement.setInt(2, this.post_id); createStatement.setString(3, this.content); createStatement.executeUpdate(); ResultSet keys = createStatement.getGeneratedKeys(); if (keys.next()) { this.reply_id = keys.getInt(1); } keys.close(); connection.commit(); load(); } @Override public void delete() throws SQLException { if (deleteStatement == null) { deleteStatement = connection.prepareStatement(deleteString); } deleteStatement.setInt(1, this.reply_id); deleteStatement.executeUpdate(); connection.commit(); } @Override public void load() throws SQLException { if (loadStatement == null) { loadStatement = connection.prepareStatement(loadString); } ResultSet result; loadStatement.setInt(1, this.reply_id); result = loadStatement.executeQuery(); if (!result.next()) { throw new SQLException("User not exists!"); } result.first(); this.user_id = result.getInt("user_id"); this.post_id = result.getInt("post_id"); this.replied_id = result.getInt("replied_id"); this.content = result.getString("content"); this.reply_time = result.getDate("reply_time"); result.close(); } @Override public void store() throws SQLException { throw new RuntimeException("Operation not supported!"); } @Override public void update(Map<String, String> properties) { String key, value; for (Entry<String, String> entry : properties.entrySet()) { key = entry.getKey(); value = entry.getValue(); switch (key) { case "content": this.content = value; default: break; } } } public static ArrayList<Reply> query(String queryString) throws SQLException { Reply reply; ResultSet result = naiveQuery(queryString); ArrayList<Reply> replyList = new ArrayList<>(); while (result.next()) { reply = new Reply(result.getInt("user_id"), result.getInt("post_id"), result.getString("content")); reply.reply_id = result.getInt("reply_id"); replyList.add(reply); } return replyList; } @Override public String toString() { return "{" + "reply_id=" + reply_id + ", post_id=" + post_id + ", replied_id=" + replied_id + ", content=" + content + ", reply_time=" + reply_time + "}"; } }
GravityMatrix/rsql-mybatis
src/main/java/com/github/mybatis/searcher/convert/StringToIntegerConverter.java
package com.github.mybatis.searcher.convert; import cn.hutool.core.util.NumberUtil; /** * @author WangChen * @since 2022-01-07 17:11 **/ public class StringToIntegerConverter implements SearchConverter<Integer> { @Override public Integer convert(String target) { return NumberUtil.isInteger(target) ? Integer.valueOf(target) : null; } }
uccser-admin/programming-practice-prototype
codewof/programming/content/en/prime-numbers/solution.py
number = int(input("Enter a positive integer: ")) if number < 2: print('No primes.') else: print(2) for possible_prime in range(3, number + 1): prime = True for divisor in range(2, possible_prime): if (possible_prime % divisor) == 0: prime = False break if prime: print(possible_prime)
fogoplayer/M2N-website
src/pages/membership.js
import React from 'react' import Layout from '../components/layout' import Seo from '../components/seo' import MembershipPage from '../components/membership' export default function membership() { return ( <Layout> <Seo title={'Membership'} /> <MembershipPage /> </Layout> ) }
JoeGruffins/termdash
internal/segdisp/segment/segment_test.go
// Copyright 2019 Google Inc. // // 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 segment import ( "fmt" "image" "testing" "github.com/joegruffins/termdash/cell" "github.com/joegruffins/termdash/internal/area" "github.com/joegruffins/termdash/internal/canvas/braille" "github.com/joegruffins/termdash/internal/canvas/braille/testbraille" "github.com/joegruffins/termdash/internal/draw" "github.com/joegruffins/termdash/internal/draw/testdraw" "github.com/joegruffins/termdash/internal/faketerm" ) func TestHV(t *testing.T) { tests := []struct { desc string opts []Option cellCanvas image.Rectangle // Canvas in cells that will be converted to braille canvas for drawing. ar image.Rectangle st Type want func(size image.Point) *faketerm.Terminal wantErr bool }{ { desc: "fails on area with negative Min.X", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(-1, 0, 1, 1), st: Horizontal, wantErr: true, }, { desc: "fails on area with negative Min.Y", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, -1, 1, 1), st: Horizontal, wantErr: true, }, { desc: "fails on area with negative Max.X", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rectangle{image.Point{0, 0}, image.Point{-1, 1}}, st: Horizontal, wantErr: true, }, { desc: "fails on area with negative Max.Y", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rectangle{image.Point{0, 0}, image.Point{1, -1}}, st: Horizontal, wantErr: true, }, { desc: "fails on area with zero Dx()", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 0, 1), st: Horizontal, wantErr: true, }, { desc: "fails on area with zero Dy()", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 0), st: Horizontal, wantErr: true, }, { desc: "fails on unsupported segment type (too small)", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), st: Type(0), wantErr: true, }, { desc: "fails on unsupported segment type (too large)", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), st: Type(int(Vertical) + 1), wantErr: true, }, { desc: "fails on area larger than the canvas", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 3, 1), st: Horizontal, wantErr: true, }, { desc: "sets cell options", opts: []Option{ CellOpts( cell.FgColor(cell.ColorRed), cell.BgColor(cell.ColorGreen), ), }, cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testbraille.MustSetPixel(bc, image.Point{0, 0}, cell.FgColor(cell.ColorRed), cell.BgColor(cell.ColorGreen)) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 1x1", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testbraille.MustSetPixel(bc, image.Point{0, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 1x2", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 1x3", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 1x4", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 4), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{0, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 1x5", cellCanvas: image.Rect(0, 0, 1, 2), ar: image.Rect(0, 0, 1, 5), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 4}, image.Point{0, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 2x1", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 2x2", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 2x3", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 2x4", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 4), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 2x5", cellCanvas: image.Rect(0, 0, 1, 2), ar: image.Rect(0, 0, 2, 5), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 4}, image.Point{1, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x2, reverse slopes", opts: []Option{ ReverseSlopes(), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 1}, image.Point{1, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x3, reverse slopes has no effect on larger height", opts: []Option{ ReverseSlopes(), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x3, skip slopes", opts: []Option{ SkipSlopesLTE(3), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x3, doesn't skip slopes because is taller", opts: []Option{ SkipSlopesLTE(2), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 4), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 3x5", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 3, 5), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 4}, image.Point{1, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 4x1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 4x2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 4x3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{2, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 4x4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 4x5", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 4, 5), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 4}, image.Point{2, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 5x1", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 1), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{4, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 5x2", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 2), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 5x3", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 3), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{3, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 5x4", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 4), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{4, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{3, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "horizontal, segment 5x5", cellCanvas: image.Rect(0, 0, 3, 2), ar: image.Rect(0, 0, 5, 5), st: Horizontal, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{4, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{2, 4}, image.Point{2, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 1x1", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 1), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testbraille.MustSetPixel(bc, image.Point{0, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 1x2", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 2), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 1x3", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 1x4", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 4), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{0, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 1x5", cellCanvas: image.Rect(0, 0, 1, 2), ar: image.Rect(0, 0, 1, 5), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 4}, image.Point{0, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x1", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 1), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x2", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x3", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x3, reverse slopes", opts: []Option{ ReverseSlopes(), }, cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{0, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x4", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 4), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 2x5", cellCanvas: image.Rect(0, 0, 1, 2), ar: image.Rect(0, 0, 2, 5), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{1, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 4}, image.Point{1, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 1), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 2), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x3, reverse slopes has no effect on larger width", opts: []Option{ ReverseSlopes(), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x3, skips slopes", opts: []Option{ SkipSlopesLTE(3), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x3, doesn't skips slopes because is wider", opts: []Option{ SkipSlopesLTE(2), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{1, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 3, 4), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 3x5", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 3, 5), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{1, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{2, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 4}, image.Point{1, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 4x1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 1), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 4x2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 2), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 4x3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 2}, image.Point{2, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 4x4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 4x5", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 4, 5), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 4}, image.Point{2, 4}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 5x1", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 1), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{4, 0}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 5x2", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 2), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{4, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 5x3", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 3), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testdraw.MustBrailleLine(bc, image.Point{2, 2}, image.Point{2, 2}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 5x4", cellCanvas: image.Rect(0, 0, 3, 1), ar: image.Rect(0, 0, 5, 4), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{4, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{4, 2}) testdraw.MustBrailleLine(bc, image.Point{2, 3}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "vertical, segment 5x5", cellCanvas: image.Rect(0, 0, 3, 2), ar: image.Rect(0, 0, 5, 5), st: Vertical, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{2, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 1}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{4, 2}) testdraw.MustBrailleLine(bc, image.Point{1, 3}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{2, 4}, image.Point{2, 4}) testbraille.MustApply(bc, ft) return ft }, }, } for _, tc := range tests { t.Run(fmt.Sprintf("%s st:%v", tc.desc, tc.st), func(t *testing.T) { bc, err := braille.New(tc.cellCanvas) if err != nil { t.Fatalf("braille.New => unexpected error: %v", err) } err = HV(bc, tc.ar, tc.st, tc.opts...) if (err != nil) != tc.wantErr { t.Errorf("HV => unexpected error: %v, wantErr: %v", err, tc.wantErr) } if err != nil { return } size := area.Size(tc.cellCanvas) want := faketerm.MustNew(size) if tc.want != nil { want = tc.want(size) } got, err := faketerm.New(size) if err != nil { t.Fatalf("faketerm.New => unexpected error: %v", err) } if err := bc.Apply(got); err != nil { t.Fatalf("bc.Apply => unexpected error: %v", err) } if diff := faketerm.Diff(want, got); diff != "" { t.Fatalf("HV => %v", diff) } }) } } // hvSegment is one horizontal or vertical segment. type hvSegment struct { ar image.Rectangle st Type } // diagSegment is one diagonal segment. type diagSegment struct { ar image.Rectangle width int dt DiagonalType } func TestAdjustHoriz(t *testing.T) { tests := []struct { desc string start image.Point end image.Point segWidth int adjust int wantStart image.Point wantEnd image.Point }{ { desc: "no change for zero adjustment", }, { desc: "safe adjustments, points don't cross", start: image.Point{0, 0}, end: image.Point{5, 0}, segWidth: 6, adjust: 1, wantStart: image.Point{1, 0}, wantEnd: image.Point{4, 0}, }, { desc: "safe adjustments, points land on each other", start: image.Point{0, 0}, end: image.Point{4, 0}, segWidth: 5, adjust: 2, wantStart: image.Point{2, 0}, wantEnd: image.Point{2, 0}, }, { desc: "points cross, width divides evenly", start: image.Point{0, 0}, end: image.Point{5, 0}, segWidth: 6, adjust: 3, wantStart: image.Point{2, 0}, wantEnd: image.Point{3, 0}, }, { desc: "points cross, width divides oddly", start: image.Point{0, 0}, end: image.Point{6, 0}, segWidth: 7, adjust: 4, wantStart: image.Point{3, 0}, wantEnd: image.Point{3, 0}, }, } for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { gotStart, gotEnd := adjustHoriz(tc.start, tc.end, tc.segWidth, tc.adjust) if !gotStart.Eq(tc.wantStart) || !gotEnd.Eq(tc.wantEnd) { t.Errorf("adjustHoriz(%v, %v, %v, %v) => %v, %v, want %v, %v", tc.start, tc.end, tc.segWidth, tc.adjust, gotStart, gotEnd, tc.wantStart, tc.wantEnd) } }) } } func TestAdjustVert(t *testing.T) { tests := []struct { desc string start image.Point end image.Point segHeight int adjust int wantStart image.Point wantEnd image.Point }{ { desc: "no change for zero adjustment", }, { desc: "safe adjustments, points don't cross", start: image.Point{0, 0}, end: image.Point{0, 5}, segHeight: 6, adjust: 1, wantStart: image.Point{0, 1}, wantEnd: image.Point{0, 4}, }, { desc: "safe adjustments, points land on each other", start: image.Point{0, 0}, end: image.Point{0, 4}, segHeight: 5, adjust: 2, wantStart: image.Point{0, 2}, wantEnd: image.Point{0, 2}, }, { desc: "points cross, width divides evenly", start: image.Point{0, 0}, end: image.Point{0, 5}, segHeight: 6, adjust: 3, wantStart: image.Point{0, 2}, wantEnd: image.Point{0, 3}, }, { desc: "points cross, width divides oddly", start: image.Point{0, 0}, end: image.Point{0, 6}, segHeight: 7, adjust: 4, wantStart: image.Point{0, 3}, wantEnd: image.Point{0, 3}, }, } for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { gotStart, gotEnd := adjustVert(tc.start, tc.end, tc.segHeight, tc.adjust) if !gotStart.Eq(tc.wantStart) || !gotEnd.Eq(tc.wantEnd) { t.Errorf("adjustVert(%v, %v, %v, %v) => %v, %v, want %v, %v", tc.start, tc.end, tc.segHeight, tc.adjust, gotStart, gotEnd, tc.wantStart, tc.wantEnd) } }) } } func TestDiagonal(t *testing.T) { tests := []struct { desc string opts []DiagonalOption cellCanvas image.Rectangle // Canvas in cells that will be converted to braille canvas for drawing. ar image.Rectangle width int dt DiagonalType want func(size image.Point) *faketerm.Terminal wantErr bool }{ { desc: "fails on area with negative Min.X", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(-1, 0, 1, 1), width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on area with negative Min.Y", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, -1, 1, 1), width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on area with negative Max.X", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rectangle{image.Point{0, 0}, image.Point{-1, 1}}, width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on area with negative Max.Y", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rectangle{image.Point{0, 0}, image.Point{1, -1}}, width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on area with zero Dx()", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 0, 1), width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on area with zero Dy()", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 1, 0), width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on unsupported diagonal type (too small)", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), width: 1, dt: DiagonalType(0), wantErr: true, }, { desc: "fails on unsupported diagonal type (too large)", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 2, 2), width: 1, dt: DiagonalType(int(RightToLeft) + 1), wantErr: true, }, { desc: "fails on area larger than the canvas", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 3, 1), width: 1, dt: LeftToRight, wantErr: true, }, { desc: "fails on zero width", cellCanvas: image.Rect(0, 0, 1, 1), ar: image.Rect(0, 0, 3, 1), width: 0, dt: LeftToRight, wantErr: true, }, { desc: "left to right, area 4x4, width 1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 1, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 1", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 1, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 2, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 2", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 2, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 3", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 8x4, width 3", cellCanvas: image.Rect(0, 0, 4, 1), ar: image.Rect(0, 0, 8, 4), dt: LeftToRight, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{7, 3}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{7, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{6, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 8x4, width 3", cellCanvas: image.Rect(0, 0, 4, 1), ar: image.Rect(0, 0, 8, 4), dt: RightToLeft, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{7, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{6, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{7, 1}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x8, width 3", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 4, 8), dt: LeftToRight, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 7}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 6}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 7}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x8, width 3", cellCanvas: image.Rect(0, 0, 2, 2), ar: image.Rect(0, 0, 4, 8), dt: RightToLeft, width: 3, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 7}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 6}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 7}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 4, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 4", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 4, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 5", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 5, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 5", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 5, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 2}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 6", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 6, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 6", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 6, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 2}, image.Point{2, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, area 4x4, width 7", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 7, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{3, 0}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{3, 1}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 1}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 2}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{0, 3}, image.Point{3, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "right to left, area 4x4, width 7", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 7, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{0, 0}) testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{0, 1}) testdraw.MustBrailleLine(bc, image.Point{2, 0}, image.Point{0, 2}) testdraw.MustBrailleLine(bc, image.Point{3, 0}, image.Point{0, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 1}, image.Point{1, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 2}, image.Point{2, 3}) testdraw.MustBrailleLine(bc, image.Point{3, 3}, image.Point{3, 3}) testbraille.MustApply(bc, ft) return ft }, }, { desc: "left to right, fails when width is larger than area", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 8, wantErr: true, }, { desc: "right to left, fails when width is larger than area", cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: RightToLeft, width: 8, wantErr: true, }, { desc: "sets cell options", opts: []DiagonalOption{ DiagonalCellOpts( cell.FgColor(cell.ColorRed), cell.BgColor(cell.ColorGreen), ), }, cellCanvas: image.Rect(0, 0, 2, 1), ar: image.Rect(0, 0, 4, 4), dt: LeftToRight, width: 2, want: func(size image.Point) *faketerm.Terminal { ft := faketerm.MustNew(size) bc := testbraille.MustNew(ft.Area()) opts := []draw.BrailleLineOption{ draw.BrailleLineCellOpts( cell.FgColor(cell.ColorRed), cell.BgColor(cell.ColorGreen), ), } testdraw.MustBrailleLine(bc, image.Point{1, 0}, image.Point{3, 2}, opts...) testdraw.MustBrailleLine(bc, image.Point{0, 0}, image.Point{3, 3}, opts...) testbraille.MustApply(bc, ft) return ft }, }, } for _, tc := range tests { t.Run(fmt.Sprintf("%s dt:%v", tc.desc, tc.dt), func(t *testing.T) { bc, err := braille.New(tc.cellCanvas) if err != nil { t.Fatalf("braille.New => unexpected error: %v", err) } err = Diagonal(bc, tc.ar, tc.width, tc.dt, tc.opts...) if (err != nil) != tc.wantErr { t.Errorf("Diagonal => unexpected error: %v, wantErr: %v", err, tc.wantErr) } if err != nil { return } size := area.Size(tc.cellCanvas) want := faketerm.MustNew(size) if tc.want != nil { want = tc.want(size) } got, err := faketerm.New(size) if err != nil { t.Fatalf("faketerm.New => unexpected error: %v", err) } if err := bc.Apply(got); err != nil { t.Fatalf("bc.Apply => unexpected error: %v", err) } if diff := faketerm.Diff(want, got); diff != "" { t.Fatalf("Diagonal => %v", diff) } }) } }
All8Up/cpf
Cpf/Plugins/Game/EntityService/Public/EntityService.hpp
<reponame>All8Up/cpf ////////////////////////////////////////////////////////////////////////// #pragma once #include "EntityService/Export.hpp" #include "CPF/Plugin/iRegistry.hpp" namespace CPF { struct EntityServiceInitializer { static int Install(Plugin::iRegistry* registry); static int Remove(); private: EntityServiceInitializer() = delete; ~EntityServiceInitializer() = delete; }; } #ifdef CPF_STATIC_ENTITYSERVICE # define CPF_INIT_ENTITYSERVICE(reg, dir) ScopedInitializer<EntityServiceInitializer, int, Plugin::iRegistry*> entityServiceInit(reg); #else # define CPF_INIT_ENTITYSERVICE(reg, dir) reg->Load(dir "/EntityService.cfp"); #endif
crunchbang/lang-adventures
c/misc/linked_list/push.c
#include <stdlib.h> #include <stdio.h> #include "node.h" void Push(struct node** headRef, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = *headRef; *headRef = newNode; } void PushTest () { struct node* head = buildOneTwoThree(); struct node* curr; Push(&head, 1); Push(&head, 13); curr = head; while (curr != NULL) { printf("%d->", curr->data); curr = curr->next; } }
aajjbb/contest-files
Codeforces/DZYLovesSequences.cpp
<gh_stars>1-10 #include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; const int MAXN = 100005; int N; int P[MAXN], C[MAXN]; int main(void) { cin >> N; vector<pair<int, int> > vp; for (int i = 0; i < N; i++) { cin >> P[i]; } for (int i = 0; i < N; i++) { int j = i + 1; while (j < N) { if (P[j] < P[j - 1]) { P[j] = (j - 2 >= 0 ? P[j - 2] + 1 : P[j] - 1); C[j] += 1; } j++; } i = j; } for (int i = 0; i < N; i++) { cout << P[i] << " "; } cout << "\n"; int best = 0; for (int i = 0; i < N; i++) { int j = i; int cnt = 0; while (j < N && cnt < 2) { cnt += C[i]; if (j - 1 >= 0 && P[j] <= P[j - 1]) break; j++; } if (j == N) j--; chmax(best, j - i + 1); if (j == N) j++; } /* int j = i + 1; chmax(best, vp[i].second - vp[i].first + 1); // cout << vp[i].first << " "<< vp[i].second << "\n"; // cout << "go\n"; while (j < N && vp[j].first <= vp[i].second) { // cout << vp[j].first << " "<< vp[j].second << "\n"; if (vp[j].first == vp[i].second && vp[i].first - 1 >= 0 && vp[j].second + 1 < N && P[vp[i].first - 1] + 1 < P[vp[j].second + 1]) { chmax(best, vp[j].second - vp[i].first + 1); } j++; } } */ cout << best << "\n"; return 0; }
stephengold/Heart
HeartLibrary/src/main/java/jme3utilities/MyRender.java
<gh_stars>10-100 /* Copyright (c) 2019-2021, <NAME> 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 copyright holder 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. */ package jme3utilities; import com.jme3.renderer.opengl.GL; import com.jme3.renderer.opengl.GLRenderer; import java.lang.reflect.Field; import java.util.logging.Logger; /** * Utility methods that operate on jME3 renderers. * * @author Stephen Gold <EMAIL> */ final public class MyRender { // ************************************************************************* // constants and loggers /** * message logger for this class */ final private static Logger logger = Logger.getLogger(MyRender.class.getName()); // ************************************************************************* // constructors /** * A private constructor to inhibit instantiation of this class. */ private MyRender() { } // ************************************************************************* // new methods exposed /** * Access the baseline OpenGL interface of the specified renderer. * * @param renderer which renderer (not null, unaffected) * @return the pre-existing interface (not null) */ public static GL getGL(GLRenderer renderer) { Field field; try { field = GLRenderer.class.getDeclaredField("gl"); } catch (NoSuchFieldException exception) { throw new RuntimeException(exception); } field.setAccessible(true); GL result; try { result = (GL) field.get(renderer); } catch (IllegalAccessException exception) { throw new RuntimeException(exception); } assert result != null; return result; } }
Luecx/3DGameEngine_src
projects/game/solarsystem/Celestial.java
package projects.game.solarsystem; import engine.core.components.Group; import engine.core.exceptions.CoreException; import engine.core.sourceelements.RawModel; import engine.core.system.Sys; import engine.linear.entities.Entity; import engine.linear.entities.TexturedModel; import engine.linear.loading.Loader; import engine.linear.loading.OBJLoader; import engine.linear.material.EntityMaterial; import java.util.ArrayList; /** * Created by Luecx on 19.01.2017. */ public class Celestial { public static double SCALE_FACTOR = Math.pow(10,-2); public static double SPHERE_DEFAULT_RAD = 99.6; public static RawModel model = OBJLoader.loadOBJ("objectWithTextures/moon/moon", true); public ArrayList<Celestial> subObjects = new ArrayList<>(); private Celestial parent; private Group connection = new Group(); private Group group = new Group(); private Entity entity; //Unit := KM private double dist; //distance to center of rotation private double rad; //radius of the object //Unit := KG private double mass; //mass of the object //Unit := days public double circulationTime; //time to rotate around the center private double rotationTime; //time to rotate around its y axis public Celestial(double mass, double centerMass, double distance, double rotationTime){ this.mass = mass; this.connection.addChild(group); this.dist = distance; this.group.setPosition((float)(SCALE_FACTOR * dist),0,0); this.circulationTime = Calculus.calculateCirculationTime(mass, centerMass, distance); this.rotationTime = rotationTime; } public Celestial addSubObject(double mass, double dist, double rotationTime){ Celestial subObj = new Celestial(mass, this.mass, dist, rotationTime); subObj.setParent(this); subObjects.add(subObj); return subObj; } public boolean hasActiveEntity() { return this.entity != null; } public void update(double days){ if(circulationTime != 0) this.connection.increaseRotation(0,(float)(days/circulationTime)*360,0); if(rotationTime == 0) return; this.entity.increaseRotation(0,(float)(days/rotationTime)*360,0); updateAllChilds(days); } public void updateAllChilds(double days) { for (Celestial c : subObjects){ c.update(days); } } public void generateEntity(String texture, String normal, boolean transparent, float specular, float reflec){ if(hasActiveEntity()) { return; } EntityMaterial material = new EntityMaterial(Loader.loadTexture(texture)); material.setNormalMap(Loader.loadTexture(normal)); material.setTransparency(transparent); material.setShineDamper(specular); material.setReflectivity(reflec); TexturedModel model1 = new TexturedModel(Celestial.model , material); this.entity = new Entity(model1); this.entity.setParent(this.group); try { Sys.NORMAL_ENTITY_SYSTEM.addElement(this.entity); } catch (CoreException e) { e.printStackTrace(); } } public void setParent(Celestial celestial) { this.parent = celestial; this.connection.setParent(celestial.group); } public void addChild(Celestial celestial) { celestial.setParent(this); } public double getMass() { return mass; } public void setMass(double mass) { this.mass = mass; this.circulationTime = Calculus.calculateCirculationTime(mass, this.parent.getMass(), dist); } public double getDist() { return dist; } @Deprecated public void setDist(double dist) { this.dist = dist; this.group.setPosition((float)(SCALE_FACTOR *dist),0,0); this.circulationTime = Calculus.calculateCirculationTime(mass, this.parent.getMass(), dist); } public double getRad() { return rad; } public void setRad(double rad) { this.rad = rad; this.entity.setScale((float)(rad * SCALE_FACTOR / SPHERE_DEFAULT_RAD),(float)(rad * SCALE_FACTOR / SPHERE_DEFAULT_RAD),(float)(rad * SCALE_FACTOR / SPHERE_DEFAULT_RAD)); } public double getCirculationTime() { return circulationTime; } public void setCirculationTime(double circulationTime) { this.circulationTime = circulationTime; } public void printEntityInformation(){ if(hasActiveEntity()){ System.out.println(entity.toString()); } } public Group getConnection() { return connection; } public Group getGroup() { return group; } public Entity getEntity() { return entity; } public Celestial getParent() { return parent; } public double getRotationTime() { return rotationTime; } @Override public String toString() { return "Celestial{" + ",\n dist=" + dist + ",\n rad=" + rad + ",\n mass=" + mass + ",\n circulationTime=" + circulationTime + ",\n rotationTime=" + rotationTime + '}'; } }
frimtec/PikettAssist
app/src/test/java/com/github/frimtec/android/pikettassist/service/TestAlarmServiceWorkUnitTest.java
package com.github.frimtec.android.pikettassist.service; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import android.content.Intent; import com.github.frimtec.android.pikettassist.domain.OnOffState; import com.github.frimtec.android.pikettassist.domain.TestAlarmContext; import com.github.frimtec.android.pikettassist.service.dao.TestAlarmDao; import com.github.frimtec.android.pikettassist.service.system.AlarmService.ScheduleInfo; import com.github.frimtec.android.pikettassist.service.system.NotificationService; import com.github.frimtec.android.pikettassist.state.ApplicationPreferences; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.time.Duration; import java.time.Instant; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; class TestAlarmServiceWorkUnitTest { public static final HashSet<String> WEEK_DAYS = new HashSet<>(Arrays.asList("1", "2", "3", "4", "5")); public static final HashSet<String> ALL_DAYS = new HashSet<>(Arrays.asList("1", "2", "3", "4", "5", "6", "7")); @ParameterizedTest @ValueSource(booleans = {true, false}) void applyForTestAlarmDisabledShiftOnReturnsEmpty(boolean initial) { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(false); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(WEEK_DAYS); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn("12:00"); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(initial); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); // assert assertThat(scheduleInfo).isEqualTo(Optional.empty()); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @ParameterizedTest @ValueSource(booleans = {true, false}) void applyForTestAlarmEnabledShiftOffReturnsEmpty(boolean initial) { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(WEEK_DAYS); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn("12:00"); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.OFF); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(initial); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); // assert assertThat(scheduleInfo).isEqualTo(Optional.empty()); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @ParameterizedTest @ValueSource(booleans = {true, false}) void applyForTestNoWeekDaysReturnsEmpty(boolean initial) { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn("12:00"); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(initial); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); // assert assertThat(scheduleInfo).isEqualTo(Optional.empty()); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @Test void applyForInitialCheckTimeBeforeNowReturnsInitialFalseTimeTillTomorrowsCheckTime() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(ALL_DAYS); ZonedDateTime checkTime = ZonedDateTime.now().minusMinutes(10); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(true); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofDays(1).minusMinutes(11), Duration.ofDays(1).minusMinutes(10)); verify(resultIntent).putExtra("initial", false); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @Test void applyForInitialCheckTimeAfterNowReturnsInitialFalseTimeTillTodaysCheckTime() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(ALL_DAYS); ZonedDateTime checkTime = ZonedDateTime.now().plusMinutes(11); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(true); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofMinutes(10), Duration.ofMinutes(11)); verify(resultIntent).putExtra("initial", false); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @Test void applyForInitialCheckTimeAfterNowWithNextTwoWeekdaysDisabledReturnsInitialFalseTimeTillOverTomorrowsCheckTime() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); Set<String> weekdays = new HashSet<>(ALL_DAYS); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(weekdays); ZonedDateTime checkTime = ZonedDateTime.now().plusMinutes(11); weekdays.remove(String.valueOf(checkTime.getDayOfWeek().getValue())); weekdays.remove(String.valueOf(checkTime.plusDays(1).getDayOfWeek().getValue())); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); TestAlarmContext testAlarmContext = new TestAlarmContext("context"); when(testAlarmDao.isTestAlarmReceived(eq(testAlarmContext), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(true); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofDays(2).plusMinutes(10), Duration.ofDays(2).plusMinutes(11)); verify(resultIntent).putExtra("initial", false); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(testAlarmContext, OnOffState.ON); verify(alarmTrigger, never()).run(); } @Test void applyForNonInitialNotAllAlarmsReceivedWithinTimeReturnsInitialFalseTimeTillTomorrowsCheckTimeRacesAlarm() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); TestAlarmContext tc1 = new TestAlarmContext("tc1"); TestAlarmContext tc2 = new TestAlarmContext("tc2"); TestAlarmContext tc3 = new TestAlarmContext("tc3"); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(new HashSet<>(Arrays.asList(tc1, tc2, tc3))); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(ALL_DAYS); ZonedDateTime checkTime = ZonedDateTime.now(); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); when(testAlarmDao.isTestAlarmReceived(eq(tc1), any(Instant.class))).thenReturn(false); when(testAlarmDao.isTestAlarmReceived(eq(tc2), any(Instant.class))).thenReturn(true); when(testAlarmDao.isTestAlarmReceived(eq(tc3), any(Instant.class))).thenReturn(false); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(false); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofDays(1).minusMinutes(1), Duration.ofDays(1)); verify(resultIntent).putExtra("initial", false); verify(notificationService).notifyMissingTestAlarm(any(Intent.class), eq(new HashSet<>(Arrays.asList(tc1, tc3)))); verify(testAlarmDao).updateAlertState(tc1, OnOffState.ON); verify(testAlarmDao, never()).updateAlertState(tc2, OnOffState.ON); verify(testAlarmDao).updateAlertState(tc3, OnOffState.ON); verify(alarmTrigger).run(); } @Test void applyForNonTestContextInitialReturnsInitialFalseTimeTillTomorrowsCheckTime() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(Collections.emptySet()); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(ALL_DAYS); ZonedDateTime checkTime = ZonedDateTime.now(); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); when(testAlarmDao.isTestAlarmReceived(any(TestAlarmContext.class), any(Instant.class))).thenReturn(false); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(false); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofDays(1).minusMinutes(1), Duration.ofDays(1)); verify(resultIntent).putExtra("initial", false); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(any(TestAlarmContext.class), eq(OnOffState.ON)); verify(alarmTrigger, never()).run(); } @Test void applyForNonInitialAllAlarmsReceivedWithinTimeReturnsInitialFalseTimeTillTomorrowsCheckTime() { // arrange Context context = mock(Context.class); NotificationService notificationService = mock(NotificationService.class); ApplicationPreferences applicationPreferences = mock(ApplicationPreferences.class); when(applicationPreferences.getTestAlarmEnabled(context)).thenReturn(true); when(applicationPreferences.getTestAlarmAcceptTimeWindowMinutes(context)).thenReturn(15); TestAlarmContext tc1 = new TestAlarmContext("tc1"); TestAlarmContext tc2 = new TestAlarmContext("tc2"); TestAlarmContext tc3 = new TestAlarmContext("tc3"); when(applicationPreferences.getSupervisedTestAlarms(context)).thenReturn(new HashSet<>(Arrays.asList(tc1, tc2, tc3))); when(applicationPreferences.getTestAlarmCheckWeekdays(context)).thenReturn(ALL_DAYS); ZonedDateTime checkTime = ZonedDateTime.now(); when(applicationPreferences.getTestAlarmCheckTime(context)).thenReturn(checkTime.format(DateTimeFormatter.ofPattern("HH:mm"))); ShiftService shiftService = mock(ShiftService.class); when(shiftService.getState()).thenReturn(OnOffState.ON); TestAlarmDao testAlarmDao = mock(TestAlarmDao.class); when(testAlarmDao.isTestAlarmReceived(eq(tc1), any(Instant.class))).thenReturn(true); when(testAlarmDao.isTestAlarmReceived(eq(tc2), any(Instant.class))).thenReturn(true); when(testAlarmDao.isTestAlarmReceived(eq(tc3), any(Instant.class))).thenReturn(true); Runnable alarmTrigger = mock(Runnable.class); ServiceWorkUnit workUnit = new TestAlarmServiceWorkUnit( applicationPreferences, testAlarmDao, shiftService, notificationService, alarmTrigger, context ); Intent intent = mock(Intent.class); when(intent.getBooleanExtra("initial", true)).thenReturn(false); // act Optional<ScheduleInfo> scheduleInfo = workUnit.apply(intent); ScheduleInfo info = scheduleInfo.orElse(new ScheduleInfo(Duration.ZERO)); Intent resultIntent = mock(Intent.class); info.getIntentExtrasSetter().accept(resultIntent); // assert assertThat(info.getScheduleDelay()).isBetween(Duration.ofDays(1).minusMinutes(1), Duration.ofDays(1)); verify(resultIntent).putExtra("initial", false); //noinspection unchecked verify(notificationService, never()).notifyMissingTestAlarm(any(Intent.class), any(Set.class)); verify(testAlarmDao, never()).updateAlertState(any(TestAlarmContext.class), eq(OnOffState.ON)); verify(alarmTrigger, never()).run(); } }
IncioMan/findyourfriend
backend/src/main/java/com/group14/findeyourfriend/bracelet/Mover.java
package com.group14.findeyourfriend.bracelet; import com.group14.common_interface.Position; import com.group14.common_interface.Vector2; import com.group14.findeyourfriend.Constants; import com.group14.findeyourfriend.debug.DebugLog; public class Mover { private Position _position; private Vector2 _speed = new Vector2(); // private Vector2 _acceleration = new Vector2(); public final Position getPosition() { return _position; } public final void setPosition(Position value) { _position = value; } public final Vector2 getSpeed() { return _speed; } public void setSpeed(Vector2 value) { _speed = value; } // public final Vector2 getAcceleration() { // return _acceleration; // } // // public final void setAcceleration(Vector2 value) { // _acceleration = value; // } public final void MoveTo(Position pos) { setPosition(pos); } public final void UpdatePosition() { if ((getPosition().getCoordinates().x + getSpeed().x) > Constants.MAX_WIDTH || (getPosition().getCoordinates().x + getSpeed().x) < Constants.MIN_WIDTH) { Turn180DegreesOnXAxis(); } if ((getPosition().getCoordinates().y + getSpeed().y) > Constants.MAX_HEIGHT || (getPosition().getCoordinates().y + getSpeed().y) < Constants.MIN_HEIGHT) { Turn180DegreesOnYAxis(); } getPosition().Update(getSpeed()); // Speed = Vector2.Add(Speed, Acceleration); } public final void Turn180DegreesOnXAxis() { setSpeed(new Vector2(getSpeed().x * -1, getSpeed().y)); } public final void Turn180DegreesOnYAxis() { setSpeed(new Vector2(getSpeed().x, getSpeed().y * -1)); } @Override public String toString() { return "Position: " + getPosition().toString(); } public final void GoTowards(Position otherPosition) { DebugLog.log(getPosition() + " GoTowards " + otherPosition); Vector2 heading = Vector2.Subtract(otherPosition.getCoordinates(), getPosition().getCoordinates()); Vector2 direction = Vector2.Normalize(heading); setSpeed(Vector2.Multiply(1.8f, direction)); DebugLog.log("Direction: " + direction); } }
Dukoia/simple-mall
mall-sms/sms-boot/src/main/java/com/yqf/mall/sms/service/IAsyncService.java
<filename>mall-sms/sms-boot/src/main/java/com/yqf/mall/sms/service/IAsyncService.java package com.yqf.mall.sms.service; import com.yqf.mall.sms.pojo.domain.SmsCouponTemplate; /** * @author xinyi * @desc:异步服务接口 * @date 2021/6/27 */ public interface IAsyncService { /** * 通过优惠券模板异步的创建优惠券码 * @param template {@link SmsCouponTemplate} 优惠券模板实体 */ void asyncConstructCouponByTemplate(SmsCouponTemplate template); }
leiphp/gulimall
gulimall-product/src/main/java/cn/lxtkj/gulimall/product/service/SpuInfoService.java
package cn.lxtkj.gulimall.product.service; import cn.lxtkj.gulimall.product.entity.SpuInfoDescEntity; import cn.lxtkj.gulimall.product.vo.SpuSaveVo; import com.baomidou.mybatisplus.extension.service.IService; import cn.lxtkj.common.utils.PageUtils; import cn.lxtkj.gulimall.product.entity.SpuInfoEntity; import java.util.Map; /** * spu信息 * * @author leixiaotian * @email <EMAIL> * @date 2021-08-12 00:20:21 */ public interface SpuInfoService extends IService<SpuInfoEntity> { PageUtils queryPage(Map<String, Object> params); void saveSpuInfo(SpuSaveVo vo); void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity); PageUtils queryPageByCondition(Map<String, Object> params); void up(Long spuId); SpuInfoEntity getSpuInfoBySkuId(Long skuId); }
vikulin/PlayMarket-2.0-App
app/src/main/java/com/blockchain/store/playmarket/ui/pex_screen/DappsFragment.java
package com.blockchain.store.playmarket.ui.pex_screen; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import androidx.fragment.app.Fragment; import com.blockchain.store.playmarket.R; import com.blockchain.store.playmarket.dapps.Web3View; import com.blockchain.store.playmarket.data.entities.DappTransaction; import com.blockchain.store.playmarket.interfaces.BackPressedCallback; import com.blockchain.store.playmarket.ui.main_list_screen.MainMenuActivity; import com.blockchain.store.playmarket.utilities.AccountManager; import com.blockchain.store.playmarket.utilities.Constants; import com.blockchain.store.playmarket.utilities.ToastUtil; import com.blockchain.store.playmarket.utilities.crypto.CryptoUtils; import com.blockchain.store.playmarket.utilities.dialogs.DappTxDialog; import com.blockchain.store.playmarket.utilities.dialogs.SignMessageDialog; import com.blockchain.store.playmarket.utilities.drawable.HamburgerDrawable; import com.google.gson.Gson; import org.ethereum.geth.Account; import org.ethereum.geth.Transaction; import org.json.JSONObject; import org.spongycastle.util.encoders.Hex; import org.web3j.protocol.Web3j; import org.web3j.protocol.Web3jFactory; import org.web3j.protocol.core.methods.response.EthSendTransaction; import org.web3j.protocol.http.HttpService; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import wendu.dsbridge.CompletionHandler; import static com.blockchain.store.playmarket.api.RestApi.BASE_URL_INFURA; public class DappsFragment extends Fragment implements BackPressedCallback, DappTxDialog.TxDialogCallback { private static final String TAG = "DappsFragment"; private static final String IS_OPEN_FOR_DEX_KEY = "is_open_for_dex"; @BindView(R.id.web_view) Web3View webView; @BindView(R.id.progress_bar) ProgressBar progressBar; @BindView(R.id.browser_top_layout) LinearLayout topLayout; @BindView(R.id.webview_url_field) EditText urlField; @BindView(R.id.webview_home_field) ImageView homeField; @BindView(R.id.hamburger_icon) ImageView hamburgerIcon; @BindView(R.id.https_indicator) ImageView httpsIndicator; @BindView(R.id.horizontal_progress_bar) ProgressBar horizontalProgressBar; private boolean isOpenForDex = false; private Web3j web3j = Web3jFactory.build(new HttpService(BASE_URL_INFURA)); private boolean isUserSawThisPage = false; private CompletionHandler lastKnownHandler; public static DappsFragment newInstance() { Bundle args = new Bundle(); DappsFragment fragment = new DappsFragment(); args.putBoolean(IS_OPEN_FOR_DEX_KEY, true); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dapps, container, false); ButterKnife.bind(this, view); if (getArguments() != null) { isOpenForDex = getArguments().getBoolean(IS_OPEN_FOR_DEX_KEY, false); topLayout.setVisibility(View.GONE); } initEdittext(); setWebView(); return view; } @OnClick(R.id.hamburger_icon) void onHamburgerIcon() { ((MainMenuActivity) getActivity()).openDrawer(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser && !isUserSawThisPage) { this.isUserSawThisPage = true; } } private void initEdittext() { urlField.setOnKeyListener((v, keyCode, event) -> { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { String url = urlField.getText().toString(); if (!urlField.getText().toString().startsWith("http")) { url = "https://" + url; } if (!url.trim().isEmpty()) { webView.loadUrl(url); } hideKeyboardFrom(v); return true; } return false; }); } public void hideKeyboardFrom(View view) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } private void setWebView() { hamburgerIcon.setImageDrawable(new HamburgerDrawable(getActivity())); webView.addJavascriptObject(new JsApi(getActivity()), ""); webView.setCallback(new Web3View.Web3ViewCallback() { @Override public void onPageStarted(String page) { horizontalProgressBar.setVisibility(View.VISIBLE); httpsIndicator.setVisibility(View.GONE); urlField.setText(page); } @Override public void onPageFinished(String page) { horizontalProgressBar.setVisibility(View.GONE); if (page.startsWith("http://")) { page = page.replaceFirst("http://", ""); } if (page.startsWith("https://")) { page = page.replaceFirst("https://", ""); httpsIndicator.setVisibility(View.VISIBLE); } urlField.setText(page); } }); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); horizontalProgressBar.setProgress(newProgress); } }); loadDefaultUrl(); } private void loadDefaultUrl() { if (isOpenForDex) { webView.loadUrl(Constants.PAX_URL); } else { webView.loadUrl(Constants.DAPPS_URL); } } @OnClick(R.id.webview_home_field) void onHomeClicked() { webView.clearHistory(); loadDefaultUrl(); } @Override public boolean isUserCanHandleBackPressed() { if (webView != null && webView.canGoBack()) { webView.goBack(); } return false; } @Override public void onAccountUnlocked(DappTransaction dappTransaction, boolean isNeedToSendTx) { try { Transaction dapTx = dappTransaction.createTx(); if (isNeedToSendTx) { if (this.lastKnownHandler != null) { lastKnownHandler.complete(dapTx.getHash().getHex()); } sendRawTransaction(dapTx); } else { if (this.lastKnownHandler != null) { lastKnownHandler.complete(dapTx.toString()); } } } catch (Exception e) { e.printStackTrace(); ToastUtil.showToast(e.getMessage()); } } public class JsApi { private Context context; public JsApi(Context context) { this.context = context; } @JavascriptInterface public void getAccounts(Object abc, CompletionHandler handler) { Log.d(TAG, "getAccounts() called with: handler = [" + AccountManager.getAccount().getAddress().getHex() + "]" + abc); handler.complete(AccountManager.getAccount().getAddress().getHex()); } @JavascriptInterface public void signMessage(Object serverResult, CompletionHandler handler) { sign(serverResult,handler); } @JavascriptInterface public void signTx(Object tx, CompletionHandler handler) { Log.d(TAG, "signTx() called with: tx = [" + tx + "], handler = [" + handler + "]"); createTx(tx, handler); } @JavascriptInterface public void sign(Object tx, CompletionHandler handler) { Log.d(TAG, "sign() called with: tx = [" + tx + "], handler = [" + handler + "]"); try { JSONObject jsonObject = new JSONObject(tx.toString()); String data = jsonObject.getString("data"); data = new String(Hex.decode(data.replaceFirst("0x", ""))); String finalData = data; new SignMessageDialog(getActivity(), data, () -> { try { Account account = AccountManager.getAccount(); String msg = "\u0019Ethereum Signed Message:\n" + finalData.length() + finalData; byte[] secondSignMsgBytes = AccountManager.getKeyManager().signString(account, msg); String secondSignMsg = Hex.toHexString(secondSignMsgBytes); handler.complete("0x" + secondSignMsg); } catch (Exception e) { e.printStackTrace(); } }).show(); } catch (Exception e) { e.printStackTrace(); } } private void createTx(Object tx, CompletionHandler handler) { lastKnownHandler = handler; DappTransaction dappTransaction = new Gson().fromJson(tx.toString(), DappTransaction.class); showFragmentDialog(dappTransaction, false); } @JavascriptInterface public void sendTransaction(Object tx, CompletionHandler handler) { lastKnownHandler = handler; DappTransaction dappTransaction = new Gson().fromJson(tx.toString(), DappTransaction.class); showFragmentDialog(dappTransaction, true); } private void showFragmentDialog(DappTransaction dappTransaction, boolean isNeedToSendTx) { DappTxDialog.newInstance(dappTransaction, isNeedToSendTx).show(getChildFragmentManager(), "fragment-tag"); DappTxDialog fragmentDialog = (DappTxDialog) getChildFragmentManager().findFragmentByTag("fragment-tag"); fragmentDialog.setCallback(DappsFragment.this); } } private void sendRawTransaction(Transaction tx) { web3j.ethSendRawTransaction("0x" + CryptoUtils.getRawTransaction(tx)).observable() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onTxSend, this::onTxFailed); } private void onTxSend(EthSendTransaction ethSendTransaction) { } private void onTxFailed(Throwable throwable) { } }
Phikzel2/haroldcoin-main-MacOS
contrib/gitian-builder/inputs/MacOSX.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/IOKit/firewire/IOFWLocalIsochPort.h
/* * Copyright (c) 1998-2002 Apple Computer, Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1999-2002 Apple Computer, Inc. All rights reserved. * * IOFWIsochPort is an abstract object that represents hardware on the bus * (locally or remotely) that sends or receives isochronous packets. * Local ports are implemented by the local device driver, * Remote ports are implemented by the driver for the remote device. * * HISTORY * * $Log: not supported by cvs2svn $ * Revision 1.9 2003/08/30 00:16:44 collin * *** empty log message *** * * Revision 1.8 2003/08/15 04:36:55 niels * *** empty log message *** * * Revision 1.7 2003/07/29 22:49:22 niels * *** empty log message *** * * Revision 1.6 2003/07/21 06:52:58 niels * merge isoch to TOT * * Revision 1.5.14.1 2003/07/01 20:54:07 niels * isoch merge * */ #ifndef _IOKIT_IOFWLOCALISOCHPORT_H #define _IOKIT_IOFWLOCALISOCHPORT_H #import <IOKit/firewire/IOFireWireFamilyCommon.h> #import <IOKit/firewire/IOFWIsochPort.h> class IOFireWireController; class IODCLProgram; /*! @class IOFWLocalIsochPort */ class IOFWLocalIsochPort : public IOFWIsochPort { OSDeclareDefaultStructors(IOFWLocalIsochPort) protected: IOFireWireController * fControl; IODCLProgram * fProgram; /*! @struct ExpansionData @discussion This structure will be used to expand the capablilties of the class in the future. */ struct ExpansionData { } ; ExpansionData * fExpansion ; protected : virtual void free ( void ) APPLE_KEXT_OVERRIDE; public: virtual bool init ( IODCLProgram * program, IOFireWireController * control ) ; // Return maximum speed and channels supported // (bit n set = chan n supported) virtual IOReturn getSupported ( IOFWSpeed & maxSpeed, UInt64 & chanSupported ) APPLE_KEXT_OVERRIDE; // Allocate hardware resources for port virtual IOReturn allocatePort ( IOFWSpeed speed, UInt32 chan ) APPLE_KEXT_OVERRIDE; virtual IOReturn releasePort ( void ) APPLE_KEXT_OVERRIDE; // Free hardware resources virtual IOReturn start ( void ) APPLE_KEXT_OVERRIDE; // Start port processing packets virtual IOReturn stop ( void ) APPLE_KEXT_OVERRIDE; // Stop processing packets /*! @function notify @abstract Informs hardware of a change to the DCL program. @param notificationType Type of change. @param dclCommandList List of DCL commands that have been changed. @param numDCLCommands Number of commands in list. @result IOKit error code. */ virtual IOReturn notify( IOFWDCLNotificationType notificationType, DCLCommand ** dclCommandList, UInt32 numDCLCommands ) ; static void printDCLProgram ( const DCLCommand * dcl, UInt32 count = 0, void (*printFN)( const char *format, ...) = NULL, unsigned lineDelayMS = 0 ) ; IOReturn setIsochResourceFlags ( IOFWIsochResourceFlags flags ) ; IODCLProgram * getProgramRef() const ; IOReturn synchronizeWithIO() ; private: OSMetaClassDeclareReservedUnused ( IOFWLocalIsochPort, 0 ) ; OSMetaClassDeclareReservedUnused ( IOFWLocalIsochPort, 1 ) ; }; #endif /* ! _IOKIT_IOFWLOCALISOCHPORT_H */
msinno01/SARSCoV2HeronPipeline
heronPipeline/src/images/genotypeVariants/recipe_graph.py
from dataclasses import dataclass from typing import List @dataclass class Node: """ Assume that a recipe can only require a single parent recipe. However, a recipe can be required by multiple child recipes. """ name: str child_names: List[str] parent_name: str class RecipeDirectedGraph: def __init__(self, recipes: List[dict]): """ Parameters: -------------- recipes : list of recipe dicts Each recipe dict is defined by a PHE recipe YAML. Returns: ------------- An directed graph representation of the recipes. Two recipes are connected if a recipe has a 'requires' tag in the PHE recipe YAML that points to the other recipe. Internally, the graph is represented by a dict {node name => Node}, A Node object stores the name of it's parent node and names of it's child nodes, but not the child Node and parent Node objects themselves. The collection of node objects is only stored in the graph dict. A child node is a recipe that "requires" another recipe and a parent node is a recipe that is required by another recipe. There should be a directed edge between each child and parent. Recipes that do not require another recipe and are not required by other recipes will be unconnected nodes in the graph. """ self.graph = {} for recipe in recipes: recipe_name = recipe["unique-id"] if recipe_name not in self.graph: self.graph[recipe_name] = Node(name=recipe_name, child_names=[], parent_name=None) recipe_node = self.graph[recipe_name] if "requires" in recipe: parent_recipe_name = recipe["requires"] if parent_recipe_name not in self.graph: self.graph[parent_recipe_name] = Node(name=parent_recipe_name, child_names=[], parent_name=None) parent_recipe_node = self.graph[parent_recipe_name] recipe_node.parent_name = parent_recipe_name parent_recipe_node.child_names.append(recipe_name) def is_single_branch(self): """ Returns: boolean ----------------- Whether all nodes in the graph are connected in a single branch, forming a single path from root to leaf, and having only 1 leaf. If there are recipes in the graph that represent splitting branches in a tree, then is_single_branch() will return false. """ if len(self.graph.keys()) < 2: raise ValueError("Can only calculate leaf in graph with at least 2 nodes") leaf_count = 0 is_connected = True for node in self.graph.values(): # Disconnected node in graph if node.parent_name is None and len(node.child_names) == 0: is_connected = False break # Leaf node if node.parent_name is not None and len(node.child_names) == 0: leaf_count += 1 return is_connected and leaf_count == 1 def get_leaf_name(self): """ Returns: str ----------------- Returns the name of the first leaf encountered or None if there are no leafs. A leaf is a node that has a parent node but no child nodes. Does not care if the graph is disconnected. Raises: ----------------- ValueError If the graph has less than 2 nodes """ if len(self.graph.keys()) < 2: raise ValueError("Can only calculate leaf in graph with at least 2 nodes") for node in self.graph.values(): if node.parent_name is not None and len(node.child_names) == 0: return node.name return None def __str__(self): graph_str = "" for node_name, node in self.graph.items(): child_str = ", ".join(node.child_names) graph_str += f"{node_name}->[{child_str}]\n" return graph_str
TheRakeshPurohit/CodingSpectator
plug-ins/indigo/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescriptor.java
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.resources; import org.eclipse.core.resources.IFilterMatcherDescriptor; import org.eclipse.core.resources.filtermatchers.AbstractFileInfoMatcher; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; public class FilterDescriptor implements IFilterMatcherDescriptor { private String id; private String name; private String description; private String argumentType; private boolean isFirst = false; private IConfigurationElement element; public FilterDescriptor(IConfigurationElement element) throws CoreException { this(element, true); } public FilterDescriptor(IConfigurationElement element, boolean instantiateFactory) throws CoreException { id = element.getAttribute("id"); //$NON-NLS-1$ name = element.getAttribute("name"); //$NON-NLS-1$ description = element.getAttribute("description"); //$NON-NLS-1$ argumentType = element.getAttribute("argumentType"); //$NON-NLS-1$ if (argumentType == null) argumentType = IFilterMatcherDescriptor.ARGUMENT_TYPE_NONE; this.element = element; String ordering = element.getAttribute("ordering"); //$NON-NLS-1$ if (ordering != null) isFirst = ordering.equals("first"); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#getId() */ public String getId() { return id; } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#getName() */ public String getName() { return name; } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#getDescription() */ public String getDescription() { return description; } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#getArgumentType() */ public String getArgumentType() { return argumentType; } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#getFactory() */ public AbstractFileInfoMatcher createFilter() { try { return (AbstractFileInfoMatcher) element.createExecutableExtension("class"); //$NON-NLS-1$ } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /* (non-Javadoc) * @see org.eclipse.core.resources.IFilterDescriptor#isFirstOrdering() */ public boolean isFirstOrdering() { return isFirst; } }
huahang/sandbox
thirdparty/grpc/support/sync_custom.h
#include "thirdparty/grpc-1.19.1/include/grpc/support/sync_custom.h"
pncampbell/ct-calcs-old
src/test/scala/uk/gov/hmrc/ct/ct600a/LP03Spec.scala
<reponame>pncampbell/ct-calcs-old /* * Copyright 2016 HM Revenue & Customs * * 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 uk.gov.hmrc.ct.ct600a import org.joda.time.LocalDate import org.scalatest.{Matchers, WordSpec} import uk.gov.hmrc.ct.ct600a.v2.formats.Loans import uk.gov.hmrc.ct.ct600a.v2.{WriteOff, LP03} class LP03Spec extends WordSpec with Matchers { "LP03 to json" should { "create valid json for a single writeoff using only required fields " in { val lp03 = LP03(writeOffs = Some(List(WriteOff("123", 1, new LocalDate(2012, 3, 1))))) Loans.toJsonString(lp03) shouldEqual """{"writeOffs":[{"loanId":"123","amountWrittenOff":1,"dateWrittenOff":"2012-03-01"}]}""" } "create valid json for multiple loans" in { val lp03 = LP03(writeOffs = Some(List(WriteOff("123", 1, new LocalDate(2012, 3, 1)), WriteOff("456", 1, new LocalDate(2014, 3, 1))) )) Loans.toJsonString(lp03) shouldEqual """{"writeOffs":[{"loanId":"123","amountWrittenOff":1,"dateWrittenOff":"2012-03-01"},{"loanId":"456","amountWrittenOff":1,"dateWrittenOff":"2014-03-01"}]}""" } "create valid json for empty list of loans and not blow up!" in { val lp03 = LP03() Loans.toJsonString(lp03) shouldEqual """{}""" } "be added to another LP03" in { val lp03a = LP03(writeOffs = Some(List(WriteOff("123", 1, new LocalDate(2014, 4, 4))))) val lp03b = LP03(writeOffs = Some(List(WriteOff("456", 1, new LocalDate(2012, 3, 1))))) val expected = LP03(writeOffs = Some(List(WriteOff("123", 1, new LocalDate(2014, 4, 4)), WriteOff("456", 1, new LocalDate(2012, 3, 1))))) lp03a + lp03b shouldBe expected } } "LP03 from json" should { "create LP03 with single write off " in { Loans.lp03FromJsonString("""{"writeOffs":[{"loanId":"123","amountWrittenOff":1,"dateWrittenOff":"2012-03-01"}]}""") shouldBe LP03(writeOffs = Some(List(WriteOff("123", 1, new LocalDate(2012, 3, 1))))) } "create LP03 with multiple write offs " in { val expected = LP03(Some(List(WriteOff("123", 1, new LocalDate(2012, 3, 1)), WriteOff("456", 1, new LocalDate(2014, 3, 1))))) Loans.lp03FromJsonString("""{"writeOffs":[{"loanId":"123","amountWrittenOff":1,"dateWrittenOff":"2012-03-01"},{"loanId":"456","amountWrittenOff":1,"dateWrittenOff":"2014-03-01"}]}""") shouldBe expected } "create valid json for empty list of loans and not blow up 2!" in { Loans.lp03FromJsonString("{}") shouldEqual LP03() } } }
Cabrra/Engine-Development
FSGDEngine-Student/FSGDGame/TurretBehavior.h
#pragma once #include "../EDGOCA/BehaviorT.h" namespace Behaviors { class TurretBehavior : public EDGOCA::BehaviorT<TurretBehavior> { public: TurretBehavior(void) { baseSpeed = 15.0f; } ~TurretBehavior(void) {} static void PopulateMessageMap(void); static void OnRotateRight( EDGOCA::IBehavior* invokingBehavior, EDGOCA::IMessage* message); static void OnRotateLeft( EDGOCA::IBehavior* invokingBehavior, EDGOCA::IMessage* message ); static void OnRightStick( EDGOCA::IBehavior* pInvokingBehavior, EDGOCA::IMessage* msg); private: float baseSpeed; float ComputeRotateSpeed(); }; }
Mng12345/betterplot
betterplot-model/src/main/java/com/zhangm/betterplot/entity/Title.java
<filename>betterplot-model/src/main/java/com/zhangm/betterplot/entity/Title.java package com.zhangm.betterplot.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @Author zhangming * @Date 2020/6/21 18:30 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Title implements Serializable { private String text; }
cfc-kata/cfc-kata-team-b
src/main/java/com/cfckata/response/RepaymentBatchResponse.java
package com.cfckata.response; import java.util.List; public class RepaymentBatchResponse { private List<RepaymentCreatedResponse> successItems; private List<RepaymentFailedResponse> failedItems; public List<RepaymentCreatedResponse> getSuccessItems() { return successItems; } public void setSuccessItems(List<RepaymentCreatedResponse> successItems) { this.successItems = successItems; } public List<RepaymentFailedResponse> getFailedItems() { return failedItems; } public void setFailedItems(List<RepaymentFailedResponse> failedItems) { this.failedItems = failedItems; } }
vahndi/probability
examples/distributions/continuous/comparisons.py
<reponame>vahndi/probability import matplotlib.pyplot as plt from math import sqrt from numpy import arange from examples.colors import ML_APP_DARK_BLUE from probability.distributions import Normal, Laplace from probability.distributions.continuous.students_t import StudentsT x = arange(-4, 4.01, 0.05) def plot_normal_students_t_laplace(): """ Machine Learning: A Probabilistic Perspective. Figure 2.7 """ _, axes = plt.subplots(ncols=2, figsize=(16, 9)) # define distributions normal = Normal(mu=0, sigma=1) students_t = StudentsT(nu=1) laplace = Laplace(mu=0, b=1 / sqrt(2)) # plot pdfs ax = axes[0] normal.plot(x=x, ls=':', color='black', ax=ax) students_t.plot(x=x, ls='--', color=ML_APP_DARK_BLUE, ax=ax) laplace.plot(x=x, ls='-', color='red', ax=ax) ax.set_ylim(0, 0.8) ax.legend(loc='upper right') # plot log-pdfs ax = axes[1] normal.log_pdf().plot(x=x, ls=':', color='black', ax=ax) students_t.log_pdf().plot(x=x, ls='--', color=ML_APP_DARK_BLUE, ax=ax) laplace.log_pdf().plot(x=x, ls='-', color='red', ax=ax) ax.set_ylim(-9, 0) ax.legend(loc='upper right') plt.show() if __name__ == '__main__': plot_normal_students_t_laplace()
kmunve/APS
aps/plotting/new_snow_line_plot.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('seaborn-notebook') plt.rcParams['figure.figsize'] = (14, 12) REGION_ID = 3034 # Load data for new snow line calculated in *new_snow_line.py* nsl = pd.read_csv(r"C:\Users\kmu\PycharmProjects\APS\aps\scripts\tmp\new_snow_line_{0}_20201201_20210531.csv".format(REGION_ID), sep=";", parse_dates=['Date']) nsl['Altitude_nsl'] = np.clip(nsl['Altitude'], a_min=0, a_max=None) # group by day and keep only the highest value of 00, 06, 12, or 18 o'clock nsl_gr = nsl.groupby(by='Date', as_index=False).max() # Load data for new snow line from APS db # Used for extraction: exec GetTimeSerieData @RegionId='3034.0', @parameter='2014', @FromDate='2020-12-01', @ToDate='2021-05-31', @Model='met_obs_v2.0' db = pd.read_csv(r"C:\Users\kmu\PycharmProjects\APS\aps\scripts\tmp\{0}_newsnowline2021.csv".format(REGION_ID), sep=";", parse_dates=['Time']) db['Altitude_wetB'] = np.clip(db['Value'], a_min=0, a_max=None) db['Date'] = db['Time'].apply(lambda x: pd.Timestamp(x.date())) db['Hour'] = db['Time'].apply(lambda x: x.hour) # group by day and keep only the highest value of 00, 06, 12, or 18 o'clock db_gr = db.groupby(by='Date', as_index=False).max() # Load data for 0-isotherm from APS db db_0iso = pd.read_csv(r"C:\Users\kmu\PycharmProjects\APS\aps\scripts\tmp\{0}_0isoterm2021.csv".format(REGION_ID), sep=";", parse_dates=['Time']) db_0iso['Altitude_0iso'] = np.clip(db_0iso['Value'], a_min=0, a_max=None) db_0iso['Date'] = db_0iso['Time'].apply(lambda x: pd.Timestamp(x.date())) db_0iso['Hour'] = db_0iso['Time'].apply(lambda x: x.hour) # group by day and keep only the highest value of 00, 06, 12, or 18 o'clock db_0iso_gr = db_0iso.groupby(by='Date', as_index=False).max() # Load varsom-data containing published mountain-weather aw2 = pd.read_csv(r"C:\Users\kmu\PycharmProjects\varsomdata\varsomdata\{0}_forecasts_20_21.csv".format(REGION_ID), sep=";", header=0, index_col=0, parse_dates=['valid_from', 'date_valid']) aw2['Date'] = aw2['date_valid'] _merged = pd.merge(nsl_gr, db_gr, how='left', on='Date', suffixes=['_nsl', '_wetB']) _merged2 = pd.merge(_merged, db_0iso_gr, how='left', on='Date', suffixes=['_nsl', '_APSwetB']) _merged3 = pd.merge(_merged2, aw2, how='left', on='Date', suffixes=['_nsl', '_APS0iso']) _merged3.set_index('Date', inplace=True) fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True) _merged3.filter(['mountain_weather_freezing_level', 'Altitude_nsl']).plot.area(alpha=0.5, stacked=False, ax=ax1, title=REGION_ID) _merged3.filter(['mountain_weather_freezing_level', 'Altitude_wetB']).plot.area(alpha=0.5, stacked=False, ax=ax2) _merged3.filter(['mountain_weather_freezing_level', 'Altitude_0iso']).plot.area(alpha=0.5, stacked=False, ax=ax3) _merged3['diff_nsl'] = _merged3['mountain_weather_freezing_level'] - _merged3['Altitude_nsl'] _merged3['diff_wetB'] = _merged3['mountain_weather_freezing_level'] - _merged3['Altitude_wetB'] _merged3['diff_0iso'] = _merged3['mountain_weather_freezing_level'] - _merged3['Altitude_0iso'] plt.tight_layout() #plt.grid() plt.savefig('{0}_nsl_comparison.png'.format(REGION_ID), dpi=90) plt.show() print(_merged3['diff_nsl'].mean(), _merged3['diff_nsl'].std()) print(_merged3['diff_wetB'].mean(), _merged3['diff_wetB'].std()) print(_merged3['diff_0iso'].mean(), _merged3['diff_0iso'].std()) print(_merged3['diff_nsl'].where(_merged3['mountain_weather_precip_region'] > 1.0).describe()) print(_merged3['diff_wetB'].where(_merged3['mountain_weather_precip_region'] > 1.0).describe()) print(_merged3['diff_0iso'].where(_merged3['mountain_weather_precip_region'] > 1.0).describe()) print(nsl['Date'].iloc[0]) print(aw2['Date'].iloc[0]) print(db_gr['Date'].iloc[0]) print(db_0iso_gr['Date'].iloc[0]) print(nsl['Date'].iloc[-1]) print(aw2['Date'].iloc[-1]) print(db_gr['Date'].iloc[-1]) print(db_0iso_gr['Date'].iloc[-1])
platybrowser/mobie-python
mobie/migration/migrate_dataset.py
import argparse from .migrate_v1.migrate_dataset import migrate_dataset_to_mobie as migrate_dataset_v1 from .migrate_v2 import migrate_dataset as migrate_dataset_v2 def main(): parser = argparse.ArgumentParser(description="Migrate dataset to newer spec version.") parser.add_argument('folder', type=str) msg = """Migration script version: choose one of 1) migrate from platybrowser spec to MoBIE spec 0.1 2) migrate spec 0.1 to 0.2""" parser.add_argument('--version', '-v', type=int, default=2, help=msg) parser.add_argument('--anon', type=int, default=1) args = parser.parse_args() version = args.version if version == 1: migrate_dataset_v1(args.folder, bool(args.anon)) elif version == 2: migrate_dataset_v2(args.folder) else: raise ValueError(f"Invalid version {version}") if __name__ == '__main__': main()
hardikpedia/IEEE-Megaproject
Bitastik/pages/calender/index.js
<gh_stars>1-10 import ReactBigCalendar from "../../components/calender/ReactBigCalendar" import React from 'react' import MotionHoc from "../../components/animation/Motionhoc" import Books from '../../assets/books.jpg' const CalendarComponents=()=> { return ( <div style={{ width: '90vw', color: "black", backgroundColor: "#b8c6db", backgroundImage: "linear-gradient(315deg, #b8c6db 0%, #f5f7fa 74%)", borderRadius:"15px", padding:"20px", overflow:"hidden", // backgroundImage:`url(${Books})` }}> <ReactBigCalendar /> </div> ) } export default CalendarComponents
IronLanguages/rubyspec
1.8/core/enumerable/each_with_index_spec.rb
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "Enumerable#each_with_index" do before :each do @b = [2, 5, 3, 6, 1, 4] end it "passes each element and its index to block" do @a = [] EnumerableSpecs::Numerous.new.each_with_index { |o, i| @a << [o, i] } @a.should == [[2, 0], [5, 1], [3, 2], [6, 3], [1, 4], [4, 5]] end it "provides each element to the block" do acc = [] obj = EnumerableSpecs::EachDefiner.new() res = obj.each_with_index {|a,i| acc << [a,i]} acc.should == [] obj.should == res end it "provides each element to the block and its index" do acc = [] res = @b.each_with_index {|a,i| acc << [a,i]} [[2, 0], [5, 1], [3, 2], [6, 3], [1, 4], [4, 5]].should == acc @b.should == res end it "binds splat arguments properly" do acc = [] res = @b.each_with_index { |*b| c,d = b; acc << c; acc << d } [2, 0, 5, 1, 3, 2, 6, 3, 1, 4, 4, 5].should == acc @b.should == res end end
Vavilon3000/icq
gui/main_window/contact_list/SearchDropDown.h
<reponame>Vavilon3000/icq #pragma once namespace Ui { class ActionButton; class SearchWidget; class CustomButton; class SearchDropdown : public QWidget { Q_OBJECT enum class pencilIcon { pi_pencil, pi_cross }; public Q_SLOTS: void showPlaceholder(); void showMenuFull(); void showMenuAddContactOnly(); private Q_SLOTS: void createChat(); void addContact(); void onSearchActiveChanged(bool _isActive); void onPencilClicked(); public: SearchDropdown(QWidget* _parent, SearchWidget* _searchWidget, CustomButton* _pencil); void updatePencilIcon(const pencilIcon _pencilIcon); protected: virtual void hideEvent(QHideEvent *_event) override; private: SearchWidget* searchWidget_; CustomButton* searchPencil_; QWidget* menuWidget_; ActionButton* addContact_; ActionButton* createGroupChat_; ActionButton* createChannel_; ActionButton* createLiveChat_; QWidget* placeholderUseSearch_; }; }
basil/elastest-plugin
src/main/java/jenkins/plugins/elastest/submitters/ElasTestSubmitter.java
/* * The MIT License * * (C) Copyright 2017-2019 ElasTest (http://elastest.io/) * * 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. */ package jenkins.plugins.elastest.submitters; import java.io.IOException; import java.util.List; import jenkins.plugins.elastest.json.ExternalJob; /** * * @author <NAME> * @since 0.0.1 */ public interface ElasTestSubmitter { static enum SubmitterType { LOGSTASH("logstash"); private final String name; private SubmitterType(String s) { name = s; } public boolean equalsName(String otherName) { return name.equals(otherName); } public String toString() { return this.name; } } String getDescription(); SubmitterType getSubmitterType(); /** * Sends the log data to ElasTest. * * @param data * The serialized data, not null * @throws java.io.IOException * The data is not written to the server */ boolean push(String data) throws IOException; /** * Bulds a String playload compatible with the Logstash input. * * @param logLines * @param externalJob * @return */ String buildPayload(List<String> logLines, ExternalJob externalJob); /** * Bulds a String playload compatible with the Logstash input. * * @param message * @param externalJob * @return */ String buildPayload(String message, ExternalJob externalJob); }
TheBadZhang/OJ
usx/special/92/9224.c
<reponame>TheBadZhang/OJ #include <stdio.h> int main () { int T, m, n, i, mini; scanf ("%d", &T); while (T--) { scanf ("%d %d %d", &m, &n, &i); printf ("%d %d\n", n+i*m, i); } return 0; }
mikolajgucki/ae-engine
engine/common/luaprofiler/src/cpp/include/luap_StackItem.h
#ifndef AE_LUAP_STACK_ITEM_H #define AE_LUAP_STACK_ITEM_H /** */ typedef struct { /** */ long startTime; /** */ long startUsedMemory; /** */ long subcallsMemoryAllocated; } luap_StackItem; /** */ luap_StackItem *luap_CreateStackItem(); /** */ void luap_DeleteStackItem(luap_StackItem *item); #endif // AE_LUAP_STACK_ITEM_H
SciCompInc/hls_montecarlo
mcSVEqLinkStructNoteQ/vs_openmp/test.cpp
<reponame>SciCompInc/hls_montecarlo #include "catch2/catch.hpp" #include <iomanip> #include <iostream> #include <pricer_host.h> TEST_CASE("test11", "[hls]") { mcSVEqLinkStructNote pricer; pricer.load_inputs(); int pmax = 1 << 10; int seq = 1; int nsub = 4; double V, dev; double tk; pricer.calc(pmax, seq, nsub, V, dev, tk); double V_ref = 9464.1630859375; CHECK(V == Approx(V_ref).epsilon(0.000001)); INFO("Kernel time: " << tk << " ms"); CHECK(true); } TEST_CASE("test13", "[.][integration]") { double ctable_ref[][3] = {{16384, 9445.2792968750, 12.2280696165}, {32768, 9448.7847167969, 9.9039921271}, {65536, 9449.5662109375, 9.7391229381}, {131072, 9449.6002929687, 5.8395357108}, {262144, 9452.0356933594, 2.8051552449}, {524288, 9455.8560546875, 2.1083290403}, {1048576, 9455.8576660156, 1.6502308695}}; // Scrambled Sobol //{ 16384, 9449.5375976563, 11.8104653618}, //{ 32768, 9451.4765625000, 10.4761420499 }, //{ 65536, 9449.7967773438, 8.9634402288 }, //{ 131072, 9449.7084960938, 4.1855949456 }, //{ 262144, 9452.7068359375, 3.3358144335 }, //{ 524288, 9455.7122558594, 2.6232835375 }, //{ 1048576, 9455.6075683594, 1.6183692420 }, int ntable = sizeof(ctable_ref) / sizeof(double) / 3; double V_ref = 9455.8576660156; // pmax = 2^20 mcSVEqLinkStructNote pricer; pricer.load_inputs(); int seq = 1; int nsub = 4; double V, dev; double tk; std::cout << std::endl; std::cout << "pmax" << "\t" << "V" << "\t" << "dev" << "\t" << "|V - V_ref|" << "\t" << "Conf. Interval" << std::endl; int nseries = 20; for (int p = 0; p < ntable; p++) { int pmax = int(ctable_ref[p][0]); double sum = 0; double sum2 = 0; for (int k = 1; k <= nseries; k++) { pricer.calc(pmax, k, nsub, V, dev, tk); sum += V; sum2 += V * V; } sum /= nseries; V = sum; sum2 /= nseries; dev = sqrt(sum2 - sum * sum); std::string chk = "FAIL"; if (2.807 * dev > std::fabs(V - V_ref)) // 99.5% conf interval { chk = "OK"; } // std::cout << std::setw(10) << std::fixed << std::setprecision(10) << // pmax << "\t" << V << "\t" << dev << "\t" << std::fabs(V - V_ref) << // "\t" << chk << std::endl; std::cout << std::setw(10) << std::fixed << std::setprecision(10) << "{ " << pmax << ",\t" << V << ",\t" << dev << "}," << std::endl; REQUIRE(V == Approx(ctable_ref[p][1]).epsilon(0.00001)); REQUIRE(dev == Approx(ctable_ref[p][2]).epsilon(0.001)); } }
dalaro/tinkerpop3
gremlin-core/src/main/java/com/tinkerpop/gremlin/process/graph/step/map/SelectOneStep.java
package com.tinkerpop.gremlin.process.graph.step.map; import com.tinkerpop.gremlin.process.Traversal; import com.tinkerpop.gremlin.process.Traverser; import java.util.Arrays; import java.util.Map; import java.util.function.Function; /** * @author <NAME> (http://markorodriguez.com) */ public final class SelectOneStep<S, E> extends SelectStep { private final Function<Traverser<S>, Map<String, E>> tempFunction; public SelectOneStep(final Traversal traversal, final String selectLabel, final Function stepFunction) { super(traversal, Arrays.asList(selectLabel), stepFunction); this.tempFunction = this.selectFunction; this.setFunction(traverser -> this.tempFunction.apply(((Traverser<S>) traverser)).get(selectLabel)); } }
orekyuu/dd-trace-rb
integration/apps/rails-five/config/initializers/datadog.rb
<gh_stars>100-1000 require 'ddtrace' Datadog.configure do |c| c.diagnostics.debug = true if Datadog::DemoEnv.feature?('debug') c.analytics_enabled = true if Datadog::DemoEnv.feature?('analytics') c.runtime_metrics.enabled = true if Datadog::DemoEnv.feature?('runtime_metrics') if Datadog::DemoEnv.feature?('tracing') c.use :rails, service_name: 'acme-rails-five' c.use :redis, service_name: 'acme-redis' c.use :resque, service_name: 'acme-resque' end if Datadog::DemoEnv.feature?('pprof_to_file') # Reconfigure transport to write pprof to file c.profiling.exporter.transport = Datadog::DemoEnv.profiler_file_transport end end
ciscochus/inmo
src/main/java/com/uoc/inmo/command/inmueble/CreateInmuebleCommand.java
<reponame>ciscochus/inmo<gh_stars>0 package com.uoc.inmo.command.inmueble; import java.util.List; import java.util.UUID; import com.uoc.inmo.command.BaseCommand; import com.uoc.inmo.command.api.request.RequestFile; import lombok.Data; @Data public class CreateInmuebleCommand extends BaseCommand<UUID> { public String title; public String address; public double price; public double area; public String type; public Boolean garage; public Boolean pool; public Integer rooms; public Integer baths; public String description; public String email; public List<RequestFile> images; public CreateInmuebleCommand(){ super(UUID.randomUUID()); } public CreateInmuebleCommand(UUID id){ super(id); } public CreateInmuebleCommand(String title, String address, double price, double area, String type, Boolean garage, Boolean pool, Integer rooms, Integer baths, String description, String email) { super(UUID.randomUUID()); this.title = title; this.address = address; this.price = price; this.area = area; this.type = type; this.garage = garage; this.pool = pool; this.rooms = rooms; this.baths = baths; this.description = description; this.email = email; } }
hityc2019/servicecomb-service-center
datasource/mongo/client/mongo_test.go
<filename>datasource/mongo/client/mongo_test.go package client import ( "context" "testing" "github.com/go-chassis/go-chassis/v2/storage" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) const ( TESTCOL = "test" ) func init() { config := storage.Options{ URI: "mongodb://localhost:27017", } NewMongoClient(config) } func TestInsert(t *testing.T) { insertRes, err := GetMongoClient().Insert(context.Background(), TESTCOL, bson.M{ "instance": "instance1", "number": 123, }) if err != nil { t.Fatalf("TestMongoInsert failed, %#v", err) } res, err := GetMongoClient().Find(context.Background(), TESTCOL, bson.M{"_id": insertRes.InsertedID}) if err != nil { t.Fatalf("TestMongoInsert check insert result failed, %#v", err) } var result bson.M var flag bool for res.Next(context.Background()) { err := res.Decode(&result) if err != nil { t.Fatalf("TestMongoInsert decode result failed, %#v", err) } flag = true } if !flag { t.Fatalf("TestMongoInsert check res failed, can't get insert doc") } } func TestBatchInsert(t *testing.T) { insertRes, err := GetMongoClient().BatchInsert(context.Background(), TESTCOL, []interface{}{bson.M{"instance": "instance2"}, bson.M{"instance": "instance3"}}) if err != nil { t.Fatalf("TestMongoBatchInsert failed, %#v", err) } res, err := GetMongoClient().Find(context.Background(), TESTCOL, bson.M{"_id": bson.M{"$in": insertRes.InsertedIDs}}) if err != nil { t.Fatalf("TestBatchMongoInsert query mongdb failed, %#v", err) } var result []bson.M for res.Next(context.Background()) { var doc bson.M err := res.Decode(&doc) if err != nil { t.Fatalf("TestBatchInsert decode result failed, %#v", err) } result = append(result, doc) } if len(result) != 2 { t.Fatalf("TestBatchInsert check result failed") } } func TestDelete(t *testing.T) { insertRes, err := GetMongoClient().Insert(context.Background(), TESTCOL, bson.M{"instance": "instance4"}) if err != nil { t.Fatalf("TestMongoDelete insert failed, %#v", err) } deleteRes, err := GetMongoClient().Delete(context.Background(), TESTCOL, bson.M{"_id": insertRes.InsertedID}) if err != nil { t.Fatalf("TestMongoDelete delte failed, %#v", err) } if deleteRes.DeletedCount != 1 { t.Fatalf("TestDelete check deleteRes failed") } } func TestBatchDelete(t *testing.T) { insertRes, err := GetMongoClient().BatchInsert(context.Background(), TESTCOL, []interface{}{bson.M{"instance": "instance5"}, bson.M{"instance": "instance6"}}) if err != nil { t.Fatalf("TestMongoBatchDelete insert failed, %#v", err) } var wm []mongo.WriteModel for _, id := range insertRes.InsertedIDs { filter := bson.M{"_id": id} model := mongo.NewDeleteManyModel().SetFilter(filter) wm = append(wm, model) } batchDelRes, err := GetMongoClient().BatchDelete(context.Background(), TESTCOL, wm) if err != nil { t.Fatalf("TestBatchDelete batchDelete failed, %#v", err) } if batchDelRes.DeletedCount != 2 { t.Fatalf("TestBatchDelete check result failed") } } func TestUpdate(t *testing.T) { insertRes, err := GetMongoClient().Insert(context.Background(), TESTCOL, bson.M{ "instance": "instance7", }) if err != nil { t.Fatalf("TestMongoUpdate insert failed, %#v", err) } filter := bson.M{"_id": insertRes.InsertedID} update := bson.M{"$set": bson.M{"add": 1}} updateRes, err := GetMongoClient().Update(context.Background(), TESTCOL, filter, update) if err != nil { t.Fatalf("TestMongoUpdate update failed,%#v", err) } if updateRes.ModifiedCount != 1 { t.Fatalf("TestMongoUpdate check result failed,%#v", err) } }
turlodales/theos-projects
app_dumps/VKClient.folder/ActionOptionsProviderGift.h
<reponame>turlodales/theos-projects /** * This header is generated by class-dump-z 0.2-0. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import "ActionOptionsProviderActionBuilder.h" @class VKGiftListObject; __attribute__((visibility("hidden"))) @interface ActionOptionsProviderGift : ActionOptionsProviderActionBuilder { VKGiftListObject* _gift; } @property(readonly, assign, nonatomic) VKGiftListObject* gift; +(id)gift:(id)gift; -(void).cxx_destruct; -(void)fillOptionsForBuilder:(id)builder context:(id)context; -(id)initWithGift:(id)gift; @end
gribdesbois/ganister-test-react
vite-project/spec/relationships/00-get-relationships.spec.js
require('mocha'); const chai = require('chai'); const chaiHttp = require('chai-http'); const app = require('../../index'); const { mockNodetype, readDatamodel } = require('../helpers'); chai.use(chaiHttp); const { expect } = chai; const API_URL = '/api/v0'; const nodetypeName = 'part'; let targetNodetypeName; let relationshipName; describe('Get relationships', () => { before(async function () { const datamodel = readDatamodel(); const { nodetypeDefinitions } = datamodel; const sourceNodetypeDM = nodetypeDefinitions.find((nodetype) => { return nodetype.name === nodetypeName; }); let relationshipDirection; const relationshipDM = nodetypeDefinitions.find((nodetype) => { const { elementType, directions, hidden } = nodetype; if (elementType === 'node' || hidden) return; relationshipDirection = directions.find((d) => d.source === sourceNodetypeDM.id); return relationshipDirection; }); const targetNodetypeDM = nodetypeDefinitions.find((nodetype) => { return nodetype.id === relationshipDirection.target; }); relationshipName = relationshipDM.name; targetNodetypeName = targetNodetypeDM.name; const nodetypesNames = [nodetypeName, relationshipName, targetNodetypeName]; nodetypesNames.forEach((name) => { const nodetypeDM = nodetypeDefinitions.find((n) => n.name === name); const { elementType, properties } = nodetypeDM; const mandatoryProperties = properties .filter((p) => p.mandatory || p.generated) .map((p) => p.name); if (elementType === 'node') { mandatoryProperties.push('_tracked'); } this[`${name}MandatoryProperties`] = mandatoryProperties; }); }); beforeEach(async function () { const sourceBody = mockNodetype(nodetypeName); const sourceResponse = await chai .request(app) .post(`${API_URL}/nodes/${nodetypeName}`) .set('Authorization', this.token) .send(sourceBody); expect(sourceResponse.status).eql(200); this.source = sourceResponse.body.data; const targetBody = mockNodetype(targetNodetypeName); const targetResponse = await chai .request(app) .post(`${API_URL}/nodes/${targetNodetypeName}`) .set('Authorization', this.token) .send(targetBody); expect(targetResponse.status).eql(200); this.target = targetResponse.body.data; const relationshipBody = mockNodetype(relationshipName); relationshipBody.source = this.source; relationshipBody.target = this.target; const relationshipResponse = await chai .request(app) .post(`${API_URL}/nodes/${this.source._type}/${this.source._id}/relationships/${relationshipName}`) .set('Authorization', this.token) .send(relationshipBody); expect(relationshipResponse.status).eql(200); this.relationship = relationshipResponse.body.data; }); context("nodetype's relationships", () => { it('gets relationships', async function () { const response = await chai .request(app) .get(`${API_URL}/nodes/${this.source._type}/relationships/${this.relationship._type}`) .set('Authorization', this.token); expect(response.status).eql(200); const { data, errors } = response.body; expect(errors).to.be.an('array').and.to.have.lengthOf(0); expect(data).to.be.an('array').and.to.have.lengthOf.at.most(1); expect(data[0]).to.be.an('object'); expect(data[0]._type).to.be.eql(this.relationship._type); expect(data[0]._id).to.be.eql(this.relationship._id); expect(data[0].properties).to.be.an('object'); expect(data[0].properties).to.include(this.relationship.properties); expect(data[0].source).to.be.an('object'); expect(data[0].source._type).to.be.eql(this.source._type); expect(data[0].source._id).to.be.eql(this.source._id); expect(data[0].source.properties).to.be.an('object'); expect(data[0].target).to.be.an('object'); expect(data[0].target._type).to.be.eql(this.target._type); expect(data[0].target._id).to.be.eql(this.target._id); expect(data[0].target.properties).to.be.an('object'); }); }); context("node's relationships", () => { it('gets relationships', async function () { const response = await chai .request(app) .get(`${API_URL}/nodes/${this.source._type}/${this.source._id}/relationships/${this.relationship._type}`) .set('Authorization', this.token); expect(response.status).eql(200); const { data, errors } = response.body; expect(errors).to.be.an('array').and.to.have.lengthOf(0); expect(data) .to.be.an('array') .and.to.have.lengthOf.at.most(1); expect(data[0]).to.be.an('object'); expect(data[0]._type).to.be.eql(this.relationship._type); expect(data[0]._id).to.be.eql(this.relationship._id); expect(data[0].properties).to.be.an('object'); expect(data[0].properties).to.include(this.relationship.properties); expect(data[0].source).to.be.an('object'); expect(data[0].source._type).to.be.eql(this.source._type); expect(data[0].source._id).to.be.eql(this.source._id); expect(data[0].source.properties).to.be.an('object'); expect(data[0].target).to.be.an('object'); expect(data[0].target._type).to.be.eql(this.target._type); expect(data[0].target._id).to.be.eql(this.target._id); expect(data[0].target.properties).to.be.an('object'); }); it('searches relationships', async function () { delete this.relationship.user; const body = { relationships: [this.relationship._type] }; const response = await chai .request(app) .post(`${API_URL}/nodes/${this.source._type}/${this.source._id}/relationships`) .set('Authorization', this.token) .send(body); expect(response.status).eql(200); const { data, errors } = response.body; expect(errors).to.be.an('array').and.to.have.lengthOf(0); expect(data) .to.be.an('array') .and.to.have.lengthOf.at.most(1); expect(data[0]).to.be.an('object'); expect(data[0]._type).to.be.eql(this.relationship._type); expect(data[0]._id).to.be.eql(this.relationship._id); expect(data[0].properties).to.be.an('object'); expect(data[0].properties).to.include(this.relationship.properties); expect(data[0].source).to.be.an('object'); expect(data[0].source._type).to.be.eql(this.source._type); expect(data[0].source._id).to.be.eql(this.source._id); expect(data[0].source.properties).to.be.an('object'); expect(data[0].target).to.be.an('object'); expect(data[0].target._type).to.be.eql(this.target._type); expect(data[0].target._id).to.be.eql(this.target._id); expect(data[0].target.properties).to.be.an('object'); }); }); });
thinkpractice/bme
Src/NudgeMessageItem.cpp
#ifndef NUDGE_MESSAGE_ITEM_H #include "NudgeMessageItem.h" #endif NudgeMessageItem::NudgeMessageItem(ConvMessage* message) : MessageItem(message) { } NudgeMessageItem::~NudgeMessageItem() { } void NudgeMessageItem::DrawItem(BView* owner, BRect itemRect, bool drawEverything) { } void NudgeMessageItem::Update(BView* owner, const BFont* font) { }
straill7/wc-code-migration-tool
plugin-qcheck.core/src/com/ibm/commerce/qcheck/core/comment/Tag.java
package com.ibm.commerce.qcheck.core.comment; /* *----------------------------------------------------------------- * Copyright 2018 <NAME> * * 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. *----------------------------------------------------------------- */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.TagElement; import com.ibm.commerce.qcheck.core.ValidatorResource; /** * Tag represents a tag in a Java doc comment, such as a <code>param</code> or * <code>return</code> tag. * * @author <NAME> */ public class Tag extends CommentElement { /** * The name of the tag. This always exists. See {@link #getName} for * details. */ private CommentFragment name; /** * A further qualifier for the tag. For <code>@param</code> tags, this will * be the parameter name. For <code>@exception</code> tags, this will be the * exception name. See {@link #getSecondName} for details. */ private List<CommentFragment> secondName; /** * The description of the tag. See {@link #getComment} for details. */ private CommentDescription comment; /** * A list of all the fragments in this. Will never be null. */ private List<CommentFragment> allFragments; /** * Constructor for Tag with pre-processed values. * * @param newName * The name of the tag, such as <code>@param</code>. Cannot be * null. * @param newSecondName * A further qualifier for the tag. For <code>param</code> tags, * this will be the parameter name. For <code>exception</code> * tags, this will be the exception name. May be null. * @param newComment * The description of the tag. May be null to indicate there is * no description. * @param newFragments * The fragments of this tag. May be null to indicate that the * tag has no fragments. */ public Tag(CommentFragment newName, List<CommentFragment> newSecondName, CommentDescription newComment, List<CommentFragment> newFragments) { this.name = newName; this.secondName = newSecondName; this.comment = newComment; this.allFragments = newFragments != null ? newFragments : Collections.EMPTY_LIST; name.setTag(this); } /** * Constructor for Tag with a TagElement that must be examined. * * @param comp * The compiled form of the file with all ASTNodes and line * numbers available. Cannot be null. * @param element * The ASTNode which represents a Java doc tag. Cannot be null. */ public Tag(ValidatorResource resource, CompilationUnit comp, TagElement element) { int currentStartPosition = element.getStartPosition(); List<ASTNode> nodeList = new ArrayList<ASTNode>(); nodeList.add(element); CommentDescriptionBuilder builder = new CommentDescriptionBuilder(resource, nodeList, comp, true, element.getStartPosition(), element.getStartPosition() + element.getLength()); // find the tag created and copy the results boolean tagExists = false; for (CommentFragment fragment : builder.fragments) { Tag tag = fragment.getTag(); if (tag != null) { name = tag.name; secondName = tag.secondName; comment = tag.comment; allFragments = tag.allFragments; fragment.setTag(this); tagExists = true; break; } } if (!tagExists) { throw new IllegalStateException("CommentDescriptionBuilder did not attach " + "a Tag instance to the fragments created by a TagElement."); } } /** * Returns all fragments in this tag (including fragments within the * description). * * @return The fragments in this tag. Will not be null. */ public List<CommentFragment> getFragments() { return allFragments; } /** * Returns the name of this tag, such as <code>@param</code>. * * @return The name of this tag. Will not be null. */ public CommentFragment getName() { return name; } /** * Returns the qualifier for this tag. This will be null or non-null * depending on the type of tag: * <ul> * <li><code>@param</code> - Non-null. The name of the parameter. * <li><code>@return</code> - Null. * <li><code>@throws</code>, <code>exception</code> - Non-null. The class * name of the exception. * <li><code>@see</code> - Non-null. The class name that is referenced. * <li><code>@link</code> - Non-null. The class name that is referenced. * </ul> * * @return The qualifier for this tag. May be null depending on the tag * type. */ public List<CommentFragment> getSecondName() { return secondName; } /** * Returns the description for this tag. * * @return The description for this tag. May be null if there is no * description. */ public CommentDescription getComment() { return comment; } }
immersionroom/vee
vee/solve.py
<filename>vee/solve.py import re from vee.requirement import RequirementSet class SolveError(ValueError): pass def verbose(depth, step, *args): print('{}{}'.format(' ' * depth, step), *args) def solve(*args, **kwargs): """Solve abstract requirements into concrete provisions. :param RequirementSet requires: The abstract requirements to solve. :param Manifest manifest: Where to pull packages from. :return dict: Concrete provisions that satisfy the abstract requirements. :raises SolveError: if unable to satisfy the requirements. """ return next(iter_solve(*args, **kwargs), None) def iter_solve(requires, manifest, log=None): done = {} todo = list(RequirementSet.coerce(requires).items()) log = log or (lambda *args: None) return _solve(done, todo, manifest, log) def _solve(done, todo, manifest, log, depth=0): if not todo: yield done return name, reqs = todo[0] pkg = manifest.get(name) if pkg is None: raise SolveError("package {!r} does not exist".format(name)) log(depth, 'start', name, pkg) variants = pkg.flattened() for vi, var in enumerate(variants): log(depth, 'variant', vi, len(variants), var) failed = False # Make sure it satisfies all solved requirements. for prev in done.values(): req = prev.requires.get(name) if req and not var.provides.satisfies(req): log(depth, 'fail on existing', prev.name, req) failed = True break if failed: continue next_todo = [] for name2, req in var.requires.items(): pkg2 = done.get(name2) log(depth, 'requires', name2, req, pkg2) if pkg2 is None: # We need to solve this. # We don't grab it immediately, because we want to do a # breadth-first search. log(depth, 'to solve') next_todo.append((name2, req)) elif not pkg2.provides.satisfies(req): # This variant doesn't work with the already done packages; # move onto the next one. log(depth, 'fail variant') failed = True break if failed: continue # Go a step deeper. # We clone everything so that the call stack maintains the state we # need to keep going from here. next_done = done.copy() next_done[name] = var next_todo = todo[1:] + next_todo yield from _solve(next_done, next_todo, manifest, log, depth + 1)
MatthieuBlais/freeldep
core/status.py
import json from utils import Clients from utils import Deployer clients = Clients.get() CREATE_ACTIONS = ["UPDATE_STACK", "CREATE_OR_UPDATE_STACK", "CREATE_STACK"] DELETE_ACTIONS = ["DELETE_STACK"] def set_status(success): return "SUCCESS" if success and type(success) is bool else "FAIL" def create_handler(cfn, event): status = cfn.status(event["TemplateName"]) if status in cfn.CREATE_COMPLETE: event["Status"] = set_status(success=True) elif status in cfn.DEPLOY_FAILED: event["Status"] = set_status(success=False) else: event["Status"] = status def delete_handler(deployer, event): if deployer.exists(event["TemplateName"]): status = deployer.status(event["TemplateName"]) if status in deployer.DELETE_COMPLETE: event["Status"] = set_status(success=True) if status in deployer.DEPLOY_FAILED: event["Status"] = set_status(success=False) event["Status"] = status else: event["Status"] = set_status(success=True) def handler(event, context): print(json.dumps(event, indent=4)) deployer = Deployer.get(clients) if event["Action"] in CREATE_ACTIONS: create_handler(deployer, event) elif event["Action"] in DELETE_ACTIONS: delete_handler(deployer, event) return event
trusona/trusona-server-sdk-ruby
spec/trusona/identity_document_spec.rb
<gh_stars>1-10 # frozen_string_literal: true require 'spec_helper' RSpec.describe Trusona::IdentityDocument do describe 'findining identity documents for a user' do it 'requires a user identifier' do expect { Trusona::IdentityDocument.all(user_identifier: nil) }.to( raise_error(ArgumentError, 'A user identifier is required.') ) end it 'tells the worker to find all of the documents' do spy = double(Trusona::Workers::IdentityDocumentFinder) allow(Trusona::Workers::IdentityDocumentFinder).to( receive(:new).and_return(spy) ) expect(spy).to receive(:find_all).with('bob-123') Trusona::IdentityDocument.all(user_identifier: 'bob-123') end end describe 'finding a single identity document given an ID' do it 'requires a identity document identifier' do expect { Trusona::IdentityDocument.find(id: nil) }.to( raise_error( ArgumentError, 'An Identity Document identifier is required.' ) ) end it 'tells the worker to find that specific identity document' do spy = double(Trusona::Workers::IdentityDocumentFinder) allow(Trusona::Workers::IdentityDocumentFinder).to( receive(:new).and_return(spy) ) expect(spy).to receive(:find).with('dl-456') Trusona::IdentityDocument.find(id: 'dl-456') end end end
gonzus/pizza
base64.c
#include "base64.h" static const unsigned char enc_64[256] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 }; #define E64(c) (uint8_t)enc_64[(int)c] static const char dec_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; #define D64(c) (uint8_t)dec_64[(int)c] #define B64DEC1(s, p) (uint8_t)((E64(s.ptr[p+0]) << 2) | (E64(s.ptr[p+1]) >> 4)) #define B64DEC2(s, p) (uint8_t)((E64(s.ptr[p+1]) << 4) | (E64(s.ptr[p+2]) >> 2)) #define B64DEC3(s, p) (uint8_t)((E64(s.ptr[p+2]) << 6) | (E64(s.ptr[p+3]) >> 0)) int base64_decode(Slice encoded, Buffer *decoded) { uint32_t left = 0; while (left < encoded.len && E64(encoded.ptr[left]) < 64) { ++left; } int orig = decoded->len; uint32_t pos = 0; while (left > 4) { buffer_append_byte(decoded, B64DEC1(encoded, pos)); buffer_append_byte(decoded, B64DEC2(encoded, pos)); buffer_append_byte(decoded, B64DEC3(encoded, pos)); pos += 4; left -= 4; } if (left > 1) { buffer_append_byte(decoded, B64DEC1(encoded, pos)); } if (left > 2) { buffer_append_byte(decoded, B64DEC2(encoded, pos)); } if (left > 3) { buffer_append_byte(decoded, B64DEC3(encoded, pos)); } return decoded->len - orig; } #define B64PAD '=' #define B64ENC1x(s, p) ((s.ptr[p+0] >> 2) & 0x3F) #define B64ENC2a(s, p) ((s.ptr[p+0] & 0x03) << 4) #define B64ENC2b(s, p) ((s.ptr[p+1] & 0xF0) >> 4) #define B64ENC3a(s, p) ((s.ptr[p+1] & 0x0F) << 2) #define B64ENC3b(s, p) ((s.ptr[p+2] & 0xC0) >> 6) #define B64ENC4x(s, p) ((s.ptr[p+2] & 0x3F)) int base64_encode(Slice decoded, Buffer *encoded) { int orig = encoded->len; uint32_t pos = 0; while (pos < (decoded.len - 2)) { buffer_append_byte(encoded, D64(B64ENC1x(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC2a(decoded, pos) | B64ENC2b(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC3a(decoded, pos) | B64ENC3b(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC4x(decoded, pos))); pos += 3; } switch (decoded.len - pos) { // bytes left -- can be 0, 1 or 2 case 0: break; case 1: buffer_append_byte(encoded, D64(B64ENC1x(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC2a(decoded, pos))); buffer_append_byte(encoded, B64PAD); buffer_append_byte(encoded, B64PAD); break; case 2: buffer_append_byte(encoded, D64(B64ENC1x(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC2a(decoded, pos) | B64ENC2b(decoded, pos))); buffer_append_byte(encoded, D64(B64ENC3a(decoded, pos))); buffer_append_byte(encoded, B64PAD); break; } return encoded->len - orig; }
lechium/tvOS135Headers
Applications/TVMusic/TVMusicLibraryPlaylistsViewController.h
<reponame>lechium/tvOS135Headers // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13). // // Copyright (C) 1997-2019 <NAME>. // #import "TVMusicMPRequestViewController.h" #import "TVCollectionViewDelegate-Protocol.h" @class MPModelPlaylist, NSString; @interface TVMusicLibraryPlaylistsViewController : TVMusicMPRequestViewController <TVCollectionViewDelegate> { MPModelPlaylist *_parentPlaylistFolder; // 8 = 0x8 } - (void).cxx_destruct; // IMP=0x0000000100055fe0 @property(retain, nonatomic) MPModelPlaylist *parentPlaylistFolder; // @synthesize parentPlaylistFolder=_parentPlaylistFolder; - (id)cellForItemAtIndexPath:(id)arg1; // IMP=0x0000000100055c44 - (void)collectionView:(id)arg1 didReceiveLongPressForItemAtIndexPath:(id)arg2; // IMP=0x0000000100055bac - (_Bool)collectionView:(id)arg1 shouldHandleLongPressForItemAtIndexPath:(id)arg2; // IMP=0x0000000100055b0c - (void)collectionView:(id)arg1 didSelectItemAtIndexPath:(id)arg2; // IMP=0x00000001000558d8 - (void)_handlePlayPause:(id)arg1; // IMP=0x0000000100055674 - (void)didMoveToParentViewController:(id)arg1; // IMP=0x0000000100055668 - (void)viewDidLoad; // IMP=0x000000010005551c - (id)init; // IMP=0x000000010005550c - (id)initWithParentPlaylistFolder:(id)arg1; // IMP=0x0000000100055414 // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
zealoussnow/chromium
chrome/browser/password_manager/android/java/src/org/chromium/chrome/browser/password_manager/CredentialManagerLauncherFactoryImpl.java
<gh_stars>1000+ // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.password_manager; /** * Instantiable version of {@link CredentialManagerLauncherFactory}, don't add anything to this * class. Downstream provides an actual implementation. In the build files, we specify that * {@link CredentialManagerLauncherFactory} is compiled separately from its implementation; other * projects may specify a different PasswordStoreAndroidBackendFactory via GN. */ class CredentialManagerLauncherFactoryImpl extends CredentialManagerLauncherFactory {}
sotaoverride/backup
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/systemd/1_242+AUTOINC+db2e367bfc-r0/git/src/journal/journal-verify.c
<reponame>sotaoverride/backup /* SPDX-License-Identifier: LGPL-2.1+ */ #include "journal-verify.h" #include <fcntl.h> #include <stddef.h> #include <sys/mman.h> #include <unistd.h> #include "alloc-util.h" #include "compress.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "journal-authenticate.h" #include "journal-def.h" #include "journal-file.h" #include "lookup3.h" #include "macro.h" #include "terminal-util.h" #include "tmpfile-util.h" #include "util.h" static void draw_progress(uint64_t p, usec_t* last_usec) { unsigned n, i, j, k; usec_t z, x; if (!on_tty()) return; z = now(CLOCK_MONOTONIC); x = *last_usec; if (x != 0 && x + 40 * USEC_PER_MSEC > z) return; *last_usec = z; n = (3 * columns()) / 4; j = (n * (unsigned)p) / 65535ULL; k = n - j; fputs("\r", stdout); if (colors_enabled()) fputs("\x1B[?25l" ANSI_HIGHLIGHT_GREEN, stdout); for (i = 0; i < j; i++) fputs("\xe2\x96\x88", stdout); fputs(ANSI_NORMAL, stdout); for (i = 0; i < k; i++) fputs("\xe2\x96\x91", stdout); printf(" %3" PRIu64 "%%", 100U * p / 65535U); fputs("\r", stdout); if (colors_enabled()) fputs("\x1B[?25h", stdout); fflush(stdout); } static uint64_t scale_progress(uint64_t scale, uint64_t p, uint64_t m) { /* Calculates scale * p / m, but handles m == 0 safely, and saturates. * Currently all callers use m >= 1, but we keep the check to be defensive. */ if (p >= m || m == 0) // lgtm[cpp/constant-comparison] return scale; return scale * p / m; } static void flush_progress(void) { unsigned n, i; if (!on_tty()) return; n = (3 * columns()) / 4; putchar('\r'); for (i = 0; i < n + 5; i++) putchar(' '); putchar('\r'); fflush(stdout); } #define debug(_offset, _fmt, ...) \ do \ { \ flush_progress(); \ log_debug(OFSfmt ": " _fmt, _offset, ##__VA_ARGS__); \ } while (0) #define warning(_offset, _fmt, ...) \ do \ { \ flush_progress(); \ log_warning(OFSfmt ": " _fmt, _offset, ##__VA_ARGS__); \ } while (0) #define error(_offset, _fmt, ...) \ do \ { \ flush_progress(); \ log_error(OFSfmt ": " _fmt, (uint64_t)_offset, ##__VA_ARGS__); \ } while (0) #define error_errno(_offset, error, _fmt, ...) \ do \ { \ flush_progress(); \ log_error_errno(error, OFSfmt ": " _fmt, (uint64_t)_offset, \ ##__VA_ARGS__); \ } while (0) static int journal_file_object_verify(JournalFile* f, uint64_t offset, Object* o) { uint64_t i; assert(f); assert(offset); assert(o); /* This does various superficial tests about the length an * possible field values. It does not follow any references to * other objects. */ if ((o->object.flags & OBJECT_COMPRESSED_XZ) && o->object.type != OBJECT_DATA) { error(offset, "Found compressed object that isn't of type DATA, which " "is not allowed."); return -EBADMSG; } switch (o->object.type) { case OBJECT_DATA: { uint64_t h1, h2; int compression, r; if (le64toh(o->data.entry_offset) == 0) warning(offset, "Unused data (entry_offset==0)"); if ((le64toh(o->data.entry_offset) == 0) ^ (le64toh(o->data.n_entries) == 0)) { error(offset, "Bad n_entries: %" PRIu64, le64toh(o->data.n_entries)); return -EBADMSG; } if (le64toh(o->object.size) - offsetof(DataObject, payload) <= 0) { error(offset, "Bad object size (<= %zu): %" PRIu64, offsetof(DataObject, payload), le64toh(o->object.size)); return -EBADMSG; } h1 = le64toh(o->data.hash); compression = o->object.flags & OBJECT_COMPRESSION_MASK; if (compression) { _cleanup_free_ void* b = NULL; size_t alloc = 0, b_size; r = decompress_blob(compression, o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload), &b, &alloc, &b_size, 0); if (r < 0) { error_errno(offset, r, "%s decompression failed: %m", object_compressed_to_string(compression)); return r; } h2 = hash64(b, b_size); } else h2 = hash64(o->data.payload, le64toh(o->object.size) - offsetof(Object, data.payload)); if (h1 != h2) { error(offset, "Invalid hash (%08" PRIx64 " vs. %08" PRIx64, h1, h2); return -EBADMSG; } if (!VALID64(le64toh(o->data.next_hash_offset)) || !VALID64(le64toh(o->data.next_field_offset)) || !VALID64(le64toh(o->data.entry_offset)) || !VALID64(le64toh(o->data.entry_array_offset))) { error(offset, "Invalid offset (next_hash_offset=" OFSfmt ", next_field_offset=" OFSfmt ", entry_offset=" OFSfmt ", entry_array_offset=" OFSfmt, le64toh(o->data.next_hash_offset), le64toh(o->data.next_field_offset), le64toh(o->data.entry_offset), le64toh(o->data.entry_array_offset)); return -EBADMSG; } break; } case OBJECT_FIELD: if (le64toh(o->object.size) - offsetof(FieldObject, payload) <= 0) { error(offset, "Bad field size (<= %zu): %" PRIu64, offsetof(FieldObject, payload), le64toh(o->object.size)); return -EBADMSG; } if (!VALID64(le64toh(o->field.next_hash_offset)) || !VALID64(le64toh(o->field.head_data_offset))) { error(offset, "Invalid offset (next_hash_offset=" OFSfmt ", head_data_offset=" OFSfmt, le64toh(o->field.next_hash_offset), le64toh(o->field.head_data_offset)); return -EBADMSG; } break; case OBJECT_ENTRY: if ((le64toh(o->object.size) - offsetof(EntryObject, items)) % sizeof(EntryItem) != 0) { error(offset, "Bad entry size (<= %zu): %" PRIu64, offsetof(EntryObject, items), le64toh(o->object.size)); return -EBADMSG; } if ((le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem) <= 0) { error(offset, "Invalid number items in entry: %" PRIu64, (le64toh(o->object.size) - offsetof(EntryObject, items)) / sizeof(EntryItem)); return -EBADMSG; } if (le64toh(o->entry.seqnum) <= 0) { error(offset, "Invalid entry seqnum: %" PRIx64, le64toh(o->entry.seqnum)); return -EBADMSG; } if (!VALID_REALTIME(le64toh(o->entry.realtime))) { error(offset, "Invalid entry realtime timestamp: %" PRIu64, le64toh(o->entry.realtime)); return -EBADMSG; } if (!VALID_MONOTONIC(le64toh(o->entry.monotonic))) { error(offset, "Invalid entry monotonic timestamp: %" PRIu64, le64toh(o->entry.monotonic)); return -EBADMSG; } for (i = 0; i < journal_file_entry_n_items(o); i++) { if (le64toh(o->entry.items[i].object_offset) == 0 || !VALID64(le64toh(o->entry.items[i].object_offset))) { error(offset, "Invalid entry item (%" PRIu64 "/%" PRIu64 " offset: " OFSfmt, i, journal_file_entry_n_items(o), le64toh(o->entry.items[i].object_offset)); return -EBADMSG; } } break; case OBJECT_DATA_HASH_TABLE: case OBJECT_FIELD_HASH_TABLE: if ((le64toh(o->object.size) - offsetof(HashTableObject, items)) % sizeof(HashItem) != 0 || (le64toh(o->object.size) - offsetof(HashTableObject, items)) / sizeof(HashItem) <= 0) { error(offset, "Invalid %s hash table size: %" PRIu64, o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", le64toh(o->object.size)); return -EBADMSG; } for (i = 0; i < journal_file_hash_table_n_items(o); i++) { if (o->hash_table.items[i].head_hash_offset != 0 && !VALID64(le64toh(o->hash_table.items[i].head_hash_offset))) { error(offset, "Invalid %s hash table item (%" PRIu64 "/%" PRIu64 ") head_hash_offset: " OFSfmt, o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", i, journal_file_hash_table_n_items(o), le64toh(o->hash_table.items[i].head_hash_offset)); return -EBADMSG; } if (o->hash_table.items[i].tail_hash_offset != 0 && !VALID64(le64toh(o->hash_table.items[i].tail_hash_offset))) { error(offset, "Invalid %s hash table item (%" PRIu64 "/%" PRIu64 ") tail_hash_offset: " OFSfmt, o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", i, journal_file_hash_table_n_items(o), le64toh(o->hash_table.items[i].tail_hash_offset)); return -EBADMSG; } if ((o->hash_table.items[i].head_hash_offset != 0) != (o->hash_table.items[i].tail_hash_offset != 0)) { error(offset, "Invalid %s hash table item (%" PRIu64 "/%" PRIu64 "): head_hash_offset=" OFSfmt " tail_hash_offset=" OFSfmt, o->object.type == OBJECT_DATA_HASH_TABLE ? "data" : "field", i, journal_file_hash_table_n_items(o), le64toh(o->hash_table.items[i].head_hash_offset), le64toh(o->hash_table.items[i].tail_hash_offset)); return -EBADMSG; } } break; case OBJECT_ENTRY_ARRAY: if ((le64toh(o->object.size) - offsetof(EntryArrayObject, items)) % sizeof(le64_t) != 0 || (le64toh(o->object.size) - offsetof(EntryArrayObject, items)) / sizeof(le64_t) <= 0) { error(offset, "Invalid object entry array size: %" PRIu64, le64toh(o->object.size)); return -EBADMSG; } if (!VALID64(le64toh(o->entry_array.next_entry_array_offset))) { error(offset, "Invalid object entry array " "next_entry_array_offset: " OFSfmt, le64toh(o->entry_array.next_entry_array_offset)); return -EBADMSG; } for (i = 0; i < journal_file_entry_array_n_items(o); i++) if (le64toh(o->entry_array.items[i]) != 0 && !VALID64(le64toh(o->entry_array.items[i]))) { error(offset, "Invalid object entry array item (%" PRIu64 "/%" PRIu64 "): " OFSfmt, i, journal_file_entry_array_n_items(o), le64toh(o->entry_array.items[i])); return -EBADMSG; } break; case OBJECT_TAG: if (le64toh(o->object.size) != sizeof(TagObject)) { error(offset, "Invalid object tag size: %" PRIu64, le64toh(o->object.size)); return -EBADMSG; } if (!VALID_EPOCH(le64toh(o->tag.epoch))) { error(offset, "Invalid object tag epoch: %" PRIu64, le64toh(o->tag.epoch)); return -EBADMSG; } break; } return 0; } static int write_uint64(int fd, uint64_t p) { ssize_t k; k = write(fd, &p, sizeof(p)); if (k < 0) return -errno; if (k != sizeof(p)) return -EIO; return 0; } static int contains_uint64(MMapCache* m, MMapFileDescriptor* f, uint64_t n, uint64_t p) { uint64_t a, b; int r; assert(m); assert(f); /* Bisection ... */ a = 0; b = n; while (a < b) { uint64_t c, *z; c = (a + b) / 2; r = mmap_cache_get(m, f, PROT_READ | PROT_WRITE, 0, false, c * sizeof(uint64_t), sizeof(uint64_t), NULL, (void**)&z, NULL); if (r < 0) return r; if (*z == p) return 1; if (a + 1 >= b) return 0; if (p < *z) b = c; else a = c; } return 0; } static int entry_points_to_data(JournalFile* f, MMapFileDescriptor* cache_entry_fd, uint64_t n_entries, uint64_t entry_p, uint64_t data_p) { int r; uint64_t i, n, a; Object* o; bool found = false; assert(f); assert(cache_entry_fd); if (!contains_uint64(f->mmap, cache_entry_fd, n_entries, entry_p)) { error(data_p, "Data object references invalid entry at " OFSfmt, entry_p); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_ENTRY, entry_p, &o); if (r < 0) return r; n = journal_file_entry_n_items(o); for (i = 0; i < n; i++) if (le64toh(o->entry.items[i].object_offset) == data_p) { found = true; break; } if (!found) { error(entry_p, "Data object at " OFSfmt " not referenced by linked entry", data_p); return -EBADMSG; } /* Check if this entry is also in main entry array. Since the * main entry array has already been verified we can rely on * its consistency. */ i = 0; n = le64toh(f->header->n_entries); a = le64toh(f->header->entry_array_offset); while (i < n) { uint64_t m, u; r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); if (r < 0) return r; m = journal_file_entry_array_n_items(o); u = MIN(n - i, m); if (entry_p <= le64toh(o->entry_array.items[u - 1])) { uint64_t x, y, z; x = 0; y = u; while (x < y) { z = (x + y) / 2; if (le64toh(o->entry_array.items[z]) == entry_p) return 0; if (x + 1 >= y) break; if (entry_p < le64toh(o->entry_array.items[z])) y = z; else x = z; } error(entry_p, "Entry object doesn't exist in main entry array"); return -EBADMSG; } i += u; a = le64toh(o->entry_array.next_entry_array_offset); } return 0; } static int verify_data(JournalFile* f, Object* o, uint64_t p, MMapFileDescriptor* cache_entry_fd, uint64_t n_entries, MMapFileDescriptor* cache_entry_array_fd, uint64_t n_entry_arrays) { uint64_t i, n, a, last, q; int r; assert(f); assert(o); assert(cache_entry_fd); assert(cache_entry_array_fd); n = le64toh(o->data.n_entries); a = le64toh(o->data.entry_array_offset); /* Entry array means at least two objects */ if (a && n < 2) { error(p, "Entry array present (entry_array_offset=" OFSfmt ", but n_entries=%" PRIu64 ")", a, n); return -EBADMSG; } if (n == 0) return 0; /* We already checked that earlier */ assert(o->data.entry_offset); last = q = le64toh(o->data.entry_offset); r = entry_points_to_data(f, cache_entry_fd, n_entries, q, p); if (r < 0) return r; i = 1; while (i < n) { uint64_t next, m, j; if (a == 0) { error(p, "Array chain too short"); return -EBADMSG; } if (!contains_uint64(f->mmap, cache_entry_array_fd, n_entry_arrays, a)) { error(p, "Invalid array offset " OFSfmt, a); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); if (r < 0) return r; next = le64toh(o->entry_array.next_entry_array_offset); if (next != 0 && next <= a) { error(p, "Array chain has cycle (jumps back from " OFSfmt " to " OFSfmt ")", a, next); return -EBADMSG; } m = journal_file_entry_array_n_items(o); for (j = 0; i < n && j < m; i++, j++) { q = le64toh(o->entry_array.items[j]); if (q <= last) { error(p, "Data object's entry array not sorted"); return -EBADMSG; } last = q; r = entry_points_to_data(f, cache_entry_fd, n_entries, q, p); if (r < 0) return r; /* Pointer might have moved, reposition */ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); if (r < 0) return r; } a = next; } return 0; } static int verify_hash_table(JournalFile* f, MMapFileDescriptor* cache_data_fd, uint64_t n_data, MMapFileDescriptor* cache_entry_fd, uint64_t n_entries, MMapFileDescriptor* cache_entry_array_fd, uint64_t n_entry_arrays, usec_t* last_usec, bool show_progress) { uint64_t i, n; int r; assert(f); assert(cache_data_fd); assert(cache_entry_fd); assert(cache_entry_array_fd); assert(last_usec); n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); if (n <= 0) return 0; r = journal_file_map_data_hash_table(f); if (r < 0) return log_error_errno(r, "Failed to map data hash table: %m"); for (i = 0; i < n; i++) { uint64_t last = 0, p; if (show_progress) draw_progress(0xC000 + scale_progress(0x3FFF, i, n), last_usec); p = le64toh(f->data_hash_table[i].head_hash_offset); while (p != 0) { Object* o; uint64_t next; if (!contains_uint64(f->mmap, cache_data_fd, n_data, p)) { error(p, "Invalid data object at hash entry %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_DATA, p, &o); if (r < 0) return r; next = le64toh(o->data.next_hash_offset); if (next != 0 && next <= p) { error(p, "Hash chain has a cycle in hash entry %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } if (le64toh(o->data.hash) % n != i) { error(p, "Hash value mismatch in hash entry %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } r = verify_data(f, o, p, cache_entry_fd, n_entries, cache_entry_array_fd, n_entry_arrays); if (r < 0) return r; last = p; p = next; } if (last != le64toh(f->data_hash_table[i].tail_hash_offset)) { error(p, "Tail hash pointer mismatch in hash table"); return -EBADMSG; } } return 0; } static int data_object_in_hash_table(JournalFile* f, uint64_t hash, uint64_t p) { uint64_t n, h, q; int r; assert(f); n = le64toh(f->header->data_hash_table_size) / sizeof(HashItem); if (n <= 0) return 0; r = journal_file_map_data_hash_table(f); if (r < 0) return log_error_errno(r, "Failed to map data hash table: %m"); h = hash % n; q = le64toh(f->data_hash_table[h].head_hash_offset); while (q != 0) { Object* o; if (p == q) return 1; r = journal_file_move_to_object(f, OBJECT_DATA, q, &o); if (r < 0) return r; q = le64toh(o->data.next_hash_offset); } return 0; } static int verify_entry(JournalFile* f, Object* o, uint64_t p, MMapFileDescriptor* cache_data_fd, uint64_t n_data) { uint64_t i, n; int r; assert(f); assert(o); assert(cache_data_fd); n = journal_file_entry_n_items(o); for (i = 0; i < n; i++) { uint64_t q, h; Object* u; q = le64toh(o->entry.items[i].object_offset); h = le64toh(o->entry.items[i].hash); if (!contains_uint64(f->mmap, cache_data_fd, n_data, q)) { error(p, "Invalid data object of entry"); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_DATA, q, &u); if (r < 0) return r; if (le64toh(u->data.hash) != h) { error(p, "Hash mismatch for data object of entry"); return -EBADMSG; } r = data_object_in_hash_table(f, h, q); if (r < 0) return r; if (r == 0) { error(p, "Data object missing from hash table"); return -EBADMSG; } } return 0; } static int verify_entry_array(JournalFile* f, MMapFileDescriptor* cache_data_fd, uint64_t n_data, MMapFileDescriptor* cache_entry_fd, uint64_t n_entries, MMapFileDescriptor* cache_entry_array_fd, uint64_t n_entry_arrays, usec_t* last_usec, bool show_progress) { uint64_t i = 0, a, n, last = 0; int r; assert(f); assert(cache_data_fd); assert(cache_entry_fd); assert(cache_entry_array_fd); assert(last_usec); n = le64toh(f->header->n_entries); a = le64toh(f->header->entry_array_offset); while (i < n) { uint64_t next, m, j; Object* o; if (show_progress) draw_progress(0x8000 + scale_progress(0x3FFF, i, n), last_usec); if (a == 0) { error(a, "Array chain too short at %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } if (!contains_uint64(f->mmap, cache_entry_array_fd, n_entry_arrays, a)) { error(a, "Invalid array %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); if (r < 0) return r; next = le64toh(o->entry_array.next_entry_array_offset); if (next != 0 && next <= a) { error(a, "Array chain has cycle at %" PRIu64 " of %" PRIu64 " (jumps back from to " OFSfmt ")", i, n, next); return -EBADMSG; } m = journal_file_entry_array_n_items(o); for (j = 0; i < n && j < m; i++, j++) { uint64_t p; p = le64toh(o->entry_array.items[j]); if (p <= last) { error(a, "Entry array not sorted at %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } last = p; if (!contains_uint64(f->mmap, cache_entry_fd, n_entries, p)) { error(a, "Invalid array entry at %" PRIu64 " of %" PRIu64, i, n); return -EBADMSG; } r = journal_file_move_to_object(f, OBJECT_ENTRY, p, &o); if (r < 0) return r; r = verify_entry(f, o, p, cache_data_fd, n_data); if (r < 0) return r; /* Pointer might have moved, reposition */ r = journal_file_move_to_object(f, OBJECT_ENTRY_ARRAY, a, &o); if (r < 0) return r; } a = next; } return 0; } int journal_file_verify(JournalFile* f, const char* key, usec_t* first_contained, usec_t* last_validated, usec_t* last_contained, bool show_progress) { int r; Object* o; uint64_t p = 0, last_epoch = 0, last_tag_realtime = 0, last_sealed_realtime = 0; uint64_t entry_seqnum = 0, entry_monotonic = 0, entry_realtime = 0; sd_id128_t entry_boot_id; bool entry_seqnum_set = false, entry_monotonic_set = false, entry_realtime_set = false, found_main_entry_array = false; uint64_t n_weird = 0, n_objects = 0, n_entries = 0, n_data = 0, n_fields = 0, n_data_hash_tables = 0, n_field_hash_tables = 0, n_entry_arrays = 0, n_tags = 0; usec_t last_usec = 0; int data_fd = -1, entry_fd = -1, entry_array_fd = -1; MMapFileDescriptor *cache_data_fd = NULL, *cache_entry_fd = NULL, *cache_entry_array_fd = NULL; unsigned i; bool found_last = false; const char* tmp_dir = NULL; #if HAVE_GCRYPT uint64_t last_tag = 0; #endif assert(f); if (key) { #if HAVE_GCRYPT r = journal_file_parse_verification_key(f, key); if (r < 0) { log_error("Failed to parse seed."); return r; } #else return -EOPNOTSUPP; #endif } else if (f->seal) return -ENOKEY; r = var_tmp_dir(&tmp_dir); if (r < 0) { log_error_errno(r, "Failed to determine temporary directory: %m"); goto fail; } data_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); if (data_fd < 0) { r = log_error_errno(data_fd, "Failed to create data file: %m"); goto fail; } entry_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); if (entry_fd < 0) { r = log_error_errno(entry_fd, "Failed to create entry file: %m"); goto fail; } entry_array_fd = open_tmpfile_unlinkable(tmp_dir, O_RDWR | O_CLOEXEC); if (entry_array_fd < 0) { r = log_error_errno(entry_array_fd, "Failed to create entry array file: %m"); goto fail; } cache_data_fd = mmap_cache_add_fd(f->mmap, data_fd); if (!cache_data_fd) { r = log_oom(); goto fail; } cache_entry_fd = mmap_cache_add_fd(f->mmap, entry_fd); if (!cache_entry_fd) { r = log_oom(); goto fail; } cache_entry_array_fd = mmap_cache_add_fd(f->mmap, entry_array_fd); if (!cache_entry_array_fd) { r = log_oom(); goto fail; } if (le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SUPPORTED) { log_error("Cannot verify file with unknown extensions."); r = -EOPNOTSUPP; goto fail; } for (i = 0; i < sizeof(f->header->reserved); i++) if (f->header->reserved[i] != 0) { error(offsetof(Header, reserved[i]), "Reserved field is non-zero"); r = -EBADMSG; goto fail; } /* First iteration: we go through all objects, verify the * superficial structure, headers, hashes. */ p = le64toh(f->header->header_size); for (;;) { /* Early exit if there are no objects in the file, at all */ if (le64toh(f->header->tail_object_offset) == 0) break; if (show_progress) draw_progress( scale_progress(0x7FFF, p, le64toh(f->header->tail_object_offset)), &last_usec); r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o); if (r < 0) { error(p, "Invalid object"); goto fail; } if (p > le64toh(f->header->tail_object_offset)) { error(offsetof(Header, tail_object_offset), "Invalid tail object pointer"); r = -EBADMSG; goto fail; } n_objects++; r = journal_file_object_verify(f, p, o); if (r < 0) { error_errno(p, r, "Invalid object contents: %m"); goto fail; } if ((o->object.flags & OBJECT_COMPRESSED_XZ) && (o->object.flags & OBJECT_COMPRESSED_LZ4)) { error(p, "Objected with double compression"); r = -EINVAL; goto fail; } if ((o->object.flags & OBJECT_COMPRESSED_XZ) && !JOURNAL_HEADER_COMPRESSED_XZ(f->header)) { error(p, "XZ compressed object in file without XZ compression"); r = -EBADMSG; goto fail; } if ((o->object.flags & OBJECT_COMPRESSED_LZ4) && !JOURNAL_HEADER_COMPRESSED_LZ4(f->header)) { error(p, "LZ4 compressed object in file without LZ4 compression"); r = -EBADMSG; goto fail; } switch (o->object.type) { case OBJECT_DATA: r = write_uint64(data_fd, p); if (r < 0) goto fail; n_data++; break; case OBJECT_FIELD: n_fields++; break; case OBJECT_ENTRY: if (JOURNAL_HEADER_SEALED(f->header) && n_tags <= 0) { error(p, "First entry before first tag"); r = -EBADMSG; goto fail; } r = write_uint64(entry_fd, p); if (r < 0) goto fail; if (le64toh(o->entry.realtime) < last_tag_realtime) { error(p, "Older entry after newer tag"); r = -EBADMSG; goto fail; } if (!entry_seqnum_set && le64toh(o->entry.seqnum) != le64toh(f->header->head_entry_seqnum)) { error(p, "Head entry sequence number incorrect"); r = -EBADMSG; goto fail; } if (entry_seqnum_set && entry_seqnum >= le64toh(o->entry.seqnum)) { error(p, "Entry sequence number out of synchronization"); r = -EBADMSG; goto fail; } entry_seqnum = le64toh(o->entry.seqnum); entry_seqnum_set = true; if (entry_monotonic_set && sd_id128_equal(entry_boot_id, o->entry.boot_id) && entry_monotonic > le64toh(o->entry.monotonic)) { error(p, "Entry timestamp out of synchronization"); r = -EBADMSG; goto fail; } entry_monotonic = le64toh(o->entry.monotonic); entry_boot_id = o->entry.boot_id; entry_monotonic_set = true; if (!entry_realtime_set && le64toh(o->entry.realtime) != le64toh(f->header->head_entry_realtime)) { error(p, "Head entry realtime timestamp incorrect"); r = -EBADMSG; goto fail; } entry_realtime = le64toh(o->entry.realtime); entry_realtime_set = true; n_entries++; break; case OBJECT_DATA_HASH_TABLE: if (n_data_hash_tables > 1) { error(p, "More than one data hash table"); r = -EBADMSG; goto fail; } if (le64toh(f->header->data_hash_table_offset) != p + offsetof(HashTableObject, items) || le64toh(f->header->data_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) { error(p, "header fields for data hash table invalid"); r = -EBADMSG; goto fail; } n_data_hash_tables++; break; case OBJECT_FIELD_HASH_TABLE: if (n_field_hash_tables > 1) { error(p, "More than one field hash table"); r = -EBADMSG; goto fail; } if (le64toh(f->header->field_hash_table_offset) != p + offsetof(HashTableObject, items) || le64toh(f->header->field_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) { error(p, "Header fields for field hash table invalid"); r = -EBADMSG; goto fail; } n_field_hash_tables++; break; case OBJECT_ENTRY_ARRAY: r = write_uint64(entry_array_fd, p); if (r < 0) goto fail; if (p == le64toh(f->header->entry_array_offset)) { if (found_main_entry_array) { error(p, "More than one main entry array"); r = -EBADMSG; goto fail; } found_main_entry_array = true; } n_entry_arrays++; break; case OBJECT_TAG: if (!JOURNAL_HEADER_SEALED(f->header)) { error(p, "Tag object in file without sealing"); r = -EBADMSG; goto fail; } if (le64toh(o->tag.seqnum) != n_tags + 1) { error(p, "Tag sequence number out of synchronization"); r = -EBADMSG; goto fail; } if (le64toh(o->tag.epoch) < last_epoch) { error(p, "Epoch sequence out of synchronization"); r = -EBADMSG; goto fail; } #if HAVE_GCRYPT if (f->seal) { uint64_t q, rt; debug(p, "Checking tag %" PRIu64 "...", le64toh(o->tag.seqnum)); rt = f->fss_start_usec + le64toh(o->tag.epoch) * f->fss_interval_usec; if (entry_realtime_set && entry_realtime >= rt + f->fss_interval_usec) { error(p, "tag/entry realtime timestamp out of " "synchronization"); r = -EBADMSG; goto fail; } /* OK, now we know the epoch. So let's now set * it, and calculate the HMAC for everything * since the last tag. */ r = journal_file_fsprg_seek(f, le64toh(o->tag.epoch)); if (r < 0) goto fail; r = journal_file_hmac_start(f); if (r < 0) goto fail; if (last_tag == 0) { r = journal_file_hmac_put_header(f); if (r < 0) goto fail; q = le64toh(f->header->header_size); } else q = last_tag; while (q <= p) { r = journal_file_move_to_object(f, OBJECT_UNUSED, q, &o); if (r < 0) goto fail; r = journal_file_hmac_put_object(f, OBJECT_UNUSED, o, q); if (r < 0) goto fail; q = q + ALIGN64(le64toh(o->object.size)); } /* Position might have changed, let's reposition things */ r = journal_file_move_to_object(f, OBJECT_UNUSED, p, &o); if (r < 0) goto fail; if (memcmp(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH) != 0) { error(p, "Tag failed verification"); r = -EBADMSG; goto fail; } f->hmac_running = false; last_tag_realtime = rt; last_sealed_realtime = entry_realtime; } last_tag = p + ALIGN64(le64toh(o->object.size)); #endif last_epoch = le64toh(o->tag.epoch); n_tags++; break; default: n_weird++; } if (p == le64toh(f->header->tail_object_offset)) { found_last = true; break; } p = p + ALIGN64(le64toh(o->object.size)); }; if (!found_last && le64toh(f->header->tail_object_offset) != 0) { error(le64toh(f->header->tail_object_offset), "Tail object pointer dead"); r = -EBADMSG; goto fail; } if (n_objects != le64toh(f->header->n_objects)) { error(offsetof(Header, n_objects), "Object number mismatch"); r = -EBADMSG; goto fail; } if (n_entries != le64toh(f->header->n_entries)) { error(offsetof(Header, n_entries), "Entry number mismatch"); r = -EBADMSG; goto fail; } if (JOURNAL_HEADER_CONTAINS(f->header, n_data) && n_data != le64toh(f->header->n_data)) { error(offsetof(Header, n_data), "Data number mismatch"); r = -EBADMSG; goto fail; } if (JOURNAL_HEADER_CONTAINS(f->header, n_fields) && n_fields != le64toh(f->header->n_fields)) { error(offsetof(Header, n_fields), "Field number mismatch"); r = -EBADMSG; goto fail; } if (JOURNAL_HEADER_CONTAINS(f->header, n_tags) && n_tags != le64toh(f->header->n_tags)) { error(offsetof(Header, n_tags), "Tag number mismatch"); r = -EBADMSG; goto fail; } if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays) && n_entry_arrays != le64toh(f->header->n_entry_arrays)) { error(offsetof(Header, n_entry_arrays), "Entry array number mismatch"); r = -EBADMSG; goto fail; } if (!found_main_entry_array && le64toh(f->header->entry_array_offset) != 0) { error(0, "Missing entry array"); r = -EBADMSG; goto fail; } if (entry_seqnum_set && entry_seqnum != le64toh(f->header->tail_entry_seqnum)) { error(offsetof(Header, tail_entry_seqnum), "Invalid tail seqnum"); r = -EBADMSG; goto fail; } if (entry_monotonic_set && (sd_id128_equal(entry_boot_id, f->header->boot_id) && entry_monotonic != le64toh(f->header->tail_entry_monotonic))) { error(0, "Invalid tail monotonic timestamp"); r = -EBADMSG; goto fail; } if (entry_realtime_set && entry_realtime != le64toh(f->header->tail_entry_realtime)) { error(0, "Invalid tail realtime timestamp"); r = -EBADMSG; goto fail; } /* Second iteration: we follow all objects referenced from the * two entry points: the object hash table and the entry * array. We also check that everything referenced (directly * or indirectly) in the data hash table also exists in the * entry array, and vice versa. Note that we do not care for * unreferenced objects. We only care that everything that is * referenced is consistent. */ r = verify_entry_array(f, cache_data_fd, n_data, cache_entry_fd, n_entries, cache_entry_array_fd, n_entry_arrays, &last_usec, show_progress); if (r < 0) goto fail; r = verify_hash_table(f, cache_data_fd, n_data, cache_entry_fd, n_entries, cache_entry_array_fd, n_entry_arrays, &last_usec, show_progress); if (r < 0) goto fail; if (show_progress) flush_progress(); mmap_cache_free_fd(f->mmap, cache_data_fd); mmap_cache_free_fd(f->mmap, cache_entry_fd); mmap_cache_free_fd(f->mmap, cache_entry_array_fd); safe_close(data_fd); safe_close(entry_fd); safe_close(entry_array_fd); if (first_contained) *first_contained = le64toh(f->header->head_entry_realtime); if (last_validated) *last_validated = last_sealed_realtime; if (last_contained) *last_contained = le64toh(f->header->tail_entry_realtime); return 0; fail: if (show_progress) flush_progress(); log_error("File corruption detected at %s:" OFSfmt " (of %llu bytes, %" PRIu64 "%%).", f->path, p, (unsigned long long)f->last_stat.st_size, 100 * p / f->last_stat.st_size); if (data_fd >= 0) safe_close(data_fd); if (entry_fd >= 0) safe_close(entry_fd); if (entry_array_fd >= 0) safe_close(entry_array_fd); if (cache_data_fd) mmap_cache_free_fd(f->mmap, cache_data_fd); if (cache_entry_fd) mmap_cache_free_fd(f->mmap, cache_entry_fd); if (cache_entry_array_fd) mmap_cache_free_fd(f->mmap, cache_entry_array_fd); return r; }
Video-Byte/prebid-server
adapters/smartrtb/smartrtb.go
<filename>adapters/smartrtb/smartrtb.go package smartrtb import ( "encoding/json" "fmt" "net/http" "text/template" "github.com/mxmCherry/openrtb/v15/openrtb2" "github.com/prebid/prebid-server/adapters" "github.com/prebid/prebid-server/config" "github.com/prebid/prebid-server/errortypes" "github.com/prebid/prebid-server/macros" "github.com/prebid/prebid-server/openrtb_ext" ) // Base adapter structure. type SmartRTBAdapter struct { EndpointTemplate *template.Template } // Bid request extension appended to downstream request. // PubID are non-empty iff request.{App,Site} or // request.{App,Site}.Publisher are nil, respectively. type bidRequestExt struct { PubID string `json:"pub_id,omitempty"` ZoneID string `json:"zone_id,omitempty"` ForceBid bool `json:"force_bid,omitempty"` } // bidExt.CreativeType values. const ( creativeTypeBanner string = "BANNER" creativeTypeVideo = "VIDEO" creativeTypeNative = "NATIVE" creativeTypeAudio = "AUDIO" ) // Bid response extension from downstream. type bidExt struct { CreativeType string `json:"format"` } // Builder builds a new instance of the SmartRTB adapter for the given bidder with the given config. func Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) { template, err := template.New("endpointTemplate").Parse(config.Endpoint) if err != nil { return nil, fmt.Errorf("unable to parse endpoint url template: %v", err) } bidder := &SmartRTBAdapter{ EndpointTemplate: template, } return bidder, nil } func (adapter *SmartRTBAdapter) buildEndpointURL(pubID string) (string, error) { endpointParams := macros.EndpointTemplateParams{PublisherID: pubID} return macros.ResolveMacros(adapter.EndpointTemplate, endpointParams) } func parseExtImp(dst *bidRequestExt, imp *openrtb2.Imp) error { var ext adapters.ExtImpBidder if err := json.Unmarshal(imp.Ext, &ext); err != nil { return &errortypes.BadInput{ Message: err.Error(), } } var src openrtb_ext.ExtImpSmartRTB if err := json.Unmarshal(ext.Bidder, &src); err != nil { return &errortypes.BadInput{ Message: err.Error(), } } if dst.PubID == "" { dst.PubID = src.PubID } if src.ZoneID != "" { imp.TagID = src.ZoneID } return nil } func (s *SmartRTBAdapter) MakeRequests(brq *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) { var imps []openrtb2.Imp var err error ext := bidRequestExt{} nrImps := len(brq.Imp) errs := make([]error, 0, nrImps) for i := 0; i < nrImps; i++ { imp := brq.Imp[i] if imp.Banner == nil && imp.Video == nil { continue } err = parseExtImp(&ext, &imp) if err != nil { errs = append(errs, err) continue } imps = append(imps, imp) } if len(imps) == 0 { return nil, errs } if ext.PubID == "" { return nil, append(errs, &errortypes.BadInput{Message: "Cannot infer publisher ID from bid ext"}) } brq.Ext, err = json.Marshal(ext) if err != nil { return nil, append(errs, err) } brq.Imp = imps rq, err := json.Marshal(brq) if err != nil { return nil, append(errs, err) } url, err := s.buildEndpointURL(ext.PubID) if err != nil { return nil, append(errs, err) } headers := http.Header{} headers.Add("Content-Type", "application/json;charset=utf-8") headers.Add("Accept", "application/json") headers.Add("x-openrtb-version", "2.5") return []*adapters.RequestData{{ Method: "POST", Uri: url, Body: rq, Headers: headers, }}, errs } func (s *SmartRTBAdapter) MakeBids( brq *openrtb2.BidRequest, drq *adapters.RequestData, rs *adapters.ResponseData, ) (*adapters.BidderResponse, []error) { if rs.StatusCode == http.StatusNoContent { return nil, nil } else if rs.StatusCode == http.StatusBadRequest { return nil, []error{&errortypes.BadInput{Message: "Invalid request."}} } else if rs.StatusCode != http.StatusOK { return nil, []error{&errortypes.BadServerResponse{ Message: fmt.Sprintf("Unexpected HTTP status %d.", rs.StatusCode), }} } var brs openrtb2.BidResponse if err := json.Unmarshal(rs.Body, &brs); err != nil { return nil, []error{err} } rv := adapters.NewBidderResponseWithBidsCapacity(5) for _, seat := range brs.SeatBid { for i := range seat.Bid { var ext bidExt if err := json.Unmarshal(seat.Bid[i].Ext, &ext); err != nil { return nil, []error{&errortypes.BadServerResponse{ Message: "Invalid bid extension from endpoint.", }} } var btype openrtb_ext.BidType switch ext.CreativeType { case creativeTypeBanner: btype = openrtb_ext.BidTypeBanner case creativeTypeVideo: btype = openrtb_ext.BidTypeVideo default: return nil, []error{&errortypes.BadServerResponse{ Message: fmt.Sprintf("Unsupported creative type %s.", ext.CreativeType), }} } seat.Bid[i].Ext = nil rv.Bids = append(rv.Bids, &adapters.TypedBid{ Bid: &seat.Bid[i], BidType: btype, }) } } return rv, nil }
ss23/cpp3ds
include/cpp3ds/System.hpp
<filename>include/cpp3ds/System.hpp #ifndef CPP3DS_SYSTEM_HPP #define CPP3DS_SYSTEM_HPP #include <cpp3ds/Config.hpp> #include <cpp3ds/System/Clock.hpp> #include <cpp3ds/System/Err.hpp> #include <cpp3ds/System/I18n.hpp> #include <cpp3ds/System/InputStream.hpp> #include <cpp3ds/System/Lock.hpp> #include <cpp3ds/System/Mutex.hpp> #include <cpp3ds/System/Sleep.hpp> #include <cpp3ds/System/String.hpp> #include <cpp3ds/System/Service.hpp> #include <cpp3ds/System/Thread.hpp> #include <cpp3ds/System/ThreadLocal.hpp> #include <cpp3ds/System/ThreadLocalPtr.hpp> #include <cpp3ds/System/Utf.hpp> #include <cpp3ds/System/Vector2.hpp> #include <cpp3ds/System/Vector3.hpp> #endif //////////////////////////////////////////////////////////// /// \defgroup system System module /// /// Base module of cpp3ds, defining various utilities. It provides /// vector classes, unicode strings and conversion functions, /// threads and mutexes, timing classes. /// ////////////////////////////////////////////////////////////
wojciech-panek/devtalk-pwa-app
webapp/src/modules/game/index.js
export { GameTypes, GameActions, } from './game.redux'; export * from './game.selectors';
daveagill/InvasionOfTheLiquidSnatchersGame
src/week/of/awesome/game/Beamable.java
package week.of.awesome.game; public interface Beamable { public void onEnterBeam(Beam b); public void onExitBeam(); }
Testiduk/gitlabhq
spec/frontend/filtered_search/issues_filtered_search_token_keys_spec.js
<reponame>Testiduk/gitlabhq import IssuableFilteredSearchTokenKeys from '~/filtered_search/issuable_filtered_search_token_keys'; describe('Issues Filtered Search Token Keys', () => { describe('get', () => { let tokenKeys; beforeEach(() => { tokenKeys = IssuableFilteredSearchTokenKeys.get(); }); it('should return tokenKeys', () => { expect(tokenKeys).not.toBeNull(); }); it('should return tokenKeys as an array', () => { expect(tokenKeys instanceof Array).toBe(true); }); it('should always return the same array', () => { const tokenKeys2 = IssuableFilteredSearchTokenKeys.get(); expect(tokenKeys).toEqual(tokenKeys2); }); it('should return assignee as a string', () => { const assignee = tokenKeys.find((tokenKey) => tokenKey.key === 'assignee'); expect(assignee.type).toEqual('string'); }); }); describe('getKeys', () => { it('should return keys', () => { const getKeys = IssuableFilteredSearchTokenKeys.getKeys(); const keys = IssuableFilteredSearchTokenKeys.get().map((i) => i.key); keys.forEach((key, i) => { expect(key).toEqual(getKeys[i]); }); }); }); describe('getConditions', () => { let conditions; beforeEach(() => { conditions = IssuableFilteredSearchTokenKeys.getConditions(); }); it('should return conditions', () => { expect(conditions).not.toBeNull(); }); it('should return conditions as an array', () => { expect(conditions instanceof Array).toBe(true); }); }); describe('searchByKey', () => { it('should return null when key not found', () => { const tokenKey = IssuableFilteredSearchTokenKeys.searchByKey('notakey'); expect(tokenKey).toBeNull(); }); it('should return tokenKey when found by key', () => { const tokenKeys = IssuableFilteredSearchTokenKeys.get(); const result = IssuableFilteredSearchTokenKeys.searchByKey(tokenKeys[0].key); expect(result).toEqual(tokenKeys[0]); }); }); describe('searchBySymbol', () => { it('should return null when symbol not found', () => { const tokenKey = IssuableFilteredSearchTokenKeys.searchBySymbol('notasymbol'); expect(tokenKey).toBeNull(); }); it('should return tokenKey when found by symbol', () => { const tokenKeys = IssuableFilteredSearchTokenKeys.get(); const result = IssuableFilteredSearchTokenKeys.searchBySymbol(tokenKeys[0].symbol); expect(result).toEqual(tokenKeys[0]); }); }); describe('searchByKeyParam', () => { it('should return null when key param not found', () => { const tokenKey = IssuableFilteredSearchTokenKeys.searchByKeyParam('notakeyparam'); expect(tokenKey).toBeNull(); }); it('should return tokenKey when found by key param', () => { const tokenKeys = IssuableFilteredSearchTokenKeys.get(); const result = IssuableFilteredSearchTokenKeys.searchByKeyParam( `${tokenKeys[0].key}_${tokenKeys[0].param}`, ); expect(result).toEqual(tokenKeys[0]); }); it('should return alternative tokenKey when found by key param', () => { const tokenKeys = IssuableFilteredSearchTokenKeys.getAlternatives(); const result = IssuableFilteredSearchTokenKeys.searchByKeyParam( `${tokenKeys[0].key}_${tokenKeys[0].param}`, ); expect(result).toEqual(tokenKeys[0]); }); }); describe('searchByConditionUrl', () => { it('should return null when condition url not found', () => { const condition = IssuableFilteredSearchTokenKeys.searchByConditionUrl(null); expect(condition).toBeNull(); }); it('should return condition when found by url', () => { const conditions = IssuableFilteredSearchTokenKeys.getConditions(); const result = IssuableFilteredSearchTokenKeys.searchByConditionUrl(conditions[0].url); expect(result).toBe(conditions[0]); }); }); describe('searchByConditionKeyValue', () => { it('should return null when condition tokenKey and value not found', () => { const condition = IssuableFilteredSearchTokenKeys.searchByConditionKeyValue(null, null); expect(condition).toBeNull(); }); it('should return condition when found by tokenKey and value', () => { const conditions = IssuableFilteredSearchTokenKeys.getConditions(); const result = IssuableFilteredSearchTokenKeys.searchByConditionKeyValue( conditions[0].tokenKey, conditions[0].operator, conditions[0].value, ); expect(result).toEqual(conditions[0]); }); }); describe('removeTokensForKeys', () => { let initTokenKeys; beforeEach(() => { initTokenKeys = [...IssuableFilteredSearchTokenKeys.get()]; }); it('should remove the tokenKeys corresponding to the given keys', () => { const [firstTokenKey, secondTokenKey, ...restTokens] = initTokenKeys; IssuableFilteredSearchTokenKeys.removeTokensForKeys(firstTokenKey.key, secondTokenKey.key); expect(IssuableFilteredSearchTokenKeys.get()).toEqual(restTokens); }); it('should do nothing when key is not found', () => { IssuableFilteredSearchTokenKeys.removeTokensForKeys('bogus'); expect(IssuableFilteredSearchTokenKeys.get()).toEqual(initTokenKeys); }); }); });
steph-ieffam/DSpace
dspace-oai/src/main/java/org/dspace/xoai/app/XOAICerifItemCompilePlugin.java
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.xoai.app; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Objects; import java.util.Optional; import com.lyncode.xoai.dataprovider.xml.xoai.Element; import com.lyncode.xoai.dataprovider.xml.xoai.Metadata; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.dspace.content.Item; import org.dspace.content.ItemServiceImpl; import org.dspace.content.crosswalk.StreamDisseminationCrosswalk; import org.dspace.content.integration.crosswalks.StreamDisseminationCrosswalkMapper; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.eperson.factory.EPersonServiceFactory; import org.dspace.eperson.service.EPersonService; import org.dspace.utils.DSpace; import org.dspace.xoai.util.ItemUtils; /** * Utility class to enrich content of 'item.compile' solr document field, which adds a metadata containing cerif * representation of a DSpace item. * Additional xml is written into a node named "cerif." + value of field name passed in plugin configuration * */ public class XOAICerifItemCompilePlugin implements XOAIExtensionItemCompilePlugin { private static final Logger log = LogManager.getLogger(XOAICerifItemCompilePlugin.class); private EPersonService ePersonService = EPersonServiceFactory.getInstance().getEPersonService(); private String generator; private String fieldName; private String ePersonName; public String getGenerator() { return generator; } public void setGenerator(String generator) { this.generator = generator; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public void setePersonName(String ePersonName) { this.ePersonName = ePersonName; } @Override public Metadata additionalMetadata(Context context, Metadata metadata, Item item) { EPerson currentUser = context.getCurrentUser(); try { if (StringUtils.isNotBlank(ePersonName)) { EPerson ePerson = ePersonService.findByEmail(context, ePersonName); Optional.ofNullable(ePerson).ifPresent(context::setCurrentUser); } StreamDisseminationCrosswalkMapper crosswalkMapper = new DSpace().getSingletonService( StreamDisseminationCrosswalkMapper.class); ItemServiceImpl itemService = new DSpace().getSingletonService(ItemServiceImpl.class); String entityType = itemService.getEntityType(item); final String crosswalkType = entityType.substring(0, 1).toLowerCase() + entityType.substring(1) + "-" + generator; StreamDisseminationCrosswalk crosswalk = crosswalkMapper.getByType(crosswalkType); if (crosswalk == null) { log.warn("No Crosswalk found with name " + crosswalkType); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); crosswalk.disseminate(context, item, out); List<Element> elementList = metadata.getElement(); elementList.add(ItemUtils.create("cerif")); Element cerif = ItemUtils.getElement(elementList, "cerif"); if (Objects.isNull(cerif)) { elementList.add(ItemUtils.create("cerif")); cerif = ItemUtils.getElement(elementList, "cerif"); } Element fieldname = ItemUtils.create(fieldName); cerif.getElement().add(fieldname); Element none = ItemUtils.create("none"); fieldname.getElement().add(none); String xml_presentation = out.toString(); // replace \n to avoid invalid element in the xml String toWrite = xml_presentation.replace("\n", ""); none.getField().add(ItemUtils.createValue("value", xml_presentation)); none.getField().add(ItemUtils.createValue("authority", "")); none.getField().add(ItemUtils.createValue("confidence", "-1")); return metadata; } } catch (Exception e) { log.error(e.getMessage(), e); } finally { context.setCurrentUser(currentUser); } return metadata; } }
WynnKunGz/Refinement
src/main/java/com/ablackpikatchu/refinement/common/effects/NegateFall.java
<gh_stars>0 package com.ablackpikatchu.refinement.common.effects; import javax.annotation.Nonnull; import net.minecraft.entity.LivingEntity; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectType; public class NegateFall extends Effect { public NegateFall() { super(EffectType.BENEFICIAL, 0x008000); } @Override public boolean isDurationEffectTick(int duration, int amplified) { return true; } @Override public void applyEffectTick(@Nonnull LivingEntity entity, int amplifier) { if (entity.fallDistance > 1.5f) { entity.fallDistance = 0f; } } }
minsukkahng/pokr.kr
alembic/versions/225b82afbf55_insert_values_into_party_affiliation.py
<gh_stars>10-100 """insert values into party_affiliation Revision ID: 225b82afbf55 Revises: <PASSWORD> Create Date: 2014-05-31 02:30:21.664147 """ # revision identifiers, used by Alembic. revision = '225b82afbf55' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): op.execute("insert into party_affiliation (person_id, party_id, date) select person_id, party_id, to_date(date, 'YYYYMMDD') from candidacy, election where candidacy.election_id = election.id;") def downgrade(): op.execute('delete from party_affiliation;')
Stanford-ILIAD/Confidence-Aware-Imitation-Learning
collect_demo.py
import os import argparse import torch from cail.env import make_env from cail.algo.algo import EXP_ALGOS from cail.utils import collect_demo def run(args): """Collect demonstrations""" env = make_env(args.env_id) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") algo = EXP_ALGOS[args.algo]( state_shape=env.observation_space.shape, action_shape=env.action_space.shape, device=device, path=args.weight ) buffer, mean_return = collect_demo( env=env, algo=algo, buffer_size=args.buffer_size, device=device, std=args.std, p_rand=args.p_rand, seed=args.seed ) if os.path.exists(os.path.join( 'buffers/Raw', args.env_id, f'size{args.buffer_size}_reward{round(mean_return, 2)}.pth' )): print('Error: demonstrations with the same reward exists') else: buffer.save(os.path.join( 'buffers/Raw', args.env_id, f'size{args.buffer_size}_reward{round(mean_return, 2)}.pth' )) if __name__ == '__main__': p = argparse.ArgumentParser() # required p.add_argument('--weight', type=str, required=True, help='path to the well-trained weights of the agent') p.add_argument('--env-id', type=str, required=True, help='name of the environment') p.add_argument('--algo', type=str, required=True, help='name of the well-trained agent') # default p.add_argument('--buffer-size', type=int, default=40000, help='size of the buffer') p.add_argument('--std', type=float, default=0.01, help='standard deviation add to the policy') p.add_argument('--p-rand', type=float, default=0.0, help='with probability of p_rand, the policy will act randomly') p.add_argument('--seed', type=int, default=0, help='random seed') args = p.parse_args() run(args)
TencentCloud/tencentcloud-sdk-nodejs-intl-en
tencentcloud/live/v20180801/models.js
<reponame>TencentCloud/tencentcloud-sdk-nodejs-intl-en<gh_stars>1-10 /* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ const AbstractModel = require("../../common/abstract_model"); /** * CreateLiveSnapshotRule request structure. * @class */ class CreateLiveSnapshotRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. Note: if this parameter is a non-empty string, the rule will take effect only for the particular stream. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * Bandwidth and traffic information. * @class */ class BillDataInfo extends AbstractModel { constructor(){ super(); /** * Time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Time point of peak value in the format of `yyyy-mm-dd HH:MM:SS`. As raw data is at a 5-minute granularity, if data at a 1-hour or 1-day granularity is queried, the time point of peak bandwidth value at the corresponding granularity will be returned. * @type {string || null} */ this.PeakTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.PeakTime = 'PeakTime' in params ? params.PeakTime : null; } } /** * EnableLiveDomain response structure. * @class */ class EnableLiveDomainResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveCert request structure. * @class */ class CreateLiveCertRequest extends AbstractModel { constructor(){ super(); /** * Certificate type. 0: user-added certificate, 1: Tencent Cloud-hosted certificate. Note: if the certificate type is 0, `HttpsCrt` and `HttpsKey` are required; If the certificate type is 1, the certificate corresponding to `CloudCertId` will be used first. If `CloudCertId` is empty, `HttpsCrt` and `HttpsKey` will be used. * @type {number || null} */ this.CertType = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Certificate content, i.e., public key. * @type {string || null} */ this.HttpsCrt = null; /** * Private key. * @type {string || null} */ this.HttpsKey = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Tencent Cloud-hosted certificate ID. * @type {string || null} */ this.CloudCertId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertType = 'CertType' in params ? params.CertType : null; this.CertName = 'CertName' in params ? params.CertName : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.HttpsKey = 'HttpsKey' in params ? params.HttpsKey : null; this.Description = 'Description' in params ? params.Description : null; this.CloudCertId = 'CloudCertId' in params ? params.CloudCertId : null; } } /** * StopRecordTask response structure. * @class */ class StopRecordTaskResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeDeliverBandwidthList response structure. * @class */ class DescribeDeliverBandwidthListResponse extends AbstractModel { constructor(){ super(); /** * Billable bandwidth of live stream relaying. * @type {Array.<BandwidthInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new BandwidthInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveRecordRule request structure. * @class */ class DeleteLiveRecordRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. Domain name+AppName+StreamName uniquely identifies a single transcoding rule. If you need to delete it, strong match is required. For example, even if AppName is blank, you need to pass in a blank string to make a strong match. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. Domain name+AppName+StreamName uniquely identifies a single transcoding rule. If you need to delete it, strong match is required. For example, even if AppName is blank, you need to pass in a blank string to make a strong match. * @type {string || null} */ this.AppName = null; /** * Stream name. Domain name+AppName+StreamName uniquely identifies a single transcoding rule. If you need to delete it, strong match is required. For example, even if AppName is blank, you need to pass in a blank string to make a strong match. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * ResumeLiveStream request structure. * @class */ class ResumeLiveStreamRequest extends AbstractModel { constructor(){ super(); /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Your push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DeleteLiveTranscodeTemplate response structure. * @class */ class DeleteLiveTranscodeTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeBillBandwidthAndFluxList response structure. * @class */ class DescribeBillBandwidthAndFluxListResponse extends AbstractModel { constructor(){ super(); /** * Time point of peak bandwidth value in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.PeakBandwidthTime = null; /** * Peak bandwidth in Mbps. * @type {number || null} */ this.PeakBandwidth = null; /** * Time point of 95th percentile bandwidth value in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.P95PeakBandwidthTime = null; /** * 95th percentile bandwidth in Mbps. * @type {number || null} */ this.P95PeakBandwidth = null; /** * Total traffic in MB. * @type {number || null} */ this.SumFlux = null; /** * Detailed data information. * @type {Array.<BillDataInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PeakBandwidthTime = 'PeakBandwidthTime' in params ? params.PeakBandwidthTime : null; this.PeakBandwidth = 'PeakBandwidth' in params ? params.PeakBandwidth : null; this.P95PeakBandwidthTime = 'P95PeakBandwidthTime' in params ? params.P95PeakBandwidthTime : null; this.P95PeakBandwidth = 'P95PeakBandwidth' in params ? params.P95PeakBandwidth : null; this.SumFlux = 'SumFlux' in params ? params.SumFlux : null; if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new BillDataInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Transcoding template information. * @class */ class TemplateInfo extends AbstractModel { constructor(){ super(); /** * Codec: h264/h265/origin. Default value: h264. origin: keep the original codec. * @type {string || null} */ this.Vcodec = null; /** * Video bitrate. Value range: 0–8,000 Kbps. If the value is 0, the original bitrate will be retained. Note: transcoding templates require a unique bitrate. The final saved bitrate may differ from the input bitrate. * @type {number || null} */ this.VideoBitrate = null; /** * Audio codec: aac. Default value: aac. Note: This parameter will not take effect for now and will be supported soon. * @type {string || null} */ this.Acodec = null; /** * Audio bitrate. Value range: 0–500 Kbps. 0 by default. * @type {number || null} */ this.AudioBitrate = null; /** * Width. Default value: 0. Value range: [0-3,000]. The value must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Width = null; /** * Height. Default value: 0. Value range: [0-3,000]. The value must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Height = null; /** * Frame rate. Default value: 0. Range: 0-60 Fps. * @type {number || null} */ this.Fps = null; /** * Keyframe interval, unit: second. Original interval by default Range: 2-6 * @type {number || null} */ this.Gop = null; /** * Rotation angle. Default value: 0. Value range: 0, 90, 180, 270 * @type {number || null} */ this.Rotate = null; /** * Encoding quality: baseline/main/high. Default value: baseline. * @type {string || null} */ this.Profile = null; /** * Whether to use the original bitrate when the set bitrate is larger than the original bitrate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.BitrateToOrig = null; /** * Whether to use the original height when the set height is higher than the original height. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.HeightToOrig = null; /** * Whether to use the original frame rate when the set frame rate is larger than the original frame rate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.FpsToOrig = null; /** * Whether to keep the video. 0: no; 1: yes. * @type {number || null} */ this.NeedVideo = null; /** * Whether to keep the audio. 0: no; 1: yes. * @type {number || null} */ this.NeedAudio = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * Whether it is a top speed codec template. 0: no, 1: yes. Default value: 0. * @type {number || null} */ this.AiTransCode = null; /** * Bitrate compression ratio of top speed code video. Target bitrate of top speed code = VideoBitrate * (1-AdaptBitratePercent) Value range: 0.0-0.5. * @type {number || null} */ this.AdaptBitratePercent = null; /** * Whether to take the shorter side as height. 0: no, 1: yes. Default value: 0. Note: this field may return `null`, indicating that no valid value is obtained. * @type {number || null} */ this.ShortEdgeAsHeight = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.VideoBitrate = 'VideoBitrate' in params ? params.VideoBitrate : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.AudioBitrate = 'AudioBitrate' in params ? params.AudioBitrate : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.Fps = 'Fps' in params ? params.Fps : null; this.Gop = 'Gop' in params ? params.Gop : null; this.Rotate = 'Rotate' in params ? params.Rotate : null; this.Profile = 'Profile' in params ? params.Profile : null; this.BitrateToOrig = 'BitrateToOrig' in params ? params.BitrateToOrig : null; this.HeightToOrig = 'HeightToOrig' in params ? params.HeightToOrig : null; this.FpsToOrig = 'FpsToOrig' in params ? params.FpsToOrig : null; this.NeedVideo = 'NeedVideo' in params ? params.NeedVideo : null; this.NeedAudio = 'NeedAudio' in params ? params.NeedAudio : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.AiTransCode = 'AiTransCode' in params ? params.AiTransCode : null; this.AdaptBitratePercent = 'AdaptBitratePercent' in params ? params.AdaptBitratePercent : null; this.ShortEdgeAsHeight = 'ShortEdgeAsHeight' in params ? params.ShortEdgeAsHeight : null; } } /** * DeleteLiveCallbackRule response structure. * @class */ class DeleteLiveCallbackRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ResumeDelayLiveStream request structure. * @class */ class ResumeDelayLiveStreamRequest extends AbstractModel { constructor(){ super(); /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DescribeLiveWatermarkRules response structure. * @class */ class DescribeLiveWatermarkRulesResponse extends AbstractModel { constructor(){ super(); /** * Watermarking rule list. * @type {Array.<RuleInfo> || null} */ this.Rules = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Rules) { this.Rules = new Array(); for (let z in params.Rules) { let obj = new RuleInfo(); obj.deserialize(params.Rules[z]); this.Rules.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveCallbackTemplate response structure. * @class */ class DescribeLiveCallbackTemplateResponse extends AbstractModel { constructor(){ super(); /** * Callback template information. * @type {CallBackTemplateInfo || null} */ this.Template = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Template) { let obj = new CallBackTemplateInfo(); obj.deserialize(params.Template) this.Template = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveSnapshotTemplate request structure. * @class */ class DeleteLiveSnapshotTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. 1. Get from the returned value of the [CreateLiveSnapshotTemplate](https://intl.cloud.tencent.com/document/product/267/32624?from_cn_redirect=1) API call. 2. You can query the list of created screencapturing templates through the [DescribeLiveSnapshotTemplates](https://intl.cloud.tencent.com/document/product/267/32619?from_cn_redirect=1) API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DescribeGroupProIspPlayInfoList response structure. * @class */ class DescribeGroupProIspPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Data content. * @type {Array.<GroupProIspDataInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new GroupProIspDataInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Push authentication key information. * @class */ class PushAuthKeyInfo extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable. 0: disabled; 1: enabled. * @type {number || null} */ this.Enable = null; /** * Master authentication key. * @type {string || null} */ this.MasterAuthKey = null; /** * Standby authentication key. * @type {string || null} */ this.BackupAuthKey = null; /** * Validity period in seconds. * @type {number || null} */ this.AuthDelta = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.MasterAuthKey = 'MasterAuthKey' in params ? params.MasterAuthKey : null; this.BackupAuthKey = 'BackupAuthKey' in params ? params.BackupAuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; } } /** * DescribeUploadStreamNums response structure. * @class */ class DescribeUploadStreamNumsResponse extends AbstractModel { constructor(){ super(); /** * Detailed data. * @type {Array.<ConcurrentRecordStreamNum> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new ConcurrentRecordStreamNum(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveRecordTemplate request structure. * @class */ class DeleteLiveRecordTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID obtained through the `DescribeRecordTemplates` API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DeleteLiveCallbackTemplate response structure. * @class */ class DeleteLiveCallbackTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveStreamOnlineList response structure. * @class */ class DescribeLiveStreamOnlineListResponse extends AbstractModel { constructor(){ super(); /** * Total number of eligible ones. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries displayed per page. * @type {number || null} */ this.PageSize = null; /** * Active push information list. * @type {Array.<StreamOnlineInfo> || null} */ this.OnlineInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; if (params.OnlineInfo) { this.OnlineInfo = new Array(); for (let z in params.OnlineInfo) { let obj = new StreamOnlineInfo(); obj.deserialize(params.OnlineInfo[z]); this.OnlineInfo.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Push quality data of a stream. * @class */ class PushQualityData extends AbstractModel { constructor(){ super(); /** * Data time in the format of `%Y-%m-%d %H:%M:%S.%ms` and accurate down to the millisecond level. * @type {string || null} */ this.Time = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Push client IP. * @type {string || null} */ this.ClientIp = null; /** * Push start time in the format of `%Y-%m-%d %H:%M:%S.%ms` and accurate down to the millisecond level. * @type {string || null} */ this.BeginPushTime = null; /** * Resolution information. * @type {string || null} */ this.Resolution = null; /** * Video codec. * @type {string || null} */ this.VCodec = null; /** * Audio codec. * @type {string || null} */ this.ACodec = null; /** * Push serial number, which uniquely identifies a push. * @type {string || null} */ this.Sequence = null; /** * Video frame rate. * @type {number || null} */ this.VideoFps = null; /** * Video bitrate in bps. * @type {number || null} */ this.VideoRate = null; /** * Audio frame rate. * @type {number || null} */ this.AudioFps = null; /** * Audio bitrate in bps. * @type {number || null} */ this.AudioRate = null; /** * Local elapsed time in milliseconds. The greater the difference between audio/video elapsed time and local elapsed time, the poorer the push quality and the more serious the upstream lag. * @type {number || null} */ this.LocalTs = null; /** * Video elapsed time in milliseconds. * @type {number || null} */ this.VideoTs = null; /** * Audio elapsed time in milliseconds. * @type {number || null} */ this.AudioTs = null; /** * Video bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaVideoRate = null; /** * Audio bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaAudioRate = null; /** * Frame rate in `metadata`. * @type {number || null} */ this.MateFps = null; /** * Push parameter * @type {string || null} */ this.StreamParam = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.AppName = 'AppName' in params ? params.AppName : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.BeginPushTime = 'BeginPushTime' in params ? params.BeginPushTime : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; this.VCodec = 'VCodec' in params ? params.VCodec : null; this.ACodec = 'ACodec' in params ? params.ACodec : null; this.Sequence = 'Sequence' in params ? params.Sequence : null; this.VideoFps = 'VideoFps' in params ? params.VideoFps : null; this.VideoRate = 'VideoRate' in params ? params.VideoRate : null; this.AudioFps = 'AudioFps' in params ? params.AudioFps : null; this.AudioRate = 'AudioRate' in params ? params.AudioRate : null; this.LocalTs = 'LocalTs' in params ? params.LocalTs : null; this.VideoTs = 'VideoTs' in params ? params.VideoTs : null; this.AudioTs = 'AudioTs' in params ? params.AudioTs : null; this.MetaVideoRate = 'MetaVideoRate' in params ? params.MetaVideoRate : null; this.MetaAudioRate = 'MetaAudioRate' in params ? params.MetaAudioRate : null; this.MateFps = 'MateFps' in params ? params.MateFps : null; this.StreamParam = 'StreamParam' in params ? params.StreamParam : null; } } /** * UnBindLiveDomainCert response structure. * @class */ class UnBindLiveDomainCertResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLivePlayAuthKey request structure. * @class */ class ModifyLivePlayAuthKeyRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable. 0: disabled; 1: enabled. If this parameter is left empty, the current value will not be modified. * @type {number || null} */ this.Enable = null; /** * Authentication key. If this parameter is left empty, the current value will not be modified. * @type {string || null} */ this.AuthKey = null; /** * Validity period in seconds. If this parameter is left empty, the current value will not be modified. * @type {number || null} */ this.AuthDelta = null; /** * Backup authentication key. If this parameter is left empty, the current value will not be modified. * @type {string || null} */ this.AuthBackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.AuthKey = 'AuthKey' in params ? params.AuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; this.AuthBackKey = 'AuthBackKey' in params ? params.AuthBackKey : null; } } /** * DescribeLiveDelayInfoList request structure. * @class */ class DescribeLiveDelayInfoListRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * Domain name certificate information * @class */ class DomainCertInfo extends AbstractModel { constructor(){ super(); /** * Certificate ID. * @type {number || null} */ this.CertId = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Creation time in UTC format. * @type {string || null} */ this.CreateTime = null; /** * Certificate content. * @type {string || null} */ this.HttpsCrt = null; /** * Certificate type. 0: user-added certificate 1: Tencent Cloud-hosted certificate. * @type {number || null} */ this.CertType = null; /** * Certificate expiration time in UTC format. * @type {string || null} */ this.CertExpireTime = null; /** * Domain name that uses this certificate. * @type {string || null} */ this.DomainName = null; /** * Certificate status. * @type {number || null} */ this.Status = null; /** * List of domain names in the certificate. ["*.x.com"] for example. Note: this field may return `null`, indicating that no valid values can be obtained. * @type {Array.<string> || null} */ this.CertDomains = null; /** * Tencent Cloud SSL certificate ID. Note: this field may return `null`, indicating that no valid values can be obtained. * @type {string || null} */ this.CloudCertId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.CertName = 'CertName' in params ? params.CertName : null; this.Description = 'Description' in params ? params.Description : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.CertType = 'CertType' in params ? params.CertType : null; this.CertExpireTime = 'CertExpireTime' in params ? params.CertExpireTime : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Status = 'Status' in params ? params.Status : null; this.CertDomains = 'CertDomains' in params ? params.CertDomains : null; this.CloudCertId = 'CloudCertId' in params ? params.CloudCertId : null; } } /** * Recording template information * @class */ class RecordTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Message description * @type {string || null} */ this.Description = null; /** * FLV recording parameter. * @type {RecordParam || null} */ this.FlvParam = null; /** * HLS recording parameter. * @type {RecordParam || null} */ this.HlsParam = null; /** * MP4 recording parameter. * @type {RecordParam || null} */ this.Mp4Param = null; /** * AAC recording parameter. * @type {RecordParam || null} */ this.AacParam = null; /** * 0: LVB, 1: LCB. * @type {number || null} */ this.IsDelayLive = null; /** * Custom HLS recording parameter * @type {HlsSpecialParam || null} */ this.HlsSpecialParam = null; /** * MP3 recording parameter. * @type {RecordParam || null} */ this.Mp3Param = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; if (params.FlvParam) { let obj = new RecordParam(); obj.deserialize(params.FlvParam) this.FlvParam = obj; } if (params.HlsParam) { let obj = new RecordParam(); obj.deserialize(params.HlsParam) this.HlsParam = obj; } if (params.Mp4Param) { let obj = new RecordParam(); obj.deserialize(params.Mp4Param) this.Mp4Param = obj; } if (params.AacParam) { let obj = new RecordParam(); obj.deserialize(params.AacParam) this.AacParam = obj; } this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; if (params.HlsSpecialParam) { let obj = new HlsSpecialParam(); obj.deserialize(params.HlsSpecialParam) this.HlsSpecialParam = obj; } if (params.Mp3Param) { let obj = new RecordParam(); obj.deserialize(params.Mp3Param) this.Mp3Param = obj; } } } /** * DeleteLiveTranscodeRule response structure. * @class */ class DeleteLiveTranscodeRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Number of concurrent recording channels * @class */ class ConcurrentRecordStreamNum extends AbstractModel { constructor(){ super(); /** * Time point. * @type {string || null} */ this.Time = null; /** * Number of channels. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Num = 'Num' in params ? params.Num : null; } } /** * DescribeStreamPlayInfoList response structure. * @class */ class DescribeStreamPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Statistics list at a 1-minute granularity. * @type {Array.<DayStreamPlayInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new DayStreamPlayInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeScreenShotSheetNumList response structure. * @class */ class DescribeScreenShotSheetNumListResponse extends AbstractModel { constructor(){ super(); /** * Data information list. * @type {Array.<TimeValue> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new TimeValue(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLiveSnapshotTemplate response structure. * @class */ class ModifyLiveSnapshotTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLivePushAuthKey request structure. * @class */ class ModifyLivePushAuthKeyRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable. 0: disabled; 1: enabled. If this parameter is left empty, the current value will not be modified. * @type {number || null} */ this.Enable = null; /** * Master authentication key. If this parameter is left empty, the current value will not be modified. * @type {string || null} */ this.MasterAuthKey = null; /** * Backup authentication key. If this parameter is left empty, the current value will not be modified. * @type {string || null} */ this.BackupAuthKey = null; /** * Validity period in seconds. * @type {number || null} */ this.AuthDelta = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.MasterAuthKey = 'MasterAuthKey' in params ? params.MasterAuthKey : null; this.BackupAuthKey = 'BackupAuthKey' in params ? params.BackupAuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; } } /** * DeleteLiveCallbackTemplate request structure. * @class */ class DeleteLiveCallbackTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. 1. Get the template ID in the returned value of the [CreateLiveCallbackTemplate](https://intl.cloud.tencent.com/document/product/267/32637?from_cn_redirect=1) API call. 2. You can query the list of created templates through the [DescribeLiveCallbackTemplates](https://intl.cloud.tencent.com/document/product/267/32632?from_cn_redirect=1) API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DescribeLiveStreamState request structure. * @class */ class DescribeLiveStreamStateRequest extends AbstractModel { constructor(){ super(); /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Your push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DescribeLivePlayAuthKey response structure. * @class */ class DescribeLivePlayAuthKeyResponse extends AbstractModel { constructor(){ super(); /** * Playback authentication key information. * @type {PlayAuthKeyInfo || null} */ this.PlayAuthKeyInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.PlayAuthKeyInfo) { let obj = new PlayAuthKeyInfo(); obj.deserialize(params.PlayAuthKeyInfo) this.PlayAuthKeyInfo = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveCallbackTemplates request structure. * @class */ class DescribeLiveCallbackTemplatesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * LVB domain name information * @class */ class DomainInfo extends AbstractModel { constructor(){ super(); /** * LVB domain name. * @type {string || null} */ this.Name = null; /** * Domain name type: 0: push. 1: playback. * @type {number || null} */ this.Type = null; /** * Domain name status: 0: deactivated. 1: activated. * @type {number || null} */ this.Status = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Whether there is a CNAME record pointing to a fixed rule domain name: 0: no. 1: yes. * @type {number || null} */ this.BCName = null; /** * Domain name corresponding to CNAME record. * @type {string || null} */ this.TargetDomain = null; /** * Playback region. This parameter is valid only if `Type` is 1. 1: in Mainland China. 2: global. 3: outside Mainland China. * @type {number || null} */ this.PlayType = null; /** * Whether it is LCB: 0: LVB. 1: LCB. * @type {number || null} */ this.IsDelayLive = null; /** * Information of currently used CNAME record. * @type {string || null} */ this.CurrentCName = null; /** * Disused parameter, which can be ignored. * @type {number || null} */ this.RentTag = null; /** * Disused parameter, which can be ignored. * @type {string || null} */ this.RentExpireTime = null; /** * 0: LVB. 1: LVB on Mini Program. Note: this field may return null, indicating that no valid values can be obtained. * @type {number || null} */ this.IsMiniProgramLive = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.Type = 'Type' in params ? params.Type : null; this.Status = 'Status' in params ? params.Status : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.BCName = 'BCName' in params ? params.BCName : null; this.TargetDomain = 'TargetDomain' in params ? params.TargetDomain : null; this.PlayType = 'PlayType' in params ? params.PlayType : null; this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; this.CurrentCName = 'CurrentCName' in params ? params.CurrentCName : null; this.RentTag = 'RentTag' in params ? params.RentTag : null; this.RentExpireTime = 'RentExpireTime' in params ? params.RentExpireTime : null; this.IsMiniProgramLive = 'IsMiniProgramLive' in params ? params.IsMiniProgramLive : null; } } /** * DescribeLiveTranscodeRules request structure. * @class */ class DescribeLiveTranscodeRulesRequest extends AbstractModel { constructor(){ super(); /** * An array of template IDs to be filtered. * @type {Array.<number> || null} */ this.TemplateIds = null; /** * An array of domain names to be filtered. * @type {Array.<string> || null} */ this.DomainNames = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateIds = 'TemplateIds' in params ? params.TemplateIds : null; this.DomainNames = 'DomainNames' in params ? params.DomainNames : null; } } /** * DeleteLiveSnapshotRule request structure. * @class */ class DeleteLiveSnapshotRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DescribePlayErrorCodeDetailInfoList request structure. * @class */ class DescribePlayErrorCodeDetailInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start time (Beijing time), In the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time), In the format of `yyyy-mm-dd HH:MM:SS`. Note: `EndTime` and `StartTime` only support querying data for the last day. * @type {string || null} */ this.EndTime = null; /** * Query granularity: 1: 1-minute granularity. * @type {number || null} */ this.Granularity = null; /** * Yes. Valid values: "4xx", "5xx". Mixed codes in the format of `4xx,5xx` are also supported. * @type {string || null} */ this.StatType = null; /** * Playback domain name list. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Region. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China), China (data for China, including Hong Kong, Macao, and Taiwan), Foreign (data for regions outside China, excluding Hong Kong, Macao, and Taiwan), Global (default). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Granularity = 'Granularity' in params ? params.Granularity : null; this.StatType = 'StatType' in params ? params.StatType : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; } } /** * DescribeBillBandwidthAndFluxList request structure. * @class */ class DescribeBillBandwidthAndFluxListRequest extends AbstractModel { constructor(){ super(); /** * Start time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End time point in the format of yyyy-mm-dd HH:MM:SS. The difference between the start time and end time cannot be greater than 31 days. Data in the last 3 years can be queried. * @type {string || null} */ this.EndTime = null; /** * LVB playback domain name. If this parameter is left empty, full data will be queried. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Valid values: Mainland: query data for Mainland China, Oversea: query data for regions outside Mainland China, Default: query data for all regions. Note: LEB only supports querying data for all regions. * @type {string || null} */ this.MainlandOrOversea = null; /** * Data granularity. Valid values: 5: 5-minute granularity (the query time span should be within 1 day), 60: 1-hour granularity (the query time span should be within one month), 1440: 1-day granularity (the query time span should be within one month). Default value: 5. * @type {number || null} */ this.Granularity = null; /** * Service name. Valid values: LVB, LEB. The sum of LVB and LEB usage will be returned if this parameter is left empty. * @type {string || null} */ this.ServiceName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.Granularity = 'Granularity' in params ? params.Granularity : null; this.ServiceName = 'ServiceName' in params ? params.ServiceName : null; } } /** * General stream mix output parameter. * @class */ class CommonMixOutputParams extends AbstractModel { constructor(){ super(); /** * Output stream name. * @type {string || null} */ this.OutputStreamName = null; /** * Output stream type. Valid values: [0,1]. If this parameter is left empty, 0 will be used by default. If the output stream is a stream in the input stream list, enter 0. If you want the stream mix result to be a new stream, enter 1. If this value is 1, `output_stream_id` cannot appear in `input_stram_list`, and there cannot be a stream with the same ID on the LVB backend. * @type {number || null} */ this.OutputStreamType = null; /** * Output stream bitrate. Value range: [1,50000]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamBitRate = null; /** * Output stream GOP size. Value range: [1,10]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamGop = null; /** * Output stream frame rate. Value range: [1,60]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamFrameRate = null; /** * Output stream audio bitrate. Value range: [1,500] If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioBitRate = null; /** * Output stream audio sample rate. Valid values: [96000, 88200, 64000, 48000, 44100, 32000,24000, 22050, 16000, 12000, 11025, 8000]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioSampleRate = null; /** * Output stream audio sound channel. Valid values: [1,2]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioChannels = null; /** * SEI information in output stream. If there are no special needs, leave it empty. * @type {string || null} */ this.MixSei = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.OutputStreamName = 'OutputStreamName' in params ? params.OutputStreamName : null; this.OutputStreamType = 'OutputStreamType' in params ? params.OutputStreamType : null; this.OutputStreamBitRate = 'OutputStreamBitRate' in params ? params.OutputStreamBitRate : null; this.OutputStreamGop = 'OutputStreamGop' in params ? params.OutputStreamGop : null; this.OutputStreamFrameRate = 'OutputStreamFrameRate' in params ? params.OutputStreamFrameRate : null; this.OutputAudioBitRate = 'OutputAudioBitRate' in params ? params.OutputAudioBitRate : null; this.OutputAudioSampleRate = 'OutputAudioSampleRate' in params ? params.OutputAudioSampleRate : null; this.OutputAudioChannels = 'OutputAudioChannels' in params ? params.OutputAudioChannels : null; this.MixSei = 'MixSei' in params ? params.MixSei : null; } } /** * DescribeUploadStreamNums request structure. * @class */ class DescribeUploadStreamNumsRequest extends AbstractModel { constructor(){ super(); /** * Start time point in the format of yyyy-mm-dd HH:MM:SS. * @type {string || null} */ this.StartTime = null; /** * End time point in the format of yyyy-mm-dd HH:MM:SS. The difference between the start time and end time cannot be greater than 31 days. Data in the last 31 days can be queried. * @type {string || null} */ this.EndTime = null; /** * LVB domain names. If this parameter is left empty, data of all domain names will be queried. * @type {Array.<string> || null} */ this.Domains = null; /** * Time granularity of the data. Valid values: 5: 5-minute granularity (the query period is up to 1 day) 1440: 1-day granularity (the query period is up to 1 month) Default value: 5 * @type {number || null} */ this.Granularity = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Domains = 'Domains' in params ? params.Domains : null; this.Granularity = 'Granularity' in params ? params.Granularity : null; } } /** * DescribeLiveSnapshotRules response structure. * @class */ class DescribeLiveSnapshotRulesResponse extends AbstractModel { constructor(){ super(); /** * Rule list. * @type {Array.<RuleInfo> || null} */ this.Rules = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Rules) { this.Rules = new Array(); for (let z in params.Rules) { let obj = new RuleInfo(); obj.deserialize(params.Rules[z]); this.Rules.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveTranscodeDetailInfo response structure. * @class */ class DescribeLiveTranscodeDetailInfoResponse extends AbstractModel { constructor(){ super(); /** * Statistics list. * @type {Array.<TranscodeDetailInfo> || null} */ this.DataInfoList = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. * @type {number || null} */ this.PageSize = null; /** * Total number. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new TranscodeDetailInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveDomain request structure. * @class */ class DescribeLiveDomainRequest extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * DescribeLiveStreamPublishedList request structure. * @class */ class DescribeLiveStreamPublishedListRequest extends AbstractModel { constructor(){ super(); /** * Your push domain name. * @type {string || null} */ this.DomainName = null; /** * End time. In UTC format, such as 2016-06-30T19:00:00Z. This cannot be after the current time. Note: The difference between EndTime and StartTime cannot be greater than 30 days. * @type {string || null} */ this.EndTime = null; /** * Start time. In UTC format, such as 2016-06-29T19:00:00Z. This supports querying data in the past 60 days. * @type {string || null} */ this.StartTime = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. Fuzzy match is not supported. * @type {string || null} */ this.AppName = null; /** * Page number to get. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Maximum value: 100 Valid values: integers between 10 and 100 Default value: 10 * @type {number || null} */ this.PageSize = null; /** * Stream name, which supports fuzzy match. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.AppName = 'AppName' in params ? params.AppName : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DeleteLiveTranscodeRule request structure. * @class */ class DeleteLiveTranscodeRuleRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * CreateLiveRecordRule request structure. * @class */ class CreateLiveRecordRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Stream name. Note: If the parameter is a non-empty string, the rule will be only applicable to the particular stream. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DescribeLiveSnapshotTemplates request structure. * @class */ class DescribeLiveSnapshotTemplatesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * AddLiveWatermark response structure. * @class */ class AddLiveWatermarkResponse extends AbstractModel { constructor(){ super(); /** * Watermark ID. * @type {number || null} */ this.WatermarkId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveStreamPushInfoList response structure. * @class */ class DescribeLiveStreamPushInfoListResponse extends AbstractModel { constructor(){ super(); /** * Live stream statistics list. * @type {Array.<PushDataInfo> || null} */ this.DataInfoList = null; /** * Total number of live streams. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Page number where the current data resides. * @type {number || null} */ this.PageNum = null; /** * Number of live streams per page. * @type {number || null} */ this.PageSize = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new PushDataInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveDomainCert response structure. * @class */ class DescribeLiveDomainCertResponse extends AbstractModel { constructor(){ super(); /** * Certificate information. * @type {DomainCertInfo || null} */ this.DomainCertInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DomainCertInfo) { let obj = new DomainCertInfo(); obj.deserialize(params.DomainCertInfo) this.DomainCertInfo = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveRecordTemplate request structure. * @class */ class DescribeLiveRecordTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID obtained by [DescribeLiveRecordTemplates](https://intl.cloud.tencent.com/document/product/267/32609?from_cn_redirect=1). * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * ModifyLiveDomainCert request structure. * @class */ class ModifyLiveDomainCertRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Certificate ID. * @type {number || null} */ this.CertId = null; /** * Status. 0: off, 1: on. * @type {number || null} */ this.Status = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.CertId = 'CertId' in params ? params.CertId : null; this.Status = 'Status' in params ? params.Status : null; } } /** * CreateLiveWatermarkRule response structure. * @class */ class CreateLiveWatermarkRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeProIspPlaySumInfoList request structure. * @class */ class DescribeProIspPlaySumInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start time (Beijing time). In the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time). In the format of `yyyy-mm-dd HH:MM:SS`. Note: `EndTime` and `StartTime` only support querying data for the last day. * @type {string || null} */ this.EndTime = null; /** * Statistics type. Valid values: Province (district), Isp (ISP), CountryOrArea (country or region). * @type {string || null} */ this.StatType = null; /** * Playback domain name list. If it is left empty, it refers to all playback domain names. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Page number. Value range: [1,1000]. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Region. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China), China (data for China, including Hong Kong, Macao, and Taiwan), Foreign (data for regions outside China, excluding Hong Kong, Macao, and Taiwan), Global (default). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; /** * Language used in the output field. Valid values: Chinese (default), English. Currently, country/region, district, and ISP parameters support multiple languages. * @type {string || null} */ this.OutLanguage = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.StatType = 'StatType' in params ? params.StatType : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.OutLanguage = 'OutLanguage' in params ? params.OutLanguage : null; } } /** * DescribeDeliverBandwidthList request structure. * @class */ class DescribeDeliverBandwidthListRequest extends AbstractModel { constructor(){ super(); /** * Start time in the format of "%Y-%m-%d %H:%M:%S". * @type {string || null} */ this.StartTime = null; /** * End time in the format of "%Y-%m-%d %H:%M:%S". Data in the last 3 months can be queried, and the query period is up to 1 month. * @type {string || null} */ this.EndTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; } } /** * Total occurrences of each status code. Most HTTP return codes are supported. * @class */ class PlayCodeTotalInfo extends AbstractModel { constructor(){ super(); /** * HTTP code. Valid values: 400, 403, 404, 500, 502, 503, 504. * @type {string || null} */ this.Code = null; /** * Total occurrences. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Code = 'Code' in params ? params.Code : null; this.Num = 'Num' in params ? params.Num : null; } } /** * AddLiveWatermark request structure. * @class */ class AddLiveWatermarkRequest extends AbstractModel { constructor(){ super(); /** * Watermark image URL. Unallowed characters in the URL: ;(){}$>`#"\'| * @type {string || null} */ this.PictureUrl = null; /** * Watermark name. Up to 16 bytes. * @type {string || null} */ this.WatermarkName = null; /** * Display position: X-axis offset in %. Default value: 0. * @type {number || null} */ this.XPosition = null; /** * Display position: Y-axis offset in %. Default value: 0. * @type {number || null} */ this.YPosition = null; /** * Watermark width or its percentage of the live streaming video width. It is recommended to just specify either height or width as the other will be scaled proportionally to avoid distortions. The original width is used by default. * @type {number || null} */ this.Width = null; /** * Watermark height, which is set by entering a percentage of the live stream image’s original height. You are advised to set either the height or width as the other will be scaled proportionally to avoid distortions. Default value: original height. * @type {number || null} */ this.Height = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PictureUrl = 'PictureUrl' in params ? params.PictureUrl : null; this.WatermarkName = 'WatermarkName' in params ? params.WatermarkName : null; this.XPosition = 'XPosition' in params ? params.XPosition : null; this.YPosition = 'YPosition' in params ? params.YPosition : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; } } /** * ModifyLiveTranscodeTemplate response structure. * @class */ class ModifyLiveTranscodeTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * The bandwidth information of a country, `DescribeAreaBillBandwidthAndFluxList` output parameter * @class */ class BillCountryInfo extends AbstractModel { constructor(){ super(); /** * Country * @type {string || null} */ this.Name = null; /** * Detailed bandwidth information * @type {Array.<BillDataInfo> || null} */ this.BandInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; if (params.BandInfoList) { this.BandInfoList = new Array(); for (let z in params.BandInfoList) { let obj = new BillDataInfo(); obj.deserialize(params.BandInfoList[z]); this.BandInfoList.push(obj); } } } } /** * ModifyLiveRecordTemplate response structure. * @class */ class ModifyLiveRecordTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLivePlayDomain request structure. * @class */ class ModifyLivePlayDomainRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Pull domain name type. 1: Mainland China. 2: global, 3: outside Mainland China * @type {number || null} */ this.PlayType = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.PlayType = 'PlayType' in params ? params.PlayType : null; } } /** * DeleteLiveRecordTemplate response structure. * @class */ class DeleteLiveRecordTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveWatermark request structure. * @class */ class DescribeLiveWatermarkRequest extends AbstractModel { constructor(){ super(); /** * Watermark ID returned by the `DescribeLiveWatermarks` API. * @type {number || null} */ this.WatermarkId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; } } /** * Playback error code information * @class */ class ProIspPlayCodeDataInfo extends AbstractModel { constructor(){ super(); /** * Country or region. * @type {string || null} */ this.CountryAreaName = null; /** * District. * @type {string || null} */ this.ProvinceName = null; /** * ISP. * @type {string || null} */ this.IspName = null; /** * Occurrences of 2xx error codes. * @type {number || null} */ this.Code2xx = null; /** * Occurrences of 3xx error codes. * @type {number || null} */ this.Code3xx = null; /** * Occurrences of 4xx error codes. * @type {number || null} */ this.Code4xx = null; /** * Occurrences of 5xx error codes. * @type {number || null} */ this.Code5xx = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CountryAreaName = 'CountryAreaName' in params ? params.CountryAreaName : null; this.ProvinceName = 'ProvinceName' in params ? params.ProvinceName : null; this.IspName = 'IspName' in params ? params.IspName : null; this.Code2xx = 'Code2xx' in params ? params.Code2xx : null; this.Code3xx = 'Code3xx' in params ? params.Code3xx : null; this.Code4xx = 'Code4xx' in params ? params.Code4xx : null; this.Code5xx = 'Code5xx' in params ? params.Code5xx : null; } } /** * General stream mix layout parameter. * @class */ class CommonMixLayoutParams extends AbstractModel { constructor(){ super(); /** * Input layer. Value range: [1,16]. 1) For `image_layer` of background stream (i.e., main host video image or canvas), enter 1. 2) For audio stream mix, this parameter is also required. * @type {number || null} */ this.ImageLayer = null; /** * Input type. Value range: [0,5]. If this parameter is left empty, 0 will be used by default. 0: the input stream is audio/video. 2: the input stream is image. 3: the input stream is canvas. 4: the input stream is audio. 5: the input stream is pure video. * @type {number || null} */ this.InputType = null; /** * Output width of input video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, the input stream width will be used by default. If percentage is used, the expected output is (percentage * background width). * @type {number || null} */ this.ImageWidth = null; /** * Output height of input video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, the input stream height will be used by default. If percentage is used, the expected output is (percentage * background height). * @type {number || null} */ this.ImageHeight = null; /** * X-axis offset of input in output video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, 0 will be used by default. Horizontal offset from the top-left corner of main host background video image. If percentage is used, the expected output is (percentage * background width). * @type {number || null} */ this.LocationX = null; /** * Y-axis offset of input in output video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, 0 will be used by default. Vertical offset from the top-left corner of main host background video image. If percentage is used, the expected output is (percentage * background width) * @type {number || null} */ this.LocationY = null; /** * When `InputType` is 3 (canvas), this value indicates the canvas color. Commonly used colors include: Red: 0xcc0033. Yellow: 0xcc9900. Green: 0xcccc33. Blue: 0x99CCFF. Black: 0x000000. White: 0xFFFFFF. Gray: 0x999999 * @type {string || null} */ this.Color = null; /** * When `InputType` is 2 (image), this value is the watermark ID. * @type {number || null} */ this.WatermarkId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ImageLayer = 'ImageLayer' in params ? params.ImageLayer : null; this.InputType = 'InputType' in params ? params.InputType : null; this.ImageWidth = 'ImageWidth' in params ? params.ImageWidth : null; this.ImageHeight = 'ImageHeight' in params ? params.ImageHeight : null; this.LocationX = 'LocationX' in params ? params.LocationX : null; this.LocationY = 'LocationY' in params ? params.LocationY : null; this.Color = 'Color' in params ? params.Color : null; this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; } } /** * DescribeLiveDomainCert request structure. * @class */ class DescribeLiveDomainCertRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * DescribeLiveStreamEventList request structure. * @class */ class DescribeLiveStreamEventListRequest extends AbstractModel { constructor(){ super(); /** * Start time. In UTC format, such as 2018-12-29T19:00:00Z. This supports querying the history of 60 days. * @type {string || null} */ this.StartTime = null; /** * End time. In UTC format, such as 2018-12-29T20:00:00Z. This cannot be after the current time and cannot be more than 30 days after the start time. * @type {string || null} */ this.EndTime = null; /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name; query with wildcard (*) is not supported; fuzzy match by default. The IsStrict field can be used to change to exact query. * @type {string || null} */ this.StreamName = null; /** * Page number to get. Default value: 1. Note: Currently, query for up to 10,000 entries is supported. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Maximum value: 100. Value range: any integer between 1 and 100. Default value: 10. Note: currently, query for up to 10,000 entries is supported. * @type {number || null} */ this.PageSize = null; /** * Whether to filter. No filtering by default. 0: No filtering at all. 1: Filter out the failing streams and return only the successful ones. * @type {number || null} */ this.IsFilter = null; /** * Whether to query exactly. Fuzzy match by default. 0: Fuzzy match. 1: Exact query. Note: This parameter takes effect when StreamName is used. * @type {number || null} */ this.IsStrict = null; /** * Whether to display in ascending order by end time. Descending order by default. 0: Descending. 1: Ascending. * @type {number || null} */ this.IsAsc = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.IsFilter = 'IsFilter' in params ? params.IsFilter : null; this.IsStrict = 'IsStrict' in params ? params.IsStrict : null; this.IsAsc = 'IsAsc' in params ? params.IsAsc : null; } } /** * Callback template information. * @class */ class CallBackTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Stream starting callback URL. * @type {string || null} */ this.StreamBeginNotifyUrl = null; /** * Stream mixing callback URL (disused) * @type {string || null} */ this.StreamMixNotifyUrl = null; /** * Interruption callback URL. * @type {string || null} */ this.StreamEndNotifyUrl = null; /** * Recording callback URL. * @type {string || null} */ this.RecordNotifyUrl = null; /** * Screencapturing callback URL. * @type {string || null} */ this.SnapshotNotifyUrl = null; /** * Porn detection callback URL. * @type {string || null} */ this.PornCensorshipNotifyUrl = null; /** * Callback authentication key. * @type {string || null} */ this.CallbackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.StreamBeginNotifyUrl = 'StreamBeginNotifyUrl' in params ? params.StreamBeginNotifyUrl : null; this.StreamMixNotifyUrl = 'StreamMixNotifyUrl' in params ? params.StreamMixNotifyUrl : null; this.StreamEndNotifyUrl = 'StreamEndNotifyUrl' in params ? params.StreamEndNotifyUrl : null; this.RecordNotifyUrl = 'RecordNotifyUrl' in params ? params.RecordNotifyUrl : null; this.SnapshotNotifyUrl = 'SnapshotNotifyUrl' in params ? params.SnapshotNotifyUrl : null; this.PornCensorshipNotifyUrl = 'PornCensorshipNotifyUrl' in params ? params.PornCensorshipNotifyUrl : null; this.CallbackKey = 'CallbackKey' in params ? params.CallbackKey : null; } } /** * DescribePlayErrorCodeSumInfoList response structure. * @class */ class DescribePlayErrorCodeSumInfoListResponse extends AbstractModel { constructor(){ super(); /** * Information of error codes starting with 2, 3, 4, or 5 by district and ISP. * @type {Array.<ProIspPlayCodeDataInfo> || null} */ this.ProIspInfoList = null; /** * Total occurrences of all status codes. * @type {number || null} */ this.TotalCodeAll = null; /** * Occurrences of 4xx status codes. * @type {number || null} */ this.TotalCode4xx = null; /** * Occurrences of 5xx status codes. * @type {number || null} */ this.TotalCode5xx = null; /** * Total occurrences of each status code. * @type {Array.<PlayCodeTotalInfo> || null} */ this.TotalCodeList = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. * @type {number || null} */ this.PageSize = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Total number of results. * @type {number || null} */ this.TotalNum = null; /** * Occurrences of 2xx status codes. * @type {number || null} */ this.TotalCode2xx = null; /** * Occurrences of 3xx status codes. * @type {number || null} */ this.TotalCode3xx = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.ProIspInfoList) { this.ProIspInfoList = new Array(); for (let z in params.ProIspInfoList) { let obj = new ProIspPlayCodeDataInfo(); obj.deserialize(params.ProIspInfoList[z]); this.ProIspInfoList.push(obj); } } this.TotalCodeAll = 'TotalCodeAll' in params ? params.TotalCodeAll : null; this.TotalCode4xx = 'TotalCode4xx' in params ? params.TotalCode4xx : null; this.TotalCode5xx = 'TotalCode5xx' in params ? params.TotalCode5xx : null; if (params.TotalCodeList) { this.TotalCodeList = new Array(); for (let z in params.TotalCodeList) { let obj = new PlayCodeTotalInfo(); obj.deserialize(params.TotalCodeList[z]); this.TotalCodeList.push(obj); } } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalCode2xx = 'TotalCode2xx' in params ? params.TotalCode2xx : null; this.TotalCode3xx = 'TotalCode3xx' in params ? params.TotalCode3xx : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * UnBindLiveDomainCert request structure. * @class */ class UnBindLiveDomainCertRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Valid values: `gray`: unbind the canary certificate `formal` (default): unbind the formal certificate `formal` will be used if no value is passed in * @type {string || null} */ this.Type = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Type = 'Type' in params ? params.Type : null; } } /** * DeleteLiveRecord response structure. * @class */ class DeleteLiveRecordResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeScreenShotSheetNumList request structure. * @class */ class DescribeScreenShotSheetNumListRequest extends AbstractModel { constructor(){ super(); /** * Start time in UTC time in the format of `yyyy-mm-ddTHH:MM:SSZ`. * @type {string || null} */ this.StartTime = null; /** * End time in UTC time in the format of `yyyy-mm-ddTHH:MM:SSZ`. Data for the last year can be queried. * @type {string || null} */ this.EndTime = null; /** * Region information. Valid values: Mainland, Oversea. The former is to query data within Mainland China, while the latter outside Mainland China. If this parameter is left empty, data of all regions will be queried. * @type {string || null} */ this.Zone = null; /** * Push domain name (data at the domain name level after November 1, 2019 can be queried). * @type {Array.<string> || null} */ this.PushDomains = null; /** * Data dimension. The data has a delay of one and a half hours. Valid values: 1. Minute (5-minute granularity, which supports a maximum query time range of 31 days); 2. Day (1-day granularity, which is the default value and supports a maximum query time range of 186 days). * @type {string || null} */ this.Granularity = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Zone = 'Zone' in params ? params.Zone : null; this.PushDomains = 'PushDomains' in params ? params.PushDomains : null; this.Granularity = 'Granularity' in params ? params.Granularity : null; } } /** * ForbidLiveStream request structure. * @class */ class ForbidLiveStreamRequest extends AbstractModel { constructor(){ super(); /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; /** * Your push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Time to resume the stream in UTC format, such as 2018-11-29T19:00:00Z. Notes: 1. The duration of forbidding is 7 days by default and can be up to 90 days. 2. The Beijing time is in UTC+8. This value should be in the format as required by ISO 8601. For more information, please see [ISO Date and Time Format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @type {string || null} */ this.ResumeTime = null; /** * Reason for forbidding. Note: Be sure to enter the reason for forbidding to avoid any faulty operations. Length limit: 2,048 bytes. * @type {string || null} */ this.Reason = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.ResumeTime = 'ResumeTime' in params ? params.ResumeTime : null; this.Reason = 'Reason' in params ? params.Reason : null; } } /** * DescribeLiveDomains response structure. * @class */ class DescribeLiveDomainsResponse extends AbstractModel { constructor(){ super(); /** * Total number of results. * @type {number || null} */ this.AllCount = null; /** * List of domain name details. * @type {Array.<DomainInfo> || null} */ this.DomainList = null; /** * The number of domain names that can be added Note: this field may return `null`, indicating that no valid values can be obtained. * @type {number || null} */ this.CreateLimitCount = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AllCount = 'AllCount' in params ? params.AllCount : null; if (params.DomainList) { this.DomainList = new Array(); for (let z in params.DomainList) { let obj = new DomainInfo(); obj.deserialize(params.DomainList[z]); this.DomainList.push(obj); } } this.CreateLimitCount = 'CreateLimitCount' in params ? params.CreateLimitCount : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Metric value at a specified point in time. * @class */ class TimeValue extends AbstractModel { constructor(){ super(); /** * UTC time in the format of `yyyy-mm-ddTHH:MM:SSZ`. * @type {string || null} */ this.Time = null; /** * Value. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Num = 'Num' in params ? params.Num : null; } } /** * Queries active push information * @class */ class StreamOnlineInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push time list * @type {Array.<PublishTime> || null} */ this.PublishTimeList = null; /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; if (params.PublishTimeList) { this.PublishTimeList = new Array(); for (let z in params.PublishTimeList) { let obj = new PublishTime(); obj.deserialize(params.PublishTimeList[z]); this.PublishTimeList.push(obj); } } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * CreateLiveRecord response structure. * @class */ class CreateLiveRecordResponse extends AbstractModel { constructor(){ super(); /** * Task ID, which uniquely identifies a recording task globally. * @type {number || null} */ this.TaskId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TaskId = 'TaskId' in params ? params.TaskId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Rule information. * @class */ class RuleInfo extends AbstractModel { constructor(){ super(); /** * Rule creation time. * @type {string || null} */ this.CreateTime = null; /** * Rule update time. * @type {string || null} */ this.UpdateTime = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.UpdateTime = 'UpdateTime' in params ? params.UpdateTime : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * UpdateLiveWatermark response structure. * @class */ class UpdateLiveWatermarkResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveTranscodeTemplate response structure. * @class */ class CreateLiveTranscodeTemplateResponse extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Region information, `DescribeAreaBillBandwidthAndFluxList` output parameter * @class */ class BillAreaInfo extends AbstractModel { constructor(){ super(); /** * Region name * @type {string || null} */ this.Name = null; /** * Detailed country information * @type {Array.<BillCountryInfo> || null} */ this.Countrys = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; if (params.Countrys) { this.Countrys = new Array(); for (let z in params.Countrys) { let obj = new BillCountryInfo(); obj.deserialize(params.Countrys[z]); this.Countrys.push(obj); } } } } /** * Playback information at the stream level. * @class */ class PlayDataInfoByStream extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; } } /** * DescribeVisitTopSumInfoList request structure. * @class */ class DescribeVisitTopSumInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start point in time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End point in time in the format of `yyyy-mm-dd HH:MM:SS` The time span is (0,4 hours]. Data for the last day can be queried. * @type {string || null} */ this.EndTime = null; /** * Bandwidth metric. Valid values: "Domain", "StreamId". * @type {string || null} */ this.TopIndex = null; /** * Playback domain name. If this parameter is left empty, full data will be queried by default. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Page number, Value range: [1,1000], Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Sorting metric. Valid values: "AvgFluxPerSecond", "TotalRequest" (default), "TotalFlux". * @type {string || null} */ this.OrderParam = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.TopIndex = 'TopIndex' in params ? params.TopIndex : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.OrderParam = 'OrderParam' in params ? params.OrderParam : null; } } /** * Stream playback information * @class */ class DayStreamPlayInfo extends AbstractModel { constructor(){ super(); /** * Data point in time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of requests. * @type {number || null} */ this.Request = null; /** * Number of online viewers. * @type {number || null} */ this.Online = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Request = 'Request' in params ? params.Request : null; this.Online = 'Online' in params ? params.Online : null; } } /** * ModifyLivePlayDomain response structure. * @class */ class ModifyLivePlayDomainResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CancelCommonMixStream response structure. * @class */ class CancelCommonMixStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeConcurrentRecordStreamNum response structure. * @class */ class DescribeConcurrentRecordStreamNumResponse extends AbstractModel { constructor(){ super(); /** * Statistics list. * @type {Array.<ConcurrentRecordStreamNum> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new ConcurrentRecordStreamNum(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveCerts response structure. * @class */ class DescribeLiveCertsResponse extends AbstractModel { constructor(){ super(); /** * Certificate information list. * @type {Array.<CertInfo> || null} */ this.CertInfoSet = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.CertInfoSet) { this.CertInfoSet = new Array(); for (let z in params.CertInfoSet) { let obj = new CertInfo(); obj.deserialize(params.CertInfoSet[z]); this.CertInfoSet.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * General stream mix input parameter. * @class */ class CommonMixInputParam extends AbstractModel { constructor(){ super(); /** * Input stream name, which can contain up to 80 bytes of letters, digits, and underscores. The value should be the name of an input stream for stream mix when `LayoutParams.InputType` is set to `0` (audio and video), `4` (pure audio), or `5` (pure video). The value can be a random name for identification, such as `Canvas1` or `Picture1`, when `LayoutParams.InputType` is set to `2` (image) or `3` (canvas). * @type {string || null} */ this.InputStreamName = null; /** * Input stream layout parameter. * @type {CommonMixLayoutParams || null} */ this.LayoutParams = null; /** * Input stream crop parameter. * @type {CommonMixCropParams || null} */ this.CropParams = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.InputStreamName = 'InputStreamName' in params ? params.InputStreamName : null; if (params.LayoutParams) { let obj = new CommonMixLayoutParams(); obj.deserialize(params.LayoutParams) this.LayoutParams = obj; } if (params.CropParams) { let obj = new CommonMixCropParams(); obj.deserialize(params.CropParams) this.CropParams = obj; } } } /** * DescribeProvinceIspPlayInfoList response structure. * @class */ class DescribeProvinceIspPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Playback information list. * @type {Array.<PlayStatInfo> || null} */ this.DataInfoList = null; /** * Statistics type, which is the same as the input parameter. * @type {string || null} */ this.StatType = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new PlayStatInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.StatType = 'StatType' in params ? params.StatType : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveRecordTemplates response structure. * @class */ class DescribeLiveRecordTemplatesResponse extends AbstractModel { constructor(){ super(); /** * Recording template information list. * @type {Array.<RecordTemplateInfo> || null} */ this.Templates = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Templates) { this.Templates = new Array(); for (let z in params.Templates) { let obj = new RecordTemplateInfo(); obj.deserialize(params.Templates[z]); this.Templates.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveCert request structure. * @class */ class DescribeLiveCertRequest extends AbstractModel { constructor(){ super(); /** * Certificate ID obtained through the `DescribeLiveCerts` API. * @type {number || null} */ this.CertId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; } } /** * DescribeLiveCallbackTemplates response structure. * @class */ class DescribeLiveCallbackTemplatesResponse extends AbstractModel { constructor(){ super(); /** * Template information list. * @type {Array.<CallBackTemplateInfo> || null} */ this.Templates = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Templates) { this.Templates = new Array(); for (let z in params.Templates) { let obj = new CallBackTemplateInfo(); obj.deserialize(params.Templates[z]); this.Templates.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLivePlayAuthKey response structure. * @class */ class ModifyLivePlayAuthKeyResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveCallbackTemplate request structure. * @class */ class CreateLiveCallbackTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template name. Maximum length: 255 bytes. Only letters, digits, underscores, and hyphens can be contained. * @type {string || null} */ this.TemplateName = null; /** * Description. Maximum length: 1,024 bytes. Only letters, digits, underscores, and hyphens can be contained. * @type {string || null} */ this.Description = null; /** * Stream starting callback URL, Protocol document: [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.StreamBeginNotifyUrl = null; /** * Interruption callback URL, Protocol document: [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.StreamEndNotifyUrl = null; /** * Recording callback URL, Protocol document: [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.RecordNotifyUrl = null; /** * Screencapturing callback URL, Protocol document: [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.SnapshotNotifyUrl = null; /** * Porn detection callback URL, Protocol document: [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32741?from_cn_redirect=1). * @type {string || null} */ this.PornCensorshipNotifyUrl = null; /** * Callback key. The callback URL is public. For the callback signature, please see the event message notification document. [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.CallbackKey = null; /** * Disused * @type {string || null} */ this.StreamMixNotifyUrl = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.StreamBeginNotifyUrl = 'StreamBeginNotifyUrl' in params ? params.StreamBeginNotifyUrl : null; this.StreamEndNotifyUrl = 'StreamEndNotifyUrl' in params ? params.StreamEndNotifyUrl : null; this.RecordNotifyUrl = 'RecordNotifyUrl' in params ? params.RecordNotifyUrl : null; this.SnapshotNotifyUrl = 'SnapshotNotifyUrl' in params ? params.SnapshotNotifyUrl : null; this.PornCensorshipNotifyUrl = 'PornCensorshipNotifyUrl' in params ? params.PornCensorshipNotifyUrl : null; this.CallbackKey = 'CallbackKey' in params ? params.CallbackKey : null; this.StreamMixNotifyUrl = 'StreamMixNotifyUrl' in params ? params.StreamMixNotifyUrl : null; } } /** * DescribeTopClientIpSumInfoList response structure. * @class */ class DescribeTopClientIpSumInfoListResponse extends AbstractModel { constructor(){ super(); /** * Page number. Value range: [1,1000]. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Sorting metric. Valid values: "TotalRequest", "FailedRequest", "TotalFlux". * @type {string || null} */ this.OrderParam = null; /** * Total number of results. * @type {number || null} */ this.TotalNum = null; /** * Total number of result pages. * @type {number || null} */ this.TotalPage = null; /** * Data content. * @type {Array.<ClientIpPlaySumInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.OrderParam = 'OrderParam' in params ? params.OrderParam : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new ClientIpPlaySumInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DropLiveStream response structure. * @class */ class DropLiveStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveStreamState response structure. * @class */ class DescribeLiveStreamStateResponse extends AbstractModel { constructor(){ super(); /** * Stream status, active: active inactive: Inactive forbid: forbidden. * @type {string || null} */ this.StreamState = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamState = 'StreamState' in params ? params.StreamState : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * StopLiveRecord request structure. * @class */ class StopLiveRecordRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Task ID returned by the `CreateLiveRecord` API. * @type {number || null} */ this.TaskId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TaskId = 'TaskId' in params ? params.TaskId : null; } } /** * DeleteLiveWatermarkRule request structure. * @class */ class DeleteLiveWatermarkRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * Streaming event information. * @class */ class StreamEventInfo extends AbstractModel { constructor(){ super(); /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push start time. In UTC format, such as 2019-01-07T12:00:00Z. * @type {string || null} */ this.StreamStartTime = null; /** * Push end time. In UTC format, such as 2019-01-07T15:00:00Z. * @type {string || null} */ this.StreamEndTime = null; /** * Stop reason. * @type {string || null} */ this.StopReason = null; /** * Push duration in seconds. * @type {number || null} */ this.Duration = null; /** * Host IP. * @type {string || null} */ this.ClientIp = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.StreamStartTime = 'StreamStartTime' in params ? params.StreamStartTime : null; this.StreamEndTime = 'StreamEndTime' in params ? params.StreamEndTime : null; this.StopReason = 'StopReason' in params ? params.StopReason : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } } /** * DeleteRecordTask response structure. * @class */ class DeleteRecordTaskResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveWatermarks request structure. * @class */ class DescribeLiveWatermarksRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * CreateLiveTranscodeRule request structure. * @class */ class CreateLiveTranscodeRuleRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. If you only bind a domain name, leave this parameter empty. * @type {string || null} */ this.AppName = null; /** * Stream name. If only the domain name or path is bound, leave this parameter blank. * @type {string || null} */ this.StreamName = null; /** * Designates an existing template ID. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DescribeLiveWatermarkRules request structure. * @class */ class DescribeLiveWatermarkRulesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * DropLiveStream request structure. * @class */ class DropLiveStreamRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Your acceleration domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the AppName in push and playback addresses and is "live" by default. * @type {string || null} */ this.AppName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; } } /** * CreateCommonMixStream request structure. * @class */ class CreateCommonMixStreamRequest extends AbstractModel { constructor(){ super(); /** * ID of stream mix session (from applying for stream mix to canceling stream mix). * @type {string || null} */ this.MixStreamSessionId = null; /** * Input stream list for stream mix. * @type {Array.<CommonMixInputParam> || null} */ this.InputStreamList = null; /** * Output stream parameter for stream mix. * @type {CommonMixOutputParams || null} */ this.OutputParams = null; /** * Input template ID. If this parameter is set, the output will be generated according to the default template layout, and there is no need to enter the custom position parameters. If this parameter is left empty, 0 will be used by default. For two input sources, 10, 20, 30, 40, and 50 are supported. For three input sources, 310, 390, and 391 are supported. For four input sources, 410 is supported. For five input sources, 510 and 590 are supported. For six input sources, 610 is supported. * @type {number || null} */ this.MixStreamTemplateId = null; /** * Special control parameter for stream mix. If there are no special needs, leave it empty. * @type {CommonMixControlParams || null} */ this.ControlParams = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.MixStreamSessionId = 'MixStreamSessionId' in params ? params.MixStreamSessionId : null; if (params.InputStreamList) { this.InputStreamList = new Array(); for (let z in params.InputStreamList) { let obj = new CommonMixInputParam(); obj.deserialize(params.InputStreamList[z]); this.InputStreamList.push(obj); } } if (params.OutputParams) { let obj = new CommonMixOutputParams(); obj.deserialize(params.OutputParams) this.OutputParams = obj; } this.MixStreamTemplateId = 'MixStreamTemplateId' in params ? params.MixStreamTemplateId : null; if (params.ControlParams) { let obj = new CommonMixControlParams(); obj.deserialize(params.ControlParams) this.ControlParams = obj; } } } /** * Referer allowlist/blocklist configuration of a live streaming domain name * @class */ class RefererAuthConfig extends AbstractModel { constructor(){ super(); /** * Domain name * @type {string || null} */ this.DomainName = null; /** * Whether to enable referer. Valid values: `0` (no), `1` (yes) * @type {number || null} */ this.Enable = null; /** * List type. Valid values: `0` (blocklist), `1` (allowlist) * @type {number || null} */ this.Type = null; /** * Whether to allow empty referer. Valid values: `0` (no), `1` (yes) * @type {number || null} */ this.AllowEmpty = null; /** * Referer list. Separate items in it with semicolons (;). * @type {string || null} */ this.Rules = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.Type = 'Type' in params ? params.Type : null; this.AllowEmpty = 'AllowEmpty' in params ? params.AllowEmpty : null; this.Rules = 'Rules' in params ? params.Rules : null; } } /** * CreateLiveCert response structure. * @class */ class CreateLiveCertResponse extends AbstractModel { constructor(){ super(); /** * Certificate ID * @type {number || null} */ this.CertId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Push information * @class */ class PushDataInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Push client IP. * @type {string || null} */ this.ClientIp = null; /** * IP of the server that receives the stream. * @type {string || null} */ this.ServerIp = null; /** * Pushed video frame rate in Hz. * @type {number || null} */ this.VideoFps = null; /** * Pushed video bitrate in bps. * @type {number || null} */ this.VideoSpeed = null; /** * Pushed audio frame rate in Hz. * @type {number || null} */ this.AudioFps = null; /** * Pushed audio bitrate in bps. * @type {number || null} */ this.AudioSpeed = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push start time. * @type {string || null} */ this.BeginPushTime = null; /** * Audio codec, Example: AAC. * @type {string || null} */ this.Acodec = null; /** * Video codec, Example: H.264. * @type {string || null} */ this.Vcodec = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; /** * Sample rate. * @type {number || null} */ this.AsampleRate = null; /** * Audio bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaAudioSpeed = null; /** * Video bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaVideoSpeed = null; /** * Frame rate in `metadata`. * @type {number || null} */ this.MetaFps = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.ServerIp = 'ServerIp' in params ? params.ServerIp : null; this.VideoFps = 'VideoFps' in params ? params.VideoFps : null; this.VideoSpeed = 'VideoSpeed' in params ? params.VideoSpeed : null; this.AudioFps = 'AudioFps' in params ? params.AudioFps : null; this.AudioSpeed = 'AudioSpeed' in params ? params.AudioSpeed : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.BeginPushTime = 'BeginPushTime' in params ? params.BeginPushTime : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; this.AsampleRate = 'AsampleRate' in params ? params.AsampleRate : null; this.MetaAudioSpeed = 'MetaAudioSpeed' in params ? params.MetaAudioSpeed : null; this.MetaVideoSpeed = 'MetaVideoSpeed' in params ? params.MetaVideoSpeed : null; this.MetaFps = 'MetaFps' in params ? params.MetaFps : null; } } /** * AddDelayLiveStream request structure. * @class */ class AddDelayLiveStreamRequest extends AbstractModel { constructor(){ super(); /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Delay time in seconds, up to 600s. * @type {number || null} */ this.DelayTime = null; /** * Expiration time of the configured delayed playback in UTC format, such as 2018-11-29T19:00:00Z. Notes: 1. The configuration will expire after 7 days by default and can last up to 7 days. 2. The Beijing time is in UTC+8. This value should be in the format as required by ISO 8601. For more information, please see [ISO Date and Time Format](https://intl.cloud.tencent.com/document/product/266/11732?from_cn_redirect=1#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F). * @type {string || null} */ this.ExpireTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DelayTime = 'DelayTime' in params ? params.DelayTime : null; this.ExpireTime = 'ExpireTime' in params ? params.ExpireTime : null; } } /** * DescribeGroupProIspPlayInfoList request structure. * @class */ class DescribeGroupProIspPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End time point in the format of `yyyy-mm-dd HH:MM:SS` The time span is (0,3 hours]. Data for the last month can be queried. * @type {string || null} */ this.EndTime = null; /** * Playback domain name. If this parameter is left empty, full data will be queried. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * District list. If this parameter is left empty, data for all districts will be returned. * @type {Array.<string> || null} */ this.ProvinceNames = null; /** * ISP list. If this parameter is left empty, data of all ISPs will be returned. * @type {Array.<string> || null} */ this.IspNames = null; /** * Within or outside Mainland China. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.ProvinceNames = 'ProvinceNames' in params ? params.ProvinceNames : null; this.IspNames = 'IspNames' in params ? params.IspNames : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; } } /** * DescribeStreamDayPlayInfoList request structure. * @class */ class DescribeStreamDayPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Date in the format of YYYY-mm-dd Data is available at 3am Beijing Time the next day. You are recommended to query the latest data after this time point. Data in the last 3 months can be queried. * @type {string || null} */ this.DayTime = null; /** * Playback domain name. * @type {string || null} */ this.PlayDomain = null; /** * Page number. Value range: [1,1000]. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [100,1000]. Default value: 1,000. * @type {number || null} */ this.PageSize = null; /** * Valid values: Mainland: query data for Mainland China, Oversea: query data for regions outside Mainland China, Default: query data for all regions. * @type {string || null} */ this.MainlandOrOversea = null; /** * Service name. Valid values: LVB, LEB. If this parameter is left empty, all data of LVB and LEB will be queried. * @type {string || null} */ this.ServiceName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DayTime = 'DayTime' in params ? params.DayTime : null; this.PlayDomain = 'PlayDomain' in params ? params.PlayDomain : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.ServiceName = 'ServiceName' in params ? params.ServiceName : null; } } /** * Transcoding details. * @class */ class TranscodeDetailInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Start time (Beijing time) in the format of `yyyy-mm-dd HH:MM`. * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time) in the format of `yyyy-mm-dd HH:MM`. * @type {string || null} */ this.EndTime = null; /** * Transcoding duration in minutes. Note: given the possible interruptions during push, duration here is the sum of actual duration of transcoding instead of the interval between the start time and end time. * @type {number || null} */ this.Duration = null; /** * Codec with modules, Example: liveprocessor_H264: LVB transcoding - H264, liveprocessor_H265: LVB transcoding - H265, topspeed_H264: top speed codec - H264, topspeed_H265: top speed codec - H265. * @type {string || null} */ this.ModuleCodec = null; /** * Bitrate. * @type {number || null} */ this.Bitrate = null; /** * Type. Valid values: Transcode, MixStream, WaterMark. * @type {string || null} */ this.Type = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ModuleCodec = 'ModuleCodec' in params ? params.ModuleCodec : null; this.Bitrate = 'Bitrate' in params ? params.Bitrate : null; this.Type = 'Type' in params ? params.Type : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } } /** * DescribeLiveSnapshotTemplate response structure. * @class */ class DescribeLiveSnapshotTemplateResponse extends AbstractModel { constructor(){ super(); /** * Screencapturing template information. * @type {SnapshotTemplateInfo || null} */ this.Template = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Template) { let obj = new SnapshotTemplateInfo(); obj.deserialize(params.Template) this.Template = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveTranscodeRules response structure. * @class */ class DescribeLiveTranscodeRulesResponse extends AbstractModel { constructor(){ super(); /** * List of transcoding rules. * @type {Array.<RuleInfo> || null} */ this.Rules = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Rules) { this.Rules = new Array(); for (let z in params.Rules) { let obj = new RuleInfo(); obj.deserialize(params.Rules[z]); this.Rules.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveDomainReferer response structure. * @class */ class DescribeLiveDomainRefererResponse extends AbstractModel { constructor(){ super(); /** * Referer allowlist/blocklist configuration of a domain name * @type {RefererAuthConfig || null} */ this.RefererAuthConfig = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.RefererAuthConfig) { let obj = new RefererAuthConfig(); obj.deserialize(params.RefererAuthConfig) this.RefererAuthConfig = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * AddLiveDomain request structure. * @class */ class AddLiveDomainRequest extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; /** * Domain name type. 0: push domain name. 1: playback domain name. * @type {number || null} */ this.DomainType = null; /** * Pull domain name type: 1: Mainland China. 2: global. 3: outside Mainland China. Default value: 1. * @type {number || null} */ this.PlayType = null; /** * Whether it is LCB: 0: LVB, 1: LCB. Default value: 0. * @type {number || null} */ this.IsDelayLive = null; /** * Whether it is LVB on Mini Program. 0: LVB. 1: LVB on Mini Program. Default value: 0. * @type {number || null} */ this.IsMiniProgramLive = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.DomainType = 'DomainType' in params ? params.DomainType : null; this.PlayType = 'PlayType' in params ? params.PlayType : null; this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; this.IsMiniProgramLive = 'IsMiniProgramLive' in params ? params.IsMiniProgramLive : null; } } /** * Stream name list. * @class */ class StreamName extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push start time. In UTC format, such as 2019-01-07T12:00:00Z. * @type {string || null} */ this.StreamStartTime = null; /** * Push end time. In UTC format, such as 2019-01-07T15:00:00Z. * @type {string || null} */ this.StreamEndTime = null; /** * Stop reason. * @type {string || null} */ this.StopReason = null; /** * Push duration in seconds. * @type {number || null} */ this.Duration = null; /** * Host IP. * @type {string || null} */ this.ClientIp = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamStartTime = 'StreamStartTime' in params ? params.StreamStartTime : null; this.StreamEndTime = 'StreamEndTime' in params ? params.StreamEndTime : null; this.StopReason = 'StopReason' in params ? params.StopReason : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } } /** * DescribeLiveCerts request structure. * @class */ class DescribeLiveCertsRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * Downstream playback statistical metrics * @class */ class CdnPlayStatData extends AbstractModel { constructor(){ super(); /** * Time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of new requests. * @type {number || null} */ this.Request = null; /** * Number of concurrent connections. * @type {number || null} */ this.Online = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Request = 'Request' in params ? params.Request : null; this.Online = 'Online' in params ? params.Online : null; } } /** * AddLiveDomain response structure. * @class */ class AddLiveDomainResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeHttpStatusInfoList request structure. * @class */ class DescribeHttpStatusInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start time (Beijing time). Format: yyyy-mm-dd HH:MM:SS. * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time). Format: yyyy-mm-dd HH:MM:SS. Note: data in the last 3 months can be queried and the query period is up to 1 day. * @type {string || null} */ this.EndTime = null; /** * Playback domain name list. * @type {Array.<string> || null} */ this.PlayDomains = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; } } /** * ModifyLiveCallbackTemplate request structure. * @class */ class ModifyLiveCallbackTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID returned by the `DescribeLiveCallbackTemplates` API. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Stream starting callback URL. * @type {string || null} */ this.StreamBeginNotifyUrl = null; /** * Interruption callback URL. * @type {string || null} */ this.StreamEndNotifyUrl = null; /** * Recording callback URL. * @type {string || null} */ this.RecordNotifyUrl = null; /** * Screencapturing callback URL. * @type {string || null} */ this.SnapshotNotifyUrl = null; /** * Porn detection callback URL. * @type {string || null} */ this.PornCensorshipNotifyUrl = null; /** * Callback key. The callback URL is public. For the callback signature, please see the event message notification document. [Event Message Notification](https://intl.cloud.tencent.com/document/product/267/32744?from_cn_redirect=1). * @type {string || null} */ this.CallbackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.StreamBeginNotifyUrl = 'StreamBeginNotifyUrl' in params ? params.StreamBeginNotifyUrl : null; this.StreamEndNotifyUrl = 'StreamEndNotifyUrl' in params ? params.StreamEndNotifyUrl : null; this.RecordNotifyUrl = 'RecordNotifyUrl' in params ? params.RecordNotifyUrl : null; this.SnapshotNotifyUrl = 'SnapshotNotifyUrl' in params ? params.SnapshotNotifyUrl : null; this.PornCensorshipNotifyUrl = 'PornCensorshipNotifyUrl' in params ? params.PornCensorshipNotifyUrl : null; this.CallbackKey = 'CallbackKey' in params ? params.CallbackKey : null; } } /** * DescribeProvinceIspPlayInfoList request structure. * @class */ class DescribeProvinceIspPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start point in time (Beijing time). Example: 2019-02-21 10:00:00. * @type {string || null} */ this.StartTime = null; /** * End point in time (Beijing time). Example: 2019-02-21 12:00:00. Note: `EndTime` and `StartTime` only support querying data for the last day. * @type {string || null} */ this.EndTime = null; /** * Supported granularities: 1: 1-minute granularity (the query interval should be within 1 day) * @type {number || null} */ this.Granularity = null; /** * Statistical metric type: "Bandwidth": bandwidth "FluxPerSecond": average traffic "Flux": traffic "Request": number of requests "Online": number of concurrent connections * @type {string || null} */ this.StatType = null; /** * Playback domain name list. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * List of the districts to be queried, such as Beijing. * @type {Array.<string> || null} */ this.ProvinceNames = null; /** * List of the ISPs to be queried, such as China Mobile. If this parameter is left empty, the data of all ISPs will be queried. * @type {Array.<string> || null} */ this.IspNames = null; /** * Region. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China), China (data for China, including Hong Kong, Macao, and Taiwan), Foreign (data for regions outside China, excluding Hong Kong, Macao, and Taiwan), Global (default). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; /** * IP type: "Ipv6": IPv6 data Data of all IPs will be returned if this parameter is left empty. * @type {string || null} */ this.IpType = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Granularity = 'Granularity' in params ? params.Granularity : null; this.StatType = 'StatType' in params ? params.StatType : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.ProvinceNames = 'ProvinceNames' in params ? params.ProvinceNames : null; this.IspNames = 'IspNames' in params ? params.IspNames : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.IpType = 'IpType' in params ? params.IpType : null; } } /** * DescribeLivePlayAuthKey request structure. * @class */ class DescribeLivePlayAuthKeyRequest extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * DescribeLiveForbidStreamList response structure. * @class */ class DescribeLiveForbidStreamListResponse extends AbstractModel { constructor(){ super(); /** * Total number of eligible ones. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries displayed per page. * @type {number || null} */ this.PageSize = null; /** * List of forbidden streams. * @type {Array.<ForbidStreamInfo> || null} */ this.ForbidStreamList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; if (params.ForbidStreamList) { this.ForbidStreamList = new Array(); for (let z in params.ForbidStreamList) { let obj = new ForbidStreamInfo(); obj.deserialize(params.ForbidStreamList[z]); this.ForbidStreamList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeStreamPushInfoList request structure. * @class */ class DescribeStreamPushInfoListRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Start time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End time point in the format of `yyyy-mm-dd HH:MM:SS`. The maximum time span is 6 hours. Data for the last 6 days can be queried. * @type {string || null} */ this.EndTime = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.AppName = 'AppName' in params ? params.AppName : null; } } /** * Multi-domain name information list * @class */ class DomainInfoList extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.Domain = null; /** * Details. * @type {Array.<DomainDetailInfo> || null} */ this.DetailInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Domain = 'Domain' in params ? params.Domain : null; if (params.DetailInfoList) { this.DetailInfoList = new Array(); for (let z in params.DetailInfoList) { let obj = new DomainDetailInfo(); obj.deserialize(params.DetailInfoList[z]); this.DetailInfoList.push(obj); } } } } /** * DescribeLiveWatermark response structure. * @class */ class DescribeLiveWatermarkResponse extends AbstractModel { constructor(){ super(); /** * Watermark information. * @type {WatermarkInfo || null} */ this.Watermark = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Watermark) { let obj = new WatermarkInfo(); obj.deserialize(params.Watermark) this.Watermark = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ResumeLiveStream response structure. * @class */ class ResumeLiveStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLiveRecordTemplate request structure. * @class */ class ModifyLiveRecordTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID obtained through the `DescribeRecordTemplates` API. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Message description * @type {string || null} */ this.Description = null; /** * FLV recording parameter, which is set when FLV recording is enabled. * @type {RecordParam || null} */ this.FlvParam = null; /** * HLS recording parameter, which is set when HLS recording is enabled. * @type {RecordParam || null} */ this.HlsParam = null; /** * MP4 recording parameter, which is set when MP4 recording is enabled. * @type {RecordParam || null} */ this.Mp4Param = null; /** * AAC recording parameter, which is set when AAC recording is enabled. * @type {RecordParam || null} */ this.AacParam = null; /** * Custom HLS recording parameter. * @type {HlsSpecialParam || null} */ this.HlsSpecialParam = null; /** * MP3 recording parameter, which is set when MP3 recording is enabled. * @type {RecordParam || null} */ this.Mp3Param = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; if (params.FlvParam) { let obj = new RecordParam(); obj.deserialize(params.FlvParam) this.FlvParam = obj; } if (params.HlsParam) { let obj = new RecordParam(); obj.deserialize(params.HlsParam) this.HlsParam = obj; } if (params.Mp4Param) { let obj = new RecordParam(); obj.deserialize(params.Mp4Param) this.Mp4Param = obj; } if (params.AacParam) { let obj = new RecordParam(); obj.deserialize(params.AacParam) this.AacParam = obj; } if (params.HlsSpecialParam) { let obj = new HlsSpecialParam(); obj.deserialize(params.HlsSpecialParam) this.HlsSpecialParam = obj; } if (params.Mp3Param) { let obj = new RecordParam(); obj.deserialize(params.Mp3Param) this.Mp3Param = obj; } } } /** * DescribeStreamPushInfoList response structure. * @class */ class DescribeStreamPushInfoListResponse extends AbstractModel { constructor(){ super(); /** * Returned data list. * @type {Array.<PushQualityData> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new PushQualityData(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveStreamPushInfoList request structure. * @class */ class DescribeLiveStreamPushInfoListRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Number of pages, Value range: [1,10000], Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page, Value range: [1,1000], Default value: 200. * @type {number || null} */ this.PageSize = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.AppName = 'AppName' in params ? params.AppName : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; } } /** * DescribeLiveWatermarks response structure. * @class */ class DescribeLiveWatermarksResponse extends AbstractModel { constructor(){ super(); /** * Total number of watermarks. * @type {number || null} */ this.TotalNum = null; /** * Watermark information list. * @type {Array.<WatermarkInfo> || null} */ this.WatermarkList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; if (params.WatermarkList) { this.WatermarkList = new Array(); for (let z in params.WatermarkList) { let obj = new WatermarkInfo(); obj.deserialize(params.WatermarkList[z]); this.WatermarkList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Watermark information. * @class */ class WatermarkInfo extends AbstractModel { constructor(){ super(); /** * Watermark ID. * @type {number || null} */ this.WatermarkId = null; /** * Watermark image URL. * @type {string || null} */ this.PictureUrl = null; /** * Display position: X-axis offset. * @type {number || null} */ this.XPosition = null; /** * Display position: Y-axis offset. * @type {number || null} */ this.YPosition = null; /** * Watermark name. * @type {string || null} */ this.WatermarkName = null; /** * Current status. 0: not used. 1: in use. * @type {number || null} */ this.Status = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Watermark width. * @type {number || null} */ this.Width = null; /** * Watermark height. * @type {number || null} */ this.Height = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; this.PictureUrl = 'PictureUrl' in params ? params.PictureUrl : null; this.XPosition = 'XPosition' in params ? params.XPosition : null; this.YPosition = 'YPosition' in params ? params.YPosition : null; this.WatermarkName = 'WatermarkName' in params ? params.WatermarkName : null; this.Status = 'Status' in params ? params.Status : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; } } /** * DescribeLiveForbidStreamList request structure. * @class */ class DescribeLiveForbidStreamListRequest extends AbstractModel { constructor(){ super(); /** * Page number to get. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Maximum value: 100. Value: any integer between 1 and 100. Default value: 10. * @type {number || null} */ this.PageSize = null; /** * The stream name to search for * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DescribeLiveDomainPlayInfoList request structure. * @class */ class DescribeLiveDomainPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name list. * @type {Array.<string> || null} */ this.PlayDomains = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; } } /** * BindLiveDomainCert request structure. * @class */ class BindLiveDomainCertRequest extends AbstractModel { constructor(){ super(); /** * Certificate ID, which can be obtained through the `CreateLiveCert` API. * @type {number || null} */ this.CertId = null; /** * Playback domain name. * @type {string || null} */ this.DomainName = null; /** * HTTPS status. 0: disabled, 1: enabled. * @type {number || null} */ this.Status = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Status = 'Status' in params ? params.Status : null; } } /** * DescribeTopClientIpSumInfoList request structure. * @class */ class DescribeTopClientIpSumInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start point in time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End point in time in the format of `yyyy-mm-dd HH:MM:SS` The time span is [0,4 hours]. Data for the last day can be queried. * @type {string || null} */ this.EndTime = null; /** * Playback domain name. If this parameter is left empty, full data will be queried by default. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Page number. Value range: [1,1000]. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Sorting metric. Valid values: TotalRequest (default value), FailedRequest, TotalFlux. * @type {string || null} */ this.OrderParam = null; /** * Region. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China), China (data for China, including Hong Kong, Macao, and Taiwan), Foreign (data for regions outside China, excluding Hong Kong, Macao, and Taiwan), Global (default). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; /** * Language used in the output field. Valid values: Chinese (default), English. Currently, country/region, district, and ISP parameters support multiple languages. * @type {string || null} */ this.OutLanguage = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.OrderParam = 'OrderParam' in params ? params.OrderParam : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.OutLanguage = 'OutLanguage' in params ? params.OutLanguage : null; } } /** * CreateLiveCallbackRule request structure. * @class */ class CreateLiveCallbackRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DeleteLiveWatermarkRule response structure. * @class */ class DeleteLiveWatermarkRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Push time. * @class */ class PublishTime extends AbstractModel { constructor(){ super(); /** * Push time. In UTC format, such as 2018-06-29T19:00:00Z. * @type {string || null} */ this.PublishTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PublishTime = 'PublishTime' in params ? params.PublishTime : null; } } /** * ModifyLiveCert response structure. * @class */ class ModifyLiveCertResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Monitored playback data * @class */ class MonitorStreamPlayInfo extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.PlayDomain = null; /** * Stream ID. * @type {string || null} */ this.StreamName = null; /** * Playback bitrate. 0 indicates the original bitrate. * @type {number || null} */ this.Rate = null; /** * Playback protocol. Valid values: Unknown, Flv, Hls, Rtmp, Huyap2p. * @type {string || null} */ this.Protocol = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Number of online viewers. A data point is sampled per minute, and the number of TCP connections across the sample points is calculated. * @type {number || null} */ this.Online = null; /** * Number of requests. * @type {number || null} */ this.Request = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PlayDomain = 'PlayDomain' in params ? params.PlayDomain : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.Rate = 'Rate' in params ? params.Rate : null; this.Protocol = 'Protocol' in params ? params.Protocol : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Online = 'Online' in params ? params.Online : null; this.Request = 'Request' in params ? params.Request : null; } } /** * DescribeLiveTranscodeDetailInfo request structure. * @class */ class DescribeLiveTranscodeDetailInfoRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Query date (UTC+8) Format: yyyymmdd Note: you can query the statistics for a day in the past month, with yesterday as the latest date allowed. * @type {string || null} */ this.DayTime = null; /** * Number of pages. Default value: 1. Up to 100 pages. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Default value: 20, Value range: [10,1000]. * @type {number || null} */ this.PageSize = null; /** * Start day time (Beijing time), In the format of `yyyymmdd`. Note: details for the last month can be queried. * @type {string || null} */ this.StartDayTime = null; /** * End date (UTC+8) Format: yyyymmdd Note: you can query the statistics for a period in the past month, with yesterday as the latest date allowed. You must specify either `DayTime`, or `StartDayTime` and `EndDayTime`. If you specify all three parameters, only `DayTime` will be applied. * @type {string || null} */ this.EndDayTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DayTime = 'DayTime' in params ? params.DayTime : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.StartDayTime = 'StartDayTime' in params ? params.StartDayTime : null; this.EndDayTime = 'EndDayTime' in params ? params.EndDayTime : null; } } /** * ModifyLiveDomainReferer response structure. * @class */ class ModifyLiveDomainRefererResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveWatermark request structure. * @class */ class DeleteLiveWatermarkRequest extends AbstractModel { constructor(){ super(); /** * Watermark ID. Watermark ID obtained in the returned value of the [AddLiveWatermark](https://intl.cloud.tencent.com/document/product/267/30154?from_cn_redirect=1) API call. Watermark ID returned by the `DescribeLiveWatermarks` API. * @type {number || null} */ this.WatermarkId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; } } /** * DescribeLiveDomains request structure. * @class */ class DescribeLiveDomainsRequest extends AbstractModel { constructor(){ super(); /** * Filter by domain name status. 0: disabled, 1: enabled. * @type {number || null} */ this.DomainStatus = null; /** * Filter by domain name type. 0: push. 1: playback * @type {number || null} */ this.DomainType = null; /** * Number of entries per page. Value range: 10-100. Default value: 10. * @type {number || null} */ this.PageSize = null; /** * Page number to get. Value range: 1-100000. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * 0: LVB, 1: LCB. Default value: 0. * @type {number || null} */ this.IsDelayLive = null; /** * Domain name prefix. * @type {string || null} */ this.DomainPrefix = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainStatus = 'DomainStatus' in params ? params.DomainStatus : null; this.DomainType = 'DomainType' in params ? params.DomainType : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; this.DomainPrefix = 'DomainPrefix' in params ? params.DomainPrefix : null; } } /** * Queries playback information by district/ISP. * @class */ class ProIspPlaySumInfo extends AbstractModel { constructor(){ super(); /** * District/ISP/country/region. * @type {string || null} */ this.Name = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Average download traffic in MB/s. * @type {number || null} */ this.AvgFluxPerSecond = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.AvgFluxPerSecond = 'AvgFluxPerSecond' in params ? params.AvgFluxPerSecond : null; } } /** * Screencapturing template information. * @class */ class SnapshotTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Screencapturing interval. Value range: 5-300s. * @type {number || null} */ this.SnapshotInterval = null; /** * Screenshot width. Value range: 0-3000. 0: original width and fit to the original ratio. * @type {number || null} */ this.Width = null; /** * Screenshot height. Value range: 0-2000. 0: original height and fit to the original ratio. * @type {number || null} */ this.Height = null; /** * Whether to enable porn detection. 0: no, 1: yes. * @type {number || null} */ this.PornFlag = null; /** * COS application ID. * @type {number || null} */ this.CosAppId = null; /** * COS bucket name. * @type {string || null} */ this.CosBucket = null; /** * COS region. * @type {string || null} */ this.CosRegion = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * COS bucket folder prefix. Note: this field may return null, indicating that no valid values can be obtained. * @type {string || null} */ this.CosPrefix = null; /** * COS filename. Note: this field may return null, indicating that no valid values can be obtained. * @type {string || null} */ this.CosFileName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.SnapshotInterval = 'SnapshotInterval' in params ? params.SnapshotInterval : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.PornFlag = 'PornFlag' in params ? params.PornFlag : null; this.CosAppId = 'CosAppId' in params ? params.CosAppId : null; this.CosBucket = 'CosBucket' in params ? params.CosBucket : null; this.CosRegion = 'CosRegion' in params ? params.CosRegion : null; this.Description = 'Description' in params ? params.Description : null; this.CosPrefix = 'CosPrefix' in params ? params.CosPrefix : null; this.CosFileName = 'CosFileName' in params ? params.CosFileName : null; } } /** * DeleteLiveSnapshotRule response structure. * @class */ class DeleteLiveSnapshotRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveRecord request structure. * @class */ class CreateLiveRecordRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Push domain name. This parameter must be set for multi-domain name push. * @type {string || null} */ this.DomainName = null; /** * Recording start time, which is China standard time and should be URL-encoded (RFC3986). For example, the encoding of 2017-01-01 10:10:01 is 2017-01-01+10%3a10%3a01. In scheduled recording mode, this field must be set; in real-time video recording mode, this field is ignored. * @type {string || null} */ this.StartTime = null; /** * Recording end time, which is China standard time and should be URL-encoded (RFC3986). For example, the encoding of 2017-01-01 10:30:01 is 2017-01-01+10%3a30%3a01. In scheduled recording mode, this field must be set; in real-time video recording mode, this field is optional. If the recording is set to real-time video recording mode through the `Highlight` parameter, the set end time should not be more than 30 minutes after the current time. If the set end time is more than 30 minutes after the current time, earlier than the current time, or left empty, the actual end time will be 30 minutes after the current time. * @type {string || null} */ this.EndTime = null; /** * Recording type. "video": Audio-video recording **(default)**. "audio": audio recording. In both scheduled and real-time video recording modes, this parameter is valid and is not case sensitive. * @type {string || null} */ this.RecordType = null; /** * Recording file format. Valid values: "flv" **(default)**, "hls", "mp4", "aac", "mp3". In both scheduled and real-time video recording modes, this parameter is valid and is not case sensitive. * @type {string || null} */ this.FileFormat = null; /** * Mark for enabling real-time video recording mode. 0: Real-time video recording mode is not enabled, i.e., the scheduled recording mode is used **(default)**. See [Sample 1](#.E7.A4.BA.E4.BE.8B1-.E5.88.9B.E5.BB.BA.E5.AE.9A.E6.97.B6.E5.BD.95.E5.88.B6.E4.BB.BB.E5.8A.A1). 1: Real-time video recording mode is enabled. See [Sample 2](#.E7.A4.BA.E4.BE.8B2-.E5.88.9B.E5.BB.BA.E5.AE.9E.E6.97.B6.E5.BD.95.E5.88.B6.E4.BB.BB.E5.8A.A1). * @type {number || null} */ this.Highlight = null; /** * Flag for enabling A+B=C mixed stream recording. 0: A+B=C mixed stream recording is not enabled **(default)**. 1: A+B=C mixed stream recording is enabled. In both scheduled and real-time video recording modes, this parameter is valid. * @type {number || null} */ this.MixStream = null; /** * Recording stream parameter. The following parameters are supported currently: record_interval: recording interval in seconds. Value range: 1800-7200. storage_time: recording file storage duration in seconds. Example: record_interval=3600&storage_time=2592000. Note: the parameter needs to be URL-encoded. In both scheduled and real-time video recording modes, this parameter is valid. * @type {string || null} */ this.StreamParam = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.RecordType = 'RecordType' in params ? params.RecordType : null; this.FileFormat = 'FileFormat' in params ? params.FileFormat : null; this.Highlight = 'Highlight' in params ? params.Highlight : null; this.MixStream = 'MixStream' in params ? params.MixStream : null; this.StreamParam = 'StreamParam' in params ? params.StreamParam : null; } } /** * ForbidLiveStream response structure. * @class */ class ForbidLiveStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Bandwidth information * @class */ class BandwidthInfo extends AbstractModel { constructor(){ super(); /** * Format of return value: yyyy-mm-dd HH:MM:SS The time accuracy matches with the query granularity. * @type {string || null} */ this.Time = null; /** * Bandwidth. * @type {number || null} */ this.Bandwidth = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; } } /** * CancelCommonMixStream request structure. * @class */ class CancelCommonMixStreamRequest extends AbstractModel { constructor(){ super(); /** * ID of stream mix session (from applying for stream mix to canceling stream mix). This value is the same as the `MixStreamSessionId` in `CreateCommonMixStream`. * @type {string || null} */ this.MixStreamSessionId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.MixStreamSessionId = 'MixStreamSessionId' in params ? params.MixStreamSessionId : null; } } /** * UpdateLiveWatermark request structure. * @class */ class UpdateLiveWatermarkRequest extends AbstractModel { constructor(){ super(); /** * Watermark ID. Get the watermark ID in the returned value of the [AddLiveWatermark](https://intl.cloud.tencent.com/document/product/267/30154?from_cn_redirect=1) API call. * @type {number || null} */ this.WatermarkId = null; /** * Watermark image URL. Unallowed characters in the URL: ;(){}$>`#"\'| * @type {string || null} */ this.PictureUrl = null; /** * Display position: X-axis offset in %. Default value: 0. * @type {number || null} */ this.XPosition = null; /** * Display position: Y-axis offset in %. Default value: 0. * @type {number || null} */ this.YPosition = null; /** * Watermark name. Up to 16 bytes. * @type {string || null} */ this.WatermarkName = null; /** * Watermark width or its percentage of the live streaming video width. It is recommended to just specify either height or width as the other will be scaled proportionally to avoid distortions. The original width is used by default. * @type {number || null} */ this.Width = null; /** * Watermark height or its percentage of the live streaming video width. It is recommended to just specify either height or width as the other will be scaled proportionally to avoid distortions. The original height is used by default. * @type {number || null} */ this.Height = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; this.PictureUrl = 'PictureUrl' in params ? params.PictureUrl : null; this.XPosition = 'XPosition' in params ? params.XPosition : null; this.YPosition = 'YPosition' in params ? params.YPosition : null; this.WatermarkName = 'WatermarkName' in params ? params.WatermarkName : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; } } /** * Certificate information. * @class */ class CertInfo extends AbstractModel { constructor(){ super(); /** * Certificate ID. * @type {number || null} */ this.CertId = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Creation time in UTC format. * @type {string || null} */ this.CreateTime = null; /** * Certificate content. * @type {string || null} */ this.HttpsCrt = null; /** * Certificate type. 0: user-added certificate 1: Tencent Cloud-hosted certificate * @type {number || null} */ this.CertType = null; /** * Certificate expiration time in UTC format. * @type {string || null} */ this.CertExpireTime = null; /** * List of domain names that use this certificate. * @type {Array.<string> || null} */ this.DomainList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.CertName = 'CertName' in params ? params.CertName : null; this.Description = 'Description' in params ? params.Description : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.CertType = 'CertType' in params ? params.CertType : null; this.CertExpireTime = 'CertExpireTime' in params ? params.CertExpireTime : null; this.DomainList = 'DomainList' in params ? params.DomainList : null; } } /** * ModifyLivePushAuthKey response structure. * @class */ class ModifyLivePushAuthKeyResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveDelayInfoList response structure. * @class */ class DescribeLiveDelayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Delayed playback information list. * @type {Array.<DelayInfo> || null} */ this.DelayInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DelayInfoList) { this.DelayInfoList = new Array(); for (let z in params.DelayInfoList) { let obj = new DelayInfo(); obj.deserialize(params.DelayInfoList[z]); this.DelayInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveTranscodeTemplate request structure. * @class */ class DeleteLiveTranscodeTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. 1. Get the template ID in the returned value of the [CreateLiveTranscodeTemplate](https://intl.cloud.tencent.com/document/product/267/32646?from_cn_redirect=1) API call. 2. You can query the list of created templates through the [DescribeLiveTranscodeTemplates](https://intl.cloud.tencent.com/document/product/267/32641?from_cn_redirect=1) API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DescribeLiveCallbackRules request structure. * @class */ class DescribeLiveCallbackRulesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * Aggregated playback information of client IP. * @class */ class ClientIpPlaySumInfo extends AbstractModel { constructor(){ super(); /** * Client IP in dotted-decimal notation. * @type {string || null} */ this.ClientIp = null; /** * District where the client is located. * @type {string || null} */ this.Province = null; /** * Total traffic. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Total number of failed requests. * @type {number || null} */ this.TotalFailedRequest = null; /** * Country/region where the client is located. * @type {string || null} */ this.CountryArea = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Province = 'Province' in params ? params.Province : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.TotalFailedRequest = 'TotalFailedRequest' in params ? params.TotalFailedRequest : null; this.CountryArea = 'CountryArea' in params ? params.CountryArea : null; } } /** * DescribeLiveTranscodeTemplate response structure. * @class */ class DescribeLiveTranscodeTemplateResponse extends AbstractModel { constructor(){ super(); /** * Template information. * @type {TemplateInfo || null} */ this.Template = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Template) { let obj = new TemplateInfo(); obj.deserialize(params.Template) this.Template = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveSnapshotTemplate response structure. * @class */ class CreateLiveSnapshotTemplateResponse extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeConcurrentRecordStreamNum request structure. * @class */ class DescribeConcurrentRecordStreamNumRequest extends AbstractModel { constructor(){ super(); /** * Live streaming type. SlowLive: LCB. NormalLive: LVB. * @type {string || null} */ this.LiveType = null; /** * Start time in the format of `yyyy-mm-dd HH:MM:SS`. Data for the last 180 days can be queried. * @type {string || null} */ this.StartTime = null; /** * End time in the format of `yyyy-mm-dd HH:MM:SS`. The maximum time span supported is 31 days. * @type {string || null} */ this.EndTime = null; /** * Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; /** * Playback domain name list. If this parameter is left empty, full data will be queried. * @type {Array.<string> || null} */ this.PushDomains = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.LiveType = 'LiveType' in params ? params.LiveType : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.PushDomains = 'PushDomains' in params ? params.PushDomains : null; } } /** * DescribePlayErrorCodeSumInfoList request structure. * @class */ class DescribePlayErrorCodeSumInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start point in time (Beijing time). In the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.StartTime = null; /** * End point in time (Beijing time). In the format of `yyyy-mm-dd HH:MM:SS`. Note: `EndTime` and `StartTime` only support querying data for the last day. * @type {string || null} */ this.EndTime = null; /** * Playback domain name list. If this parameter is left empty, full data will be queried. * @type {Array.<string> || null} */ this.PlayDomains = null; /** * Number of pages. Value range: [1,1000]. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Region. Valid values: Mainland (data for Mainland China), Oversea (data for regions outside Mainland China), China (data for China, including Hong Kong, Macao, and Taiwan), Foreign (data for regions outside China, excluding Hong Kong, Macao, and Taiwan), Global (default). If this parameter is left empty, data for all regions will be queried. * @type {string || null} */ this.MainlandOrOversea = null; /** * Grouping parameter. Valid values: CountryProIsp (default value), Country (country/region). Grouping is made by country/region + district + ISP by default. Currently, districts and ISPs outside Mainland China cannot be recognized. * @type {string || null} */ this.GroupType = null; /** * Language used in the output field. Valid values: Chinese (default), English. Currently, country/region, district, and ISP parameters support multiple languages. * @type {string || null} */ this.OutLanguage = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.GroupType = 'GroupType' in params ? params.GroupType : null; this.OutLanguage = 'OutLanguage' in params ? params.OutLanguage : null; } } /** * ModifyLiveCert request structure. * @class */ class ModifyLiveCertRequest extends AbstractModel { constructor(){ super(); /** * Certificate ID. * @type {string || null} */ this.CertId = null; /** * Certificate type. 0: user-added certificate, 1: Tencent Cloud-hosted certificate. * @type {number || null} */ this.CertType = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Certificate content, i.e., public key. * @type {string || null} */ this.HttpsCrt = null; /** * Private key. * @type {string || null} */ this.HttpsKey = null; /** * Description. * @type {string || null} */ this.Description = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.CertType = 'CertType' in params ? params.CertType : null; this.CertName = 'CertName' in params ? params.CertName : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.HttpsKey = 'HttpsKey' in params ? params.HttpsKey : null; this.Description = 'Description' in params ? params.Description : null; } } /** * General stream mix control parameter * @class */ class CommonMixControlParams extends AbstractModel { constructor(){ super(); /** * Value range: [0,1]. If 1 is entered, when the layer resolution in the parameter is different from the actual video resolution, the video will be automatically cropped according to the resolution set by the layer. * @type {number || null} */ this.UseMixCropCenter = null; /** * Value range: [0,1]. If this parameter is set to 1, when both `InputStreamList` and `OutputParams.OutputStreamType` are set to 1, you can copy a stream instead of canceling it. * @type {number || null} */ this.AllowCopy = null; /** * Valid values: 0, 1 If you set this parameter to 1, SEI (Supplemental Enhanced Information) of the input streams will be passed through. * @type {number || null} */ this.PassInputSei = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.UseMixCropCenter = 'UseMixCropCenter' in params ? params.UseMixCropCenter : null; this.AllowCopy = 'AllowCopy' in params ? params.AllowCopy : null; this.PassInputSei = 'PassInputSei' in params ? params.PassInputSei : null; } } /** * DescribeAreaBillBandwidthAndFluxList response structure. * @class */ class DescribeAreaBillBandwidthAndFluxListResponse extends AbstractModel { constructor(){ super(); /** * Detailed data information. * @type {Array.<BillAreaInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new BillAreaInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ForbidLiveDomain request structure. * @class */ class ForbidLiveDomainRequest extends AbstractModel { constructor(){ super(); /** * LVB domain name to be disabled. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * DescribeLiveRecordRules request structure. * @class */ class DescribeLiveRecordRulesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * DescribePlayErrorCodeDetailInfoList response structure. * @class */ class DescribePlayErrorCodeDetailInfoListResponse extends AbstractModel { constructor(){ super(); /** * Statistics list. * @type {Array.<HttpCodeInfo> || null} */ this.HttpCodeList = null; /** * Statistics type. * @type {string || null} */ this.StatType = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.HttpCodeList) { this.HttpCodeList = new Array(); for (let z in params.HttpCodeList) { let obj = new HttpCodeInfo(); obj.deserialize(params.HttpCodeList[z]); this.HttpCodeList.push(obj); } } this.StatType = 'StatType' in params ? params.StatType : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveRecordTemplate response structure. * @class */ class CreateLiveRecordTemplateResponse extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Recording template parameter. * @class */ class RecordParam extends AbstractModel { constructor(){ super(); /** * Max recording time per file Default value: `1800` (seconds) Value range: 30-7200 This parameter is invalid for HLS. Only one HLS file will be generated from push start to push end. * @type {number || null} */ this.RecordInterval = null; /** * Storage duration of the recording file Value range: 0-129600000 seconds (0-1500 days) `0`: permanent * @type {number || null} */ this.StorageTime = null; /** * Whether to enable recording in the current format. Default value: 0. 0: no, 1: yes. * @type {number || null} */ this.Enable = null; /** * VOD subapplication ID. * @type {number || null} */ this.VodSubAppId = null; /** * Recording filename. Supported special placeholders include: {StreamID}: stream ID {StartYear}: start time - year {StartMonth}: start time - month {StartDay}: start time - day {StartHour}: start time - hour {StartMinute}: start time - minute {StartSecond}: start time - second {StartMillisecond}: start time - millisecond {EndYear}: end time - year {EndMonth}: end time - month {EndDay}: end time - day {EndHour}: end time - hour {EndMinute}: end time - minute {EndSecond}: end time - second {EndMillisecond}: end time - millisecond If this parameter is not set, the recording filename will be `{StreamID}_{StartYear}-{StartMonth}-{StartDay}-{StartHour}-{StartMinute}-{StartSecond}_{EndYear}-{EndMonth}-{EndDay}-{EndHour}-{EndMinute}-{EndSecond}` by default * @type {string || null} */ this.VodFileName = null; /** * Task flow Note: this field may return `null`, indicating that no valid value is obtained. * @type {string || null} */ this.Procedure = null; /** * Video storage class. Valid values: `normal`: STANDARD `cold`: STANDARD_IA Note: this field may return `null`, indicating that no valid value is obtained. * @type {string || null} */ this.StorageMode = null; /** * VOD subapplication category Note: this field may return `null`, indicating that no valid value is obtained. * @type {number || null} */ this.ClassId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RecordInterval = 'RecordInterval' in params ? params.RecordInterval : null; this.StorageTime = 'StorageTime' in params ? params.StorageTime : null; this.Enable = 'Enable' in params ? params.Enable : null; this.VodSubAppId = 'VodSubAppId' in params ? params.VodSubAppId : null; this.VodFileName = 'VodFileName' in params ? params.VodFileName : null; this.Procedure = 'Procedure' in params ? params.Procedure : null; this.StorageMode = 'StorageMode' in params ? params.StorageMode : null; this.ClassId = 'ClassId' in params ? params.ClassId : null; } } /** * Statistics of each domain name. * @class */ class DomainDetailInfo extends AbstractModel { constructor(){ super(); /** * In or outside Mainland China: Mainland: data in Mainland China. Oversea: data outside Mainland China. * @type {string || null} */ this.MainlandOrOversea = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of viewers. * @type {number || null} */ this.Online = null; /** * Number of requests. * @type {number || null} */ this.Request = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Online = 'Online' in params ? params.Online : null; this.Request = 'Request' in params ? params.Request : null; } } /** * Playback error code information * @class */ class HttpStatusInfo extends AbstractModel { constructor(){ super(); /** * Playback HTTP status code. * @type {string || null} */ this.HttpStatus = null; /** * Quantity. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.HttpStatus = 'HttpStatus' in params ? params.HttpStatus : null; this.Num = 'Num' in params ? params.Num : null; } } /** * DeleteLiveRecord request structure. * @class */ class DeleteLiveRecordRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Task ID returned by the `CreateLiveRecord` API. * @type {number || null} */ this.TaskId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TaskId = 'TaskId' in params ? params.TaskId : null; } } /** * DescribeLiveSnapshotTemplates response structure. * @class */ class DescribeLiveSnapshotTemplatesResponse extends AbstractModel { constructor(){ super(); /** * Screencapturing template list. * @type {Array.<SnapshotTemplateInfo> || null} */ this.Templates = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Templates) { this.Templates = new Array(); for (let z in params.Templates) { let obj = new SnapshotTemplateInfo(); obj.deserialize(params.Templates[z]); this.Templates.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * StopRecordTask request structure. * @class */ class StopRecordTaskRequest extends AbstractModel { constructor(){ super(); /** * Recording task ID. * @type {string || null} */ this.TaskId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TaskId = 'TaskId' in params ? params.TaskId : null; } } /** * DescribeLiveDomainReferer request structure. * @class */ class DescribeLiveDomainRefererRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * Playback error code information * @class */ class HttpStatusData extends AbstractModel { constructor(){ super(); /** * Data point in time, In the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Playback status code details. * @type {Array.<HttpStatusInfo> || null} */ this.HttpStatusInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; if (params.HttpStatusInfoList) { this.HttpStatusInfoList = new Array(); for (let z in params.HttpStatusInfoList) { let obj = new HttpStatusInfo(); obj.deserialize(params.HttpStatusInfoList[z]); this.HttpStatusInfoList.push(obj); } } } } /** * HTTP return code and statistics * @class */ class HttpCodeInfo extends AbstractModel { constructor(){ super(); /** * HTTP return code. Example: "2xx", "3xx", "4xx", "5xx". * @type {string || null} */ this.HttpCode = null; /** * Statistics. 0 will be added for points in time when there is no data. * @type {Array.<HttpCodeValue> || null} */ this.ValueList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.HttpCode = 'HttpCode' in params ? params.HttpCode : null; if (params.ValueList) { this.ValueList = new Array(); for (let z in params.ValueList) { let obj = new HttpCodeValue(); obj.deserialize(params.ValueList[z]); this.ValueList.push(obj); } } } } /** * DescribeStreamPlayInfoList request structure. * @class */ class DescribeStreamPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Start time (Beijing time) in the format of yyyy-mm-dd HH:MM:SS * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time) in the format of yyyy-mm-dd HH:MM:SS. The difference between the start time and end time cannot be greater than 24 hours. Data in the last 30 days can be queried. * @type {string || null} */ this.EndTime = null; /** * Playback domain name, If this parameter is left empty, data of live streams of all playback domain names will be queried. * @type {string || null} */ this.PlayDomain = null; /** * Stream name (exact match). If this parameter is left empty, full playback data will be queried. * @type {string || null} */ this.StreamName = null; /** * Push address. Its value is the same as the `AppName` in playback address. It supports exact match, and takes effect only when `StreamName` is passed at the same time. If it is left empty, the full playback data will be queried. Note: to query by `AppName`, you need to submit a ticket first. After your application succeeds, it will take about 5 business days (subject to the time in the reply) for the configuration to take effect. * @type {string || null} */ this.AppName = null; /** * Service name. Valid values: LVB, LEB. If this parameter is left empty, all data of LVB and LEB will be queried. * @type {string || null} */ this.ServiceName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomain = 'PlayDomain' in params ? params.PlayDomain : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.ServiceName = 'ServiceName' in params ? params.ServiceName : null; } } /** * CreateLiveTranscodeTemplate request structure. * @class */ class CreateLiveTranscodeTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template name, such as “900p”. This can be only a combination of letters and digits. Length limit: Standard transcoding: 1-10 characters Top speed codec transcoding: 3-10 characters * @type {string || null} */ this.TemplateName = null; /** * Video bitrate in Kbps. Value range: 100-8000. Note: the transcoding template requires that the bitrate be unique. Therefore, the final saved bitrate may be different from the input bitrate. * @type {number || null} */ this.VideoBitrate = null; /** * Audio codec. Default value: aac. Note: this parameter is unsupported now. * @type {string || null} */ this.Acodec = null; /** * Audio bitrate. Default value: 0. Value range: 0-500. * @type {number || null} */ this.AudioBitrate = null; /** * Video codec. Valid values: h264, h265, origin (default) origin: original codec as the output codec * @type {string || null} */ this.Vcodec = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * Whether to keep the video. 0: no; 1: yes. Default value: 1. * @type {number || null} */ this.NeedVideo = null; /** * Width. Default value: 0. Value range: 0-3000 It must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Width = null; /** * Whether to keep the audio. 0: no; 1: yes. Default value: 1. * @type {number || null} */ this.NeedAudio = null; /** * Height. Default value: 0. Value range: [0,3000] The value must be a multiple of 2, and 0 is the original height. * @type {number || null} */ this.Height = null; /** * Frame rate. Default value: 0. Value range: 0-60 * @type {number || null} */ this.Fps = null; /** * Keyframe interval in seconds. Default value: original interval Value range: 2-6 * @type {number || null} */ this.Gop = null; /** * Rotation angle. Default value: 0. Valid values: 0, 90, 180, 270 * @type {number || null} */ this.Rotate = null; /** * Encoding quality: baseline/main/high. Default value: baseline. * @type {string || null} */ this.Profile = null; /** * Whether to use the original bitrate when the set bitrate is larger than the original bitrate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.BitrateToOrig = null; /** * Whether to use the original height when the set height is higher than the original height. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.HeightToOrig = null; /** * Whether to use the original frame rate when the set frame rate is larger than the original frame rate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.FpsToOrig = null; /** * Whether it is a top speed codec template. 0: no, 1: yes. Default value: 0. * @type {number || null} */ this.AiTransCode = null; /** * Bitrate compression ratio of top speed codec video. Target bitrate of top speed code = VideoBitrate * (1-AdaptBitratePercent) Value range: 0.0-0.5. * @type {number || null} */ this.AdaptBitratePercent = null; /** * Whether to use the short side as the video height. 0: no, 1: yes. Default value: 0. * @type {number || null} */ this.ShortEdgeAsHeight = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.VideoBitrate = 'VideoBitrate' in params ? params.VideoBitrate : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.AudioBitrate = 'AudioBitrate' in params ? params.AudioBitrate : null; this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.Description = 'Description' in params ? params.Description : null; this.NeedVideo = 'NeedVideo' in params ? params.NeedVideo : null; this.Width = 'Width' in params ? params.Width : null; this.NeedAudio = 'NeedAudio' in params ? params.NeedAudio : null; this.Height = 'Height' in params ? params.Height : null; this.Fps = 'Fps' in params ? params.Fps : null; this.Gop = 'Gop' in params ? params.Gop : null; this.Rotate = 'Rotate' in params ? params.Rotate : null; this.Profile = 'Profile' in params ? params.Profile : null; this.BitrateToOrig = 'BitrateToOrig' in params ? params.BitrateToOrig : null; this.HeightToOrig = 'HeightToOrig' in params ? params.HeightToOrig : null; this.FpsToOrig = 'FpsToOrig' in params ? params.FpsToOrig : null; this.AiTransCode = 'AiTransCode' in params ? params.AiTransCode : null; this.AdaptBitratePercent = 'AdaptBitratePercent' in params ? params.AdaptBitratePercent : null; this.ShortEdgeAsHeight = 'ShortEdgeAsHeight' in params ? params.ShortEdgeAsHeight : null; } } /** * DescribeLiveStreamPublishedList response structure. * @class */ class DescribeLiveStreamPublishedListResponse extends AbstractModel { constructor(){ super(); /** * Push record information. * @type {Array.<StreamName> || null} */ this.PublishInfo = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page * @type {number || null} */ this.PageSize = null; /** * Total number of eligible ones. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.PublishInfo) { this.PublishInfo = new Array(); for (let z in params.PublishInfo) { let obj = new StreamName(); obj.deserialize(params.PublishInfo[z]); this.PublishInfo.push(obj); } } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveDomain request structure. * @class */ class DeleteLiveDomainRequest extends AbstractModel { constructor(){ super(); /** * Domain name to be deleted. * @type {string || null} */ this.DomainName = null; /** * Type. 0: push, 1: playback. * @type {number || null} */ this.DomainType = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.DomainType = 'DomainType' in params ? params.DomainType : null; } } /** * AddDelayLiveStream response structure. * @class */ class AddDelayLiveStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveTranscodeTemplates response structure. * @class */ class DescribeLiveTranscodeTemplatesResponse extends AbstractModel { constructor(){ super(); /** * List of transcoding templates. * @type {Array.<TemplateInfo> || null} */ this.Templates = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Templates) { this.Templates = new Array(); for (let z in params.Templates) { let obj = new TemplateInfo(); obj.deserialize(params.Templates[z]); this.Templates.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveCallbackRule request structure. * @class */ class DeleteLiveCallbackRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; } } /** * Playback authentication key information. * @class */ class PlayAuthKeyInfo extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable: 0: disable. 1: enable. * @type {number || null} */ this.Enable = null; /** * Authentication key. * @type {string || null} */ this.AuthKey = null; /** * Validity period in seconds. * @type {number || null} */ this.AuthDelta = null; /** * Authentication `BackKey`. * @type {string || null} */ this.AuthBackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.AuthKey = 'AuthKey' in params ? params.AuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; this.AuthBackKey = 'AuthBackKey' in params ? params.AuthBackKey : null; } } /** * ModifyLiveTranscodeTemplate request structure. * @class */ class ModifyLiveTranscodeTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Video codec. Valid values: h264, h265, origin (default) origin: original codec as the output codec * @type {string || null} */ this.Vcodec = null; /** * Audio codec. Defaut value: aac. Note: this parameter is unsupported now. * @type {string || null} */ this.Acodec = null; /** * Audio bitrate. Default value: 0. Value range: 0-500. * @type {number || null} */ this.AudioBitrate = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * Video bitrate in Kbps. Value range: 100-8000. Note: the transcoding template requires that the bitrate be unique. Therefore, the final saved bitrate may be different from the input bitrate. * @type {number || null} */ this.VideoBitrate = null; /** * Width in pixels. Value range: 0-3000. It must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Width = null; /** * Whether to keep the video. 0: no; 1: yes. Default value: 1. * @type {number || null} */ this.NeedVideo = null; /** * Whether to keep the audio. 0: no; 1: yes. Default value: 1. * @type {number || null} */ this.NeedAudio = null; /** * Height in pixels. Value range: 0-3000. It must be a multiple of 2. The original height is 0. * @type {number || null} */ this.Height = null; /** * Frame rate in fps. Default value: 0. Value range: 0-60 * @type {number || null} */ this.Fps = null; /** * Keyframe interval in seconds. Value range: 2-6 * @type {number || null} */ this.Gop = null; /** * Rotation angle. Default value: 0. Valid values: 0, 90, 180, 270 * @type {number || null} */ this.Rotate = null; /** * Encoding quality: baseline/main/high. * @type {string || null} */ this.Profile = null; /** * Whether to use the original bitrate when the set bitrate is larger than the original bitrate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.BitrateToOrig = null; /** * Whether to use the original height when the set height is higher than the original height. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.HeightToOrig = null; /** * Whether to use the original frame rate when the set frame rate is larger than the original frame rate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.FpsToOrig = null; /** * Bitrate compression ratio of top speed codec video. Target bitrate of top speed code = VideoBitrate * (1-AdaptBitratePercent) Value range: 0.0-0.5. * @type {number || null} */ this.AdaptBitratePercent = null; /** * Whether to use the short side as the video height. 0: no, 1: yes. Default value: 0. * @type {number || null} */ this.ShortEdgeAsHeight = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.AudioBitrate = 'AudioBitrate' in params ? params.AudioBitrate : null; this.Description = 'Description' in params ? params.Description : null; this.VideoBitrate = 'VideoBitrate' in params ? params.VideoBitrate : null; this.Width = 'Width' in params ? params.Width : null; this.NeedVideo = 'NeedVideo' in params ? params.NeedVideo : null; this.NeedAudio = 'NeedAudio' in params ? params.NeedAudio : null; this.Height = 'Height' in params ? params.Height : null; this.Fps = 'Fps' in params ? params.Fps : null; this.Gop = 'Gop' in params ? params.Gop : null; this.Rotate = 'Rotate' in params ? params.Rotate : null; this.Profile = 'Profile' in params ? params.Profile : null; this.BitrateToOrig = 'BitrateToOrig' in params ? params.BitrateToOrig : null; this.HeightToOrig = 'HeightToOrig' in params ? params.HeightToOrig : null; this.FpsToOrig = 'FpsToOrig' in params ? params.FpsToOrig : null; this.AdaptBitratePercent = 'AdaptBitratePercent' in params ? params.AdaptBitratePercent : null; this.ShortEdgeAsHeight = 'ShortEdgeAsHeight' in params ? params.ShortEdgeAsHeight : null; } } /** * ModifyLiveDomainCert response structure. * @class */ class ModifyLiveDomainCertResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * EnableLiveDomain request structure. * @class */ class EnableLiveDomainRequest extends AbstractModel { constructor(){ super(); /** * LVB domain name to be enabled. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * DescribeAllStreamPlayInfoList response structure. * @class */ class DescribeAllStreamPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Query point in time in the returned input parameters. * @type {string || null} */ this.QueryTime = null; /** * Data information list. * @type {Array.<MonitorStreamPlayInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.QueryTime = 'QueryTime' in params ? params.QueryTime : null; if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new MonitorStreamPlayInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ForbidLiveDomain response structure. * @class */ class ForbidLiveDomainResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveSnapshotRules request structure. * @class */ class DescribeLiveSnapshotRulesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * CreateRecordTask request structure. * @class */ class CreateRecordTaskRequest extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Recording end time in UNIX timestamp format. `EndTime` should be later than `StartTime` and the current time, and the duration between `EndTime` and `StartTime` is up to 24 hours. * @type {number || null} */ this.EndTime = null; /** * Recording start time in UNIX timestamp format. Leaving this parameter empty means starting recording now. `StartTime` cannot be later than the current time plus 6 days. * @type {number || null} */ this.StartTime = null; /** * Push type. Default value: 0. Valid values: 0: LVB push. 1: mixed stream, i.e., A + B = C mixed stream. * @type {number || null} */ this.StreamType = null; /** * Recording template ID, which is the returned value of `CreateLiveRecordTemplate`. If this parameter is left empty or incorrect, the stream will be recorded in HLS format and retained permanently by default. * @type {number || null} */ this.TemplateId = null; /** * Extension field which is not defined now. It is empty by default. * @type {string || null} */ this.Extension = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.StreamType = 'StreamType' in params ? params.StreamType : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.Extension = 'Extension' in params ? params.Extension : null; } } /** * CreateLiveTranscodeRule response structure. * @class */ class CreateLiveTranscodeRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveCallbackRule response structure. * @class */ class CreateLiveCallbackRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveRecordTemplate response structure. * @class */ class DescribeLiveRecordTemplateResponse extends AbstractModel { constructor(){ super(); /** * Recording template information. * @type {RecordTemplateInfo || null} */ this.Template = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Template) { let obj = new RecordTemplateInfo(); obj.deserialize(params.Template) this.Template = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeAreaBillBandwidthAndFluxList request structure. * @class */ class DescribeAreaBillBandwidthAndFluxListRequest extends AbstractModel { constructor(){ super(); /** * Start time point in the format of yyyy-mm-dd HH:MM:SS. * @type {string || null} */ this.StartTime = null; /** * End time point in the format of yyyy-mm-dd HH:MM:SS. The difference between the start time and end time cannot be greater than 1 days. * @type {string || null} */ this.EndTime = null; /** * LVB playback domain name. If it is left blank, the full data will be queried. * @type {Array.<string> || null} */ this.PlayDomains = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; } } /** * BindLiveDomainCert response structure. * @class */ class BindLiveDomainCertResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Rule information * @class */ class CallBackRuleInfo extends AbstractModel { constructor(){ super(); /** * Rule creation time. * @type {string || null} */ this.CreateTime = null; /** * Rule update time. * @type {string || null} */ this.UpdateTime = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path. * @type {string || null} */ this.AppName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.UpdateTime = 'UpdateTime' in params ? params.UpdateTime : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; } } /** * Aggregated playback statistics. * @class */ class PlaySumStatInfo extends AbstractModel { constructor(){ super(); /** * Domain name or stream ID. * @type {string || null} */ this.Name = null; /** * Average download speed, In MB/s. Calculation formula: average download speed per minute. * @type {number || null} */ this.AvgFluxPerSecond = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.AvgFluxPerSecond = 'AvgFluxPerSecond' in params ? params.AvgFluxPerSecond : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; } } /** * DescribeLiveTranscodeTemplates request structure. * @class */ class DescribeLiveTranscodeTemplatesRequest extends AbstractModel { constructor(){ super(); } /** * @private */ deserialize(params) { if (!params) { return; } } } /** * HLS-specific recording parameter * @class */ class HlsSpecialParam extends AbstractModel { constructor(){ super(); /** * Timeout period for restarting an interrupted HLS push. Value range: [0, 1,800]. * @type {number || null} */ this.FlowContinueDuration = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.FlowContinueDuration = 'FlowContinueDuration' in params ? params.FlowContinueDuration : null; } } /** * DescribeLiveRecordRules response structure. * @class */ class DescribeLiveRecordRulesResponse extends AbstractModel { constructor(){ super(); /** * List of rules. * @type {Array.<RuleInfo> || null} */ this.Rules = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Rules) { this.Rules = new Array(); for (let z in params.Rules) { let obj = new RuleInfo(); obj.deserialize(params.Rules[z]); this.Rules.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveSnapshotTemplate request structure. * @class */ class CreateLiveSnapshotTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template name. Maximum length: 255 bytes. Only letters, digits, underscores, and hyphens can be contained. * @type {string || null} */ this.TemplateName = null; /** * COS application ID. * @type {number || null} */ this.CosAppId = null; /** * COS bucket name. Note: the value of `CosBucket` cannot contain `-[appid]`. * @type {string || null} */ this.CosBucket = null; /** * COS region. * @type {string || null} */ this.CosRegion = null; /** * Description. Maximum length: 1,024 bytes. Only letters, digits, underscores, and hyphens can be contained. * @type {string || null} */ this.Description = null; /** * Screencapturing interval in seconds. Default value: 10s. Value range: 5-300s. * @type {number || null} */ this.SnapshotInterval = null; /** * Screenshot width. Default value: `0` (original width) Value range: 0-3000 * @type {number || null} */ this.Width = null; /** * Screenshot height. Default value: `0` (original height) Value range: 0-2000 * @type {number || null} */ this.Height = null; /** * Whether to enable porn detection. 0: no, 1: yes. Default value: 0 * @type {number || null} */ this.PornFlag = null; /** * COS Bucket folder prefix. If no value is entered, the default value `/{Year}-{Month}-{Day}` will be used. * @type {string || null} */ this.CosPrefix = null; /** * COS filename. If no value is entered, the default value `{StreamID}-screenshot-{Hour}-{Minute}-{Second}-{Width}x{Height}{Ext}` will be used. * @type {string || null} */ this.CosFileName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.CosAppId = 'CosAppId' in params ? params.CosAppId : null; this.CosBucket = 'CosBucket' in params ? params.CosBucket : null; this.CosRegion = 'CosRegion' in params ? params.CosRegion : null; this.Description = 'Description' in params ? params.Description : null; this.SnapshotInterval = 'SnapshotInterval' in params ? params.SnapshotInterval : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.PornFlag = 'PornFlag' in params ? params.PornFlag : null; this.CosPrefix = 'CosPrefix' in params ? params.CosPrefix : null; this.CosFileName = 'CosFileName' in params ? params.CosFileName : null; } } /** * DescribeLiveDomainPlayInfoList response structure. * @class */ class DescribeLiveDomainPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Data time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Real-time total bandwidth. * @type {number || null} */ this.TotalBandwidth = null; /** * Real-time total traffic. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Real-time total number of connections. * @type {number || null} */ this.TotalOnline = null; /** * Data by domain name. * @type {Array.<DomainInfoList> || null} */ this.DomainInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.TotalBandwidth = 'TotalBandwidth' in params ? params.TotalBandwidth : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.TotalOnline = 'TotalOnline' in params ? params.TotalOnline : null; if (params.DomainInfoList) { this.DomainInfoList = new Array(); for (let z in params.DomainInfoList) { let obj = new DomainInfoList(); obj.deserialize(params.DomainInfoList[z]); this.DomainInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * HTTP return code data * @class */ class HttpCodeValue extends AbstractModel { constructor(){ super(); /** * Time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Occurrences. * @type {number || null} */ this.Numbers = null; /** * Proportion. * @type {number || null} */ this.Percentage = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Numbers = 'Numbers' in params ? params.Numbers : null; this.Percentage = 'Percentage' in params ? params.Percentage : null; } } /** * DescribeLiveStreamOnlineList request structure. * @class */ class DescribeLiveStreamOnlineListRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. If you use multiple paths, enter the `DomainName`. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. If you use multiple paths, enter the `AppName`. * @type {string || null} */ this.AppName = null; /** * Page number to get. Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Maximum value: 100. Value: any integer between 10 and 100. Default value: 10. * @type {number || null} */ this.PageSize = null; /** * Stream name, which is used for exact query. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } } /** * DeleteLiveSnapshotTemplate response structure. * @class */ class DeleteLiveSnapshotTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveSnapshotTemplate request structure. * @class */ class DescribeLiveSnapshotTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. Template ID returned by the [CreateLiveSnapshotTemplate](https://intl.cloud.tencent.com/document/product/267/32624?from_cn_redirect=1) API call. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DeleteLiveCert response structure. * @class */ class DeleteLiveCertResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateCommonMixStream response structure. * @class */ class CreateCommonMixStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * ModifyLiveDomainReferer request structure. * @class */ class ModifyLiveDomainRefererRequest extends AbstractModel { constructor(){ super(); /** * Playback domain name * @type {string || null} */ this.DomainName = null; /** * Whether to enable referer allowlist/blocklist authentication for the current domain name * @type {number || null} */ this.Enable = null; /** * List type. Valid values: `0` (blocklist), `1` (allowlist) * @type {number || null} */ this.Type = null; /** * Whether to allow empty referer. Valid values: `0` (no), `1` (yes) * @type {number || null} */ this.AllowEmpty = null; /** * Referer list. Separate items in it with semicolons (;). * @type {string || null} */ this.Rules = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.Type = 'Type' in params ? params.Type : null; this.AllowEmpty = 'AllowEmpty' in params ? params.AllowEmpty : null; this.Rules = 'Rules' in params ? params.Rules : null; } } /** * CreateLiveCallbackTemplate response structure. * @class */ class CreateLiveCallbackTemplateResponse extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLivePushAuthKey request structure. * @class */ class DescribeLivePushAuthKeyRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; } } /** * Queries the playback information by ISP and district. * @class */ class PlayStatInfo extends AbstractModel { constructor(){ super(); /** * Data point in time. * @type {string || null} */ this.Time = null; /** * Value of bandwidth/traffic/number of requests/number of concurrent connections/download speed. If there is no data returned, the value is 0. Note: this field may return null, indicating that no valid values can be obtained. * @type {number || null} */ this.Value = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Value = 'Value' in params ? params.Value : null; } } /** * DescribeLiveCallbackTemplate request structure. * @class */ class DescribeLiveCallbackTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. 1. Get the template ID in the returned value of the [CreateLiveCallbackTemplate](https://intl.cloud.tencent.com/document/product/267/32637?from_cn_redirect=1) API call. 2. You can query the list of created templates through the [DescribeLiveCallbackTemplates](https://intl.cloud.tencent.com/document/product/267/32632?from_cn_redirect=1) API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * ModifyLiveSnapshotTemplate request structure. * @class */ class ModifyLiveSnapshotTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. Maximum length: 255 bytes. * @type {string || null} */ this.TemplateName = null; /** * Description. Maximum length: 1,024 bytes. * @type {string || null} */ this.Description = null; /** * Screencapturing interval in seconds. Default value: 10s. Value range: 5-300s. * @type {number || null} */ this.SnapshotInterval = null; /** * Screenshot width. Default value: 0 (original width). * @type {number || null} */ this.Width = null; /** * Screenshot height. Default value: 0 (original height). * @type {number || null} */ this.Height = null; /** * Whether to enable porn detection. Default value: 0. 0: do not enable. 1: enable. * @type {number || null} */ this.PornFlag = null; /** * COS application ID. * @type {number || null} */ this.CosAppId = null; /** * COS bucket name. Note: the value of `CosBucket` cannot contain `-[appid]`. * @type {string || null} */ this.CosBucket = null; /** * COS region. * @type {string || null} */ this.CosRegion = null; /** * COS bucket folder prefix. * @type {string || null} */ this.CosPrefix = null; /** * COS filename. * @type {string || null} */ this.CosFileName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.SnapshotInterval = 'SnapshotInterval' in params ? params.SnapshotInterval : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.PornFlag = 'PornFlag' in params ? params.PornFlag : null; this.CosAppId = 'CosAppId' in params ? params.CosAppId : null; this.CosBucket = 'CosBucket' in params ? params.CosBucket : null; this.CosRegion = 'CosRegion' in params ? params.CosRegion : null; this.CosPrefix = 'CosPrefix' in params ? params.CosPrefix : null; this.CosFileName = 'CosFileName' in params ? params.CosFileName : null; } } /** * DescribeLiveCert response structure. * @class */ class DescribeLiveCertResponse extends AbstractModel { constructor(){ super(); /** * Certificate information. * @type {CertInfo || null} */ this.CertInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.CertInfo) { let obj = new CertInfo(); obj.deserialize(params.CertInfo) this.CertInfo = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveRecordRule response structure. * @class */ class CreateLiveRecordRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveTranscodeTemplate request structure. * @class */ class DescribeLiveTranscodeTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template ID. Note: get the template ID in the returned value of the [CreateLiveTranscodeTemplate](https://intl.cloud.tencent.com/document/product/267/32646?from_cn_redirect=1) API call. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * ModifyLiveCallbackTemplate response structure. * @class */ class ModifyLiveCallbackTemplateResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveWatermark response structure. * @class */ class DeleteLiveWatermarkResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLivePushAuthKey response structure. * @class */ class DescribeLivePushAuthKeyResponse extends AbstractModel { constructor(){ super(); /** * Push authentication key information. * @type {PushAuthKeyInfo || null} */ this.PushAuthKeyInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.PushAuthKeyInfo) { let obj = new PushAuthKeyInfo(); obj.deserialize(params.PushAuthKeyInfo) this.PushAuthKeyInfo = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveWatermarkRule request structure. * @class */ class CreateLiveWatermarkRuleRequest extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Watermark ID, which is the `WatermarkId` returned by the [AddLiveWatermark](https://intl.cloud.tencent.com/document/product/267/30154?from_cn_redirect=1) API. * @type {number || null} */ this.TemplateId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; } } /** * DescribeLiveRecordTemplates request structure. * @class */ class DescribeLiveRecordTemplatesRequest extends AbstractModel { constructor(){ super(); /** * Whether it is an LCB template. Default value: 0. 0: LVB. 1: LCB. * @type {number || null} */ this.IsDelayLive = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; } } /** * DescribeAllStreamPlayInfoList request structure. * @class */ class DescribeAllStreamPlayInfoListRequest extends AbstractModel { constructor(){ super(); /** * Query time point accurate to the minute. You can query data within the last month. As there is a 5-minute delay in the data, you're advised to pass in a time point 5 minutes earlier than needed. Format: yyyy-mm-dd HH:MM:00. As the accuracy is to the minute, please set the value of second to `00`. * @type {string || null} */ this.QueryTime = null; /** * Playback domain name list. If this parameter is left empty, full data will be queried. * @type {Array.<string> || null} */ this.PlayDomains = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.QueryTime = 'QueryTime' in params ? params.QueryTime : null; this.PlayDomains = 'PlayDomains' in params ? params.PlayDomains : null; } } /** * DescribeLiveDomain response structure. * @class */ class DescribeLiveDomainResponse extends AbstractModel { constructor(){ super(); /** * Domain name information. Note: this field may return `null`, indicating that no valid value is obtained. * @type {DomainInfo || null} */ this.DomainInfo = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DomainInfo) { let obj = new DomainInfo(); obj.deserialize(params.DomainInfo) this.DomainInfo = obj; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteRecordTask request structure. * @class */ class DeleteRecordTaskRequest extends AbstractModel { constructor(){ super(); /** * Task ID returned by `CreateRecordTask`. The recording task specified by `TaskId` will be deleted. * @type {string || null} */ this.TaskId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TaskId = 'TaskId' in params ? params.TaskId : null; } } /** * StopLiveRecord response structure. * @class */ class StopLiveRecordResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeStreamDayPlayInfoList response structure. * @class */ class DescribeStreamDayPlayInfoListResponse extends AbstractModel { constructor(){ super(); /** * Playback data information list. * @type {Array.<PlayDataInfoByStream> || null} */ this.DataInfoList = null; /** * Total number. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Page number where the current data resides. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. * @type {number || null} */ this.PageSize = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new PlayDataInfoByStream(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeVisitTopSumInfoList response structure. * @class */ class DescribeVisitTopSumInfoListResponse extends AbstractModel { constructor(){ super(); /** * Page number, Value range: [1,1000], Default value: 1. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. Value range: [1,1000]. Default value: 20. * @type {number || null} */ this.PageSize = null; /** * Bandwidth metric. Valid values: "Domain", "StreamId". * @type {string || null} */ this.TopIndex = null; /** * Sorting metric. Valid values: AvgFluxPerSecond (sort by average traffic per second), TotalRequest (sort by total requests), TotalFlux (sort by total traffic). Default value: TotalRequest. * @type {string || null} */ this.OrderParam = null; /** * Total number of results. * @type {number || null} */ this.TotalNum = null; /** * Total number of result pages. * @type {number || null} */ this.TotalPage = null; /** * Data content. * @type {Array.<PlaySumStatInfo> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.TopIndex = 'TopIndex' in params ? params.TopIndex : null; this.OrderParam = 'OrderParam' in params ? params.OrderParam : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new PlaySumStatInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateLiveSnapshotRule response structure. * @class */ class CreateLiveSnapshotRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Delayed playback information. * @class */ class DelayInfo extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Delay time in seconds. * @type {number || null} */ this.DelayInterval = null; /** * Creation time in UTC time. Note: the difference between UTC time and Beijing time is 8 hours. Example: 2019-06-18T12:00:00Z (i.e., June 18, 2019 20:00:00 Beijing time). * @type {string || null} */ this.CreateTime = null; /** * Expiration time in UTC time. Note: the difference between UTC time and Beijing time is 8 hours. Example: 2019-06-18T12:00:00Z (i.e., June 18, 2019 20:00:00 Beijing time). * @type {string || null} */ this.ExpireTime = null; /** * Current status: -1: expired. 1: in effect. * @type {number || null} */ this.Status = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DelayInterval = 'DelayInterval' in params ? params.DelayInterval : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.ExpireTime = 'ExpireTime' in params ? params.ExpireTime : null; this.Status = 'Status' in params ? params.Status : null; } } /** * DescribeLiveStreamEventList response structure. * @class */ class DescribeLiveStreamEventListResponse extends AbstractModel { constructor(){ super(); /** * List of streaming events. * @type {Array.<StreamEventInfo> || null} */ this.EventList = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Number of entries per page. * @type {number || null} */ this.PageSize = null; /** * Total number of eligible ones. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.EventList) { this.EventList = new Array(); for (let z in params.EventList) { let obj = new StreamEventInfo(); obj.deserialize(params.EventList[z]); this.EventList.push(obj); } } this.PageNum = 'PageNum' in params ? params.PageNum : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DescribeLiveCallbackRules response structure. * @class */ class DescribeLiveCallbackRulesResponse extends AbstractModel { constructor(){ super(); /** * Rule information list. * @type {Array.<CallBackRuleInfo> || null} */ this.Rules = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.Rules) { this.Rules = new Array(); for (let z in params.Rules) { let obj = new CallBackRuleInfo(); obj.deserialize(params.Rules[z]); this.Rules.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * CreateRecordTask response structure. * @class */ class CreateRecordTaskResponse extends AbstractModel { constructor(){ super(); /** * A globally unique task ID. If `TaskId` is returned, the recording task has been successfully created. * @type {string || null} */ this.TaskId = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TaskId = 'TaskId' in params ? params.TaskId : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * List of forbidden streams * @class */ class ForbidStreamInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Forbidding expiration time. * @type {string || null} */ this.ExpireTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.ExpireTime = 'ExpireTime' in params ? params.ExpireTime : null; } } /** * ResumeDelayLiveStream response structure. * @class */ class ResumeDelayLiveStreamResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * Bandwidth, traffic, number of requests, and number of concurrent connections of an ISP in a district. * @class */ class GroupProIspDataInfo extends AbstractModel { constructor(){ super(); /** * District. * @type {string || null} */ this.ProvinceName = null; /** * ISP. * @type {string || null} */ this.IspName = null; /** * Detailed data at the minute level. * @type {Array.<CdnPlayStatData> || null} */ this.DetailInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ProvinceName = 'ProvinceName' in params ? params.ProvinceName : null; this.IspName = 'IspName' in params ? params.IspName : null; if (params.DetailInfoList) { this.DetailInfoList = new Array(); for (let z in params.DetailInfoList) { let obj = new CdnPlayStatData(); obj.deserialize(params.DetailInfoList[z]); this.DetailInfoList.push(obj); } } } } /** * DeleteLiveDomain response structure. * @class */ class DeleteLiveDomainResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * General stream mix input crop parameter. * @class */ class CommonMixCropParams extends AbstractModel { constructor(){ super(); /** * Crop width. Value range: [0,2000]. * @type {number || null} */ this.CropWidth = null; /** * Crop height. Value range: [0,2000]. * @type {number || null} */ this.CropHeight = null; /** * Starting crop X coordinate. Value range: [0,2000]. * @type {number || null} */ this.CropStartLocationX = null; /** * Starting crop Y coordinate. Value range: [0,2000]. * @type {number || null} */ this.CropStartLocationY = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CropWidth = 'CropWidth' in params ? params.CropWidth : null; this.CropHeight = 'CropHeight' in params ? params.CropHeight : null; this.CropStartLocationX = 'CropStartLocationX' in params ? params.CropStartLocationX : null; this.CropStartLocationY = 'CropStartLocationY' in params ? params.CropStartLocationY : null; } } /** * CreateLiveRecordTemplate request structure. * @class */ class CreateLiveRecordTemplateRequest extends AbstractModel { constructor(){ super(); /** * Template name. Only letters, digits, underscores, and hyphens can be contained. * @type {string || null} */ this.TemplateName = null; /** * Message description * @type {string || null} */ this.Description = null; /** * FLV recording parameter, which is set when FLV recording is enabled. * @type {RecordParam || null} */ this.FlvParam = null; /** * HLS recording parameter, which is set when HLS recording is enabled. * @type {RecordParam || null} */ this.HlsParam = null; /** * Mp4 recording parameter, which is set when Mp4 recording is enabled. * @type {RecordParam || null} */ this.Mp4Param = null; /** * AAC recording parameter, which is set when AAC recording is enabled. * @type {RecordParam || null} */ this.AacParam = null; /** * LVB type. Default value: 0. 0: LVB. 1: LCB. * @type {number || null} */ this.IsDelayLive = null; /** * HLS-specific recording parameter. * @type {HlsSpecialParam || null} */ this.HlsSpecialParam = null; /** * Mp3 recording parameter, which is set when Mp3 recording is enabled. * @type {RecordParam || null} */ this.Mp3Param = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; if (params.FlvParam) { let obj = new RecordParam(); obj.deserialize(params.FlvParam) this.FlvParam = obj; } if (params.HlsParam) { let obj = new RecordParam(); obj.deserialize(params.HlsParam) this.HlsParam = obj; } if (params.Mp4Param) { let obj = new RecordParam(); obj.deserialize(params.Mp4Param) this.Mp4Param = obj; } if (params.AacParam) { let obj = new RecordParam(); obj.deserialize(params.AacParam) this.AacParam = obj; } this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; if (params.HlsSpecialParam) { let obj = new HlsSpecialParam(); obj.deserialize(params.HlsSpecialParam) this.HlsSpecialParam = obj; } if (params.Mp3Param) { let obj = new RecordParam(); obj.deserialize(params.Mp3Param) this.Mp3Param = obj; } } } /** * DescribeProIspPlaySumInfoList response structure. * @class */ class DescribeProIspPlaySumInfoListResponse extends AbstractModel { constructor(){ super(); /** * Total traffic. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Statistics type. * @type {string || null} */ this.StatType = null; /** * Number of results per page. * @type {number || null} */ this.PageSize = null; /** * Page number. * @type {number || null} */ this.PageNum = null; /** * Total number of results. * @type {number || null} */ this.TotalNum = null; /** * Total number of pages. * @type {number || null} */ this.TotalPage = null; /** * Aggregated data list by district, ISP, or country/region. * @type {Array.<ProIspPlaySumInfo> || null} */ this.DataInfoList = null; /** * Download speed in MB/s. Calculation method: total traffic/total duration. * @type {number || null} */ this.AvgFluxPerSecond = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.StatType = 'StatType' in params ? params.StatType : null; this.PageSize = 'PageSize' in params ? params.PageSize : null; this.PageNum = 'PageNum' in params ? params.PageNum : null; this.TotalNum = 'TotalNum' in params ? params.TotalNum : null; this.TotalPage = 'TotalPage' in params ? params.TotalPage : null; if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new ProIspPlaySumInfo(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.AvgFluxPerSecond = 'AvgFluxPerSecond' in params ? params.AvgFluxPerSecond : null; this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveCert request structure. * @class */ class DeleteLiveCertRequest extends AbstractModel { constructor(){ super(); /** * Certificate ID obtained through the `DescribeLiveCerts` API. * @type {number || null} */ this.CertId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; } } /** * DescribeHttpStatusInfoList response structure. * @class */ class DescribeHttpStatusInfoListResponse extends AbstractModel { constructor(){ super(); /** * Playback status code list. * @type {Array.<HttpStatusData> || null} */ this.DataInfoList = null; /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } if (params.DataInfoList) { this.DataInfoList = new Array(); for (let z in params.DataInfoList) { let obj = new HttpStatusData(); obj.deserialize(params.DataInfoList[z]); this.DataInfoList.push(obj); } } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } /** * DeleteLiveRecordRule response structure. * @class */ class DeleteLiveRecordRuleResponse extends AbstractModel { constructor(){ super(); /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @type {string || null} */ this.RequestId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RequestId = 'RequestId' in params ? params.RequestId : null; } } module.exports = { CreateLiveSnapshotRuleRequest: CreateLiveSnapshotRuleRequest, BillDataInfo: BillDataInfo, EnableLiveDomainResponse: EnableLiveDomainResponse, CreateLiveCertRequest: CreateLiveCertRequest, StopRecordTaskResponse: StopRecordTaskResponse, DescribeDeliverBandwidthListResponse: DescribeDeliverBandwidthListResponse, DeleteLiveRecordRuleRequest: DeleteLiveRecordRuleRequest, ResumeLiveStreamRequest: ResumeLiveStreamRequest, DeleteLiveTranscodeTemplateResponse: DeleteLiveTranscodeTemplateResponse, DescribeBillBandwidthAndFluxListResponse: DescribeBillBandwidthAndFluxListResponse, TemplateInfo: TemplateInfo, DeleteLiveCallbackRuleResponse: DeleteLiveCallbackRuleResponse, ResumeDelayLiveStreamRequest: ResumeDelayLiveStreamRequest, DescribeLiveWatermarkRulesResponse: DescribeLiveWatermarkRulesResponse, DescribeLiveCallbackTemplateResponse: DescribeLiveCallbackTemplateResponse, DeleteLiveSnapshotTemplateRequest: DeleteLiveSnapshotTemplateRequest, DescribeGroupProIspPlayInfoListResponse: DescribeGroupProIspPlayInfoListResponse, PushAuthKeyInfo: PushAuthKeyInfo, DescribeUploadStreamNumsResponse: DescribeUploadStreamNumsResponse, DeleteLiveRecordTemplateRequest: DeleteLiveRecordTemplateRequest, DeleteLiveCallbackTemplateResponse: DeleteLiveCallbackTemplateResponse, DescribeLiveStreamOnlineListResponse: DescribeLiveStreamOnlineListResponse, PushQualityData: PushQualityData, UnBindLiveDomainCertResponse: UnBindLiveDomainCertResponse, ModifyLivePlayAuthKeyRequest: ModifyLivePlayAuthKeyRequest, DescribeLiveDelayInfoListRequest: DescribeLiveDelayInfoListRequest, DomainCertInfo: DomainCertInfo, RecordTemplateInfo: RecordTemplateInfo, DeleteLiveTranscodeRuleResponse: DeleteLiveTranscodeRuleResponse, ConcurrentRecordStreamNum: ConcurrentRecordStreamNum, DescribeStreamPlayInfoListResponse: DescribeStreamPlayInfoListResponse, DescribeScreenShotSheetNumListResponse: DescribeScreenShotSheetNumListResponse, ModifyLiveSnapshotTemplateResponse: ModifyLiveSnapshotTemplateResponse, ModifyLivePushAuthKeyRequest: ModifyLivePushAuthKeyRequest, DeleteLiveCallbackTemplateRequest: DeleteLiveCallbackTemplateRequest, DescribeLiveStreamStateRequest: DescribeLiveStreamStateRequest, DescribeLivePlayAuthKeyResponse: DescribeLivePlayAuthKeyResponse, DescribeLiveCallbackTemplatesRequest: DescribeLiveCallbackTemplatesRequest, DomainInfo: DomainInfo, DescribeLiveTranscodeRulesRequest: DescribeLiveTranscodeRulesRequest, DeleteLiveSnapshotRuleRequest: DeleteLiveSnapshotRuleRequest, DescribePlayErrorCodeDetailInfoListRequest: DescribePlayErrorCodeDetailInfoListRequest, DescribeBillBandwidthAndFluxListRequest: DescribeBillBandwidthAndFluxListRequest, CommonMixOutputParams: CommonMixOutputParams, DescribeUploadStreamNumsRequest: DescribeUploadStreamNumsRequest, DescribeLiveSnapshotRulesResponse: DescribeLiveSnapshotRulesResponse, DescribeLiveTranscodeDetailInfoResponse: DescribeLiveTranscodeDetailInfoResponse, DescribeLiveDomainRequest: DescribeLiveDomainRequest, DescribeLiveStreamPublishedListRequest: DescribeLiveStreamPublishedListRequest, DeleteLiveTranscodeRuleRequest: DeleteLiveTranscodeRuleRequest, CreateLiveRecordRuleRequest: CreateLiveRecordRuleRequest, DescribeLiveSnapshotTemplatesRequest: DescribeLiveSnapshotTemplatesRequest, AddLiveWatermarkResponse: AddLiveWatermarkResponse, DescribeLiveStreamPushInfoListResponse: DescribeLiveStreamPushInfoListResponse, DescribeLiveDomainCertResponse: DescribeLiveDomainCertResponse, DescribeLiveRecordTemplateRequest: DescribeLiveRecordTemplateRequest, ModifyLiveDomainCertRequest: ModifyLiveDomainCertRequest, CreateLiveWatermarkRuleResponse: CreateLiveWatermarkRuleResponse, DescribeProIspPlaySumInfoListRequest: DescribeProIspPlaySumInfoListRequest, DescribeDeliverBandwidthListRequest: DescribeDeliverBandwidthListRequest, PlayCodeTotalInfo: PlayCodeTotalInfo, AddLiveWatermarkRequest: AddLiveWatermarkRequest, ModifyLiveTranscodeTemplateResponse: ModifyLiveTranscodeTemplateResponse, BillCountryInfo: BillCountryInfo, ModifyLiveRecordTemplateResponse: ModifyLiveRecordTemplateResponse, ModifyLivePlayDomainRequest: ModifyLivePlayDomainRequest, DeleteLiveRecordTemplateResponse: DeleteLiveRecordTemplateResponse, DescribeLiveWatermarkRequest: DescribeLiveWatermarkRequest, ProIspPlayCodeDataInfo: ProIspPlayCodeDataInfo, CommonMixLayoutParams: CommonMixLayoutParams, DescribeLiveDomainCertRequest: DescribeLiveDomainCertRequest, DescribeLiveStreamEventListRequest: DescribeLiveStreamEventListRequest, CallBackTemplateInfo: CallBackTemplateInfo, DescribePlayErrorCodeSumInfoListResponse: DescribePlayErrorCodeSumInfoListResponse, UnBindLiveDomainCertRequest: UnBindLiveDomainCertRequest, DeleteLiveRecordResponse: DeleteLiveRecordResponse, DescribeScreenShotSheetNumListRequest: DescribeScreenShotSheetNumListRequest, ForbidLiveStreamRequest: ForbidLiveStreamRequest, DescribeLiveDomainsResponse: DescribeLiveDomainsResponse, TimeValue: TimeValue, StreamOnlineInfo: StreamOnlineInfo, CreateLiveRecordResponse: CreateLiveRecordResponse, RuleInfo: RuleInfo, UpdateLiveWatermarkResponse: UpdateLiveWatermarkResponse, CreateLiveTranscodeTemplateResponse: CreateLiveTranscodeTemplateResponse, BillAreaInfo: BillAreaInfo, PlayDataInfoByStream: PlayDataInfoByStream, DescribeVisitTopSumInfoListRequest: DescribeVisitTopSumInfoListRequest, DayStreamPlayInfo: DayStreamPlayInfo, ModifyLivePlayDomainResponse: ModifyLivePlayDomainResponse, CancelCommonMixStreamResponse: CancelCommonMixStreamResponse, DescribeConcurrentRecordStreamNumResponse: DescribeConcurrentRecordStreamNumResponse, DescribeLiveCertsResponse: DescribeLiveCertsResponse, CommonMixInputParam: CommonMixInputParam, DescribeProvinceIspPlayInfoListResponse: DescribeProvinceIspPlayInfoListResponse, DescribeLiveRecordTemplatesResponse: DescribeLiveRecordTemplatesResponse, DescribeLiveCertRequest: DescribeLiveCertRequest, DescribeLiveCallbackTemplatesResponse: DescribeLiveCallbackTemplatesResponse, ModifyLivePlayAuthKeyResponse: ModifyLivePlayAuthKeyResponse, CreateLiveCallbackTemplateRequest: CreateLiveCallbackTemplateRequest, DescribeTopClientIpSumInfoListResponse: DescribeTopClientIpSumInfoListResponse, DropLiveStreamResponse: DropLiveStreamResponse, DescribeLiveStreamStateResponse: DescribeLiveStreamStateResponse, StopLiveRecordRequest: StopLiveRecordRequest, DeleteLiveWatermarkRuleRequest: DeleteLiveWatermarkRuleRequest, StreamEventInfo: StreamEventInfo, DeleteRecordTaskResponse: DeleteRecordTaskResponse, DescribeLiveWatermarksRequest: DescribeLiveWatermarksRequest, CreateLiveTranscodeRuleRequest: CreateLiveTranscodeRuleRequest, DescribeLiveWatermarkRulesRequest: DescribeLiveWatermarkRulesRequest, DropLiveStreamRequest: DropLiveStreamRequest, CreateCommonMixStreamRequest: CreateCommonMixStreamRequest, RefererAuthConfig: RefererAuthConfig, CreateLiveCertResponse: CreateLiveCertResponse, PushDataInfo: PushDataInfo, AddDelayLiveStreamRequest: AddDelayLiveStreamRequest, DescribeGroupProIspPlayInfoListRequest: DescribeGroupProIspPlayInfoListRequest, DescribeStreamDayPlayInfoListRequest: DescribeStreamDayPlayInfoListRequest, TranscodeDetailInfo: TranscodeDetailInfo, DescribeLiveSnapshotTemplateResponse: DescribeLiveSnapshotTemplateResponse, DescribeLiveTranscodeRulesResponse: DescribeLiveTranscodeRulesResponse, DescribeLiveDomainRefererResponse: DescribeLiveDomainRefererResponse, AddLiveDomainRequest: AddLiveDomainRequest, StreamName: StreamName, DescribeLiveCertsRequest: DescribeLiveCertsRequest, CdnPlayStatData: CdnPlayStatData, AddLiveDomainResponse: AddLiveDomainResponse, DescribeHttpStatusInfoListRequest: DescribeHttpStatusInfoListRequest, ModifyLiveCallbackTemplateRequest: ModifyLiveCallbackTemplateRequest, DescribeProvinceIspPlayInfoListRequest: DescribeProvinceIspPlayInfoListRequest, DescribeLivePlayAuthKeyRequest: DescribeLivePlayAuthKeyRequest, DescribeLiveForbidStreamListResponse: DescribeLiveForbidStreamListResponse, DescribeStreamPushInfoListRequest: DescribeStreamPushInfoListRequest, DomainInfoList: DomainInfoList, DescribeLiveWatermarkResponse: DescribeLiveWatermarkResponse, ResumeLiveStreamResponse: ResumeLiveStreamResponse, ModifyLiveRecordTemplateRequest: ModifyLiveRecordTemplateRequest, DescribeStreamPushInfoListResponse: DescribeStreamPushInfoListResponse, DescribeLiveStreamPushInfoListRequest: DescribeLiveStreamPushInfoListRequest, DescribeLiveWatermarksResponse: DescribeLiveWatermarksResponse, WatermarkInfo: WatermarkInfo, DescribeLiveForbidStreamListRequest: DescribeLiveForbidStreamListRequest, DescribeLiveDomainPlayInfoListRequest: DescribeLiveDomainPlayInfoListRequest, BindLiveDomainCertRequest: BindLiveDomainCertRequest, DescribeTopClientIpSumInfoListRequest: DescribeTopClientIpSumInfoListRequest, CreateLiveCallbackRuleRequest: CreateLiveCallbackRuleRequest, DeleteLiveWatermarkRuleResponse: DeleteLiveWatermarkRuleResponse, PublishTime: PublishTime, ModifyLiveCertResponse: ModifyLiveCertResponse, MonitorStreamPlayInfo: MonitorStreamPlayInfo, DescribeLiveTranscodeDetailInfoRequest: DescribeLiveTranscodeDetailInfoRequest, ModifyLiveDomainRefererResponse: ModifyLiveDomainRefererResponse, DeleteLiveWatermarkRequest: DeleteLiveWatermarkRequest, DescribeLiveDomainsRequest: DescribeLiveDomainsRequest, ProIspPlaySumInfo: ProIspPlaySumInfo, SnapshotTemplateInfo: SnapshotTemplateInfo, DeleteLiveSnapshotRuleResponse: DeleteLiveSnapshotRuleResponse, CreateLiveRecordRequest: CreateLiveRecordRequest, ForbidLiveStreamResponse: ForbidLiveStreamResponse, BandwidthInfo: BandwidthInfo, CancelCommonMixStreamRequest: CancelCommonMixStreamRequest, UpdateLiveWatermarkRequest: UpdateLiveWatermarkRequest, CertInfo: CertInfo, ModifyLivePushAuthKeyResponse: ModifyLivePushAuthKeyResponse, DescribeLiveDelayInfoListResponse: DescribeLiveDelayInfoListResponse, DeleteLiveTranscodeTemplateRequest: DeleteLiveTranscodeTemplateRequest, DescribeLiveCallbackRulesRequest: DescribeLiveCallbackRulesRequest, ClientIpPlaySumInfo: ClientIpPlaySumInfo, DescribeLiveTranscodeTemplateResponse: DescribeLiveTranscodeTemplateResponse, CreateLiveSnapshotTemplateResponse: CreateLiveSnapshotTemplateResponse, DescribeConcurrentRecordStreamNumRequest: DescribeConcurrentRecordStreamNumRequest, DescribePlayErrorCodeSumInfoListRequest: DescribePlayErrorCodeSumInfoListRequest, ModifyLiveCertRequest: ModifyLiveCertRequest, CommonMixControlParams: CommonMixControlParams, DescribeAreaBillBandwidthAndFluxListResponse: DescribeAreaBillBandwidthAndFluxListResponse, ForbidLiveDomainRequest: ForbidLiveDomainRequest, DescribeLiveRecordRulesRequest: DescribeLiveRecordRulesRequest, DescribePlayErrorCodeDetailInfoListResponse: DescribePlayErrorCodeDetailInfoListResponse, CreateLiveRecordTemplateResponse: CreateLiveRecordTemplateResponse, RecordParam: RecordParam, DomainDetailInfo: DomainDetailInfo, HttpStatusInfo: HttpStatusInfo, DeleteLiveRecordRequest: DeleteLiveRecordRequest, DescribeLiveSnapshotTemplatesResponse: DescribeLiveSnapshotTemplatesResponse, StopRecordTaskRequest: StopRecordTaskRequest, DescribeLiveDomainRefererRequest: DescribeLiveDomainRefererRequest, HttpStatusData: HttpStatusData, HttpCodeInfo: HttpCodeInfo, DescribeStreamPlayInfoListRequest: DescribeStreamPlayInfoListRequest, CreateLiveTranscodeTemplateRequest: CreateLiveTranscodeTemplateRequest, DescribeLiveStreamPublishedListResponse: DescribeLiveStreamPublishedListResponse, DeleteLiveDomainRequest: DeleteLiveDomainRequest, AddDelayLiveStreamResponse: AddDelayLiveStreamResponse, DescribeLiveTranscodeTemplatesResponse: DescribeLiveTranscodeTemplatesResponse, DeleteLiveCallbackRuleRequest: DeleteLiveCallbackRuleRequest, PlayAuthKeyInfo: PlayAuthKeyInfo, ModifyLiveTranscodeTemplateRequest: ModifyLiveTranscodeTemplateRequest, ModifyLiveDomainCertResponse: ModifyLiveDomainCertResponse, EnableLiveDomainRequest: EnableLiveDomainRequest, DescribeAllStreamPlayInfoListResponse: DescribeAllStreamPlayInfoListResponse, ForbidLiveDomainResponse: ForbidLiveDomainResponse, DescribeLiveSnapshotRulesRequest: DescribeLiveSnapshotRulesRequest, CreateRecordTaskRequest: CreateRecordTaskRequest, CreateLiveTranscodeRuleResponse: CreateLiveTranscodeRuleResponse, CreateLiveCallbackRuleResponse: CreateLiveCallbackRuleResponse, DescribeLiveRecordTemplateResponse: DescribeLiveRecordTemplateResponse, DescribeAreaBillBandwidthAndFluxListRequest: DescribeAreaBillBandwidthAndFluxListRequest, BindLiveDomainCertResponse: BindLiveDomainCertResponse, CallBackRuleInfo: CallBackRuleInfo, PlaySumStatInfo: PlaySumStatInfo, DescribeLiveTranscodeTemplatesRequest: DescribeLiveTranscodeTemplatesRequest, HlsSpecialParam: HlsSpecialParam, DescribeLiveRecordRulesResponse: DescribeLiveRecordRulesResponse, CreateLiveSnapshotTemplateRequest: CreateLiveSnapshotTemplateRequest, DescribeLiveDomainPlayInfoListResponse: DescribeLiveDomainPlayInfoListResponse, HttpCodeValue: HttpCodeValue, DescribeLiveStreamOnlineListRequest: DescribeLiveStreamOnlineListRequest, DeleteLiveSnapshotTemplateResponse: DeleteLiveSnapshotTemplateResponse, DescribeLiveSnapshotTemplateRequest: DescribeLiveSnapshotTemplateRequest, DeleteLiveCertResponse: DeleteLiveCertResponse, CreateCommonMixStreamResponse: CreateCommonMixStreamResponse, ModifyLiveDomainRefererRequest: ModifyLiveDomainRefererRequest, CreateLiveCallbackTemplateResponse: CreateLiveCallbackTemplateResponse, DescribeLivePushAuthKeyRequest: DescribeLivePushAuthKeyRequest, PlayStatInfo: PlayStatInfo, DescribeLiveCallbackTemplateRequest: DescribeLiveCallbackTemplateRequest, ModifyLiveSnapshotTemplateRequest: ModifyLiveSnapshotTemplateRequest, DescribeLiveCertResponse: DescribeLiveCertResponse, CreateLiveRecordRuleResponse: CreateLiveRecordRuleResponse, DescribeLiveTranscodeTemplateRequest: DescribeLiveTranscodeTemplateRequest, ModifyLiveCallbackTemplateResponse: ModifyLiveCallbackTemplateResponse, DeleteLiveWatermarkResponse: DeleteLiveWatermarkResponse, DescribeLivePushAuthKeyResponse: DescribeLivePushAuthKeyResponse, CreateLiveWatermarkRuleRequest: CreateLiveWatermarkRuleRequest, DescribeLiveRecordTemplatesRequest: DescribeLiveRecordTemplatesRequest, DescribeAllStreamPlayInfoListRequest: DescribeAllStreamPlayInfoListRequest, DescribeLiveDomainResponse: DescribeLiveDomainResponse, DeleteRecordTaskRequest: DeleteRecordTaskRequest, StopLiveRecordResponse: StopLiveRecordResponse, DescribeStreamDayPlayInfoListResponse: DescribeStreamDayPlayInfoListResponse, DescribeVisitTopSumInfoListResponse: DescribeVisitTopSumInfoListResponse, CreateLiveSnapshotRuleResponse: CreateLiveSnapshotRuleResponse, DelayInfo: DelayInfo, DescribeLiveStreamEventListResponse: DescribeLiveStreamEventListResponse, DescribeLiveCallbackRulesResponse: DescribeLiveCallbackRulesResponse, CreateRecordTaskResponse: CreateRecordTaskResponse, ForbidStreamInfo: ForbidStreamInfo, ResumeDelayLiveStreamResponse: ResumeDelayLiveStreamResponse, GroupProIspDataInfo: GroupProIspDataInfo, DeleteLiveDomainResponse: DeleteLiveDomainResponse, CommonMixCropParams: CommonMixCropParams, CreateLiveRecordTemplateRequest: CreateLiveRecordTemplateRequest, DescribeProIspPlaySumInfoListResponse: DescribeProIspPlaySumInfoListResponse, DeleteLiveCertRequest: DeleteLiveCertRequest, DescribeHttpStatusInfoListResponse: DescribeHttpStatusInfoListResponse, DeleteLiveRecordRuleResponse: DeleteLiveRecordRuleResponse, }
JPDSousa/rookit
rookit-auto/source/javapoet/lib/src/main/java/org/rookit/auto/javapoet/type/parameter/BaseJavaPoetTypeParameter.java
<filename>rookit-auto/source/javapoet/lib/src/main/java/org/rookit/auto/javapoet/type/parameter/BaseJavaPoetTypeParameter.java /******************************************************************************* * Copyright (C) 2018 <NAME> * * 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. ******************************************************************************/ package org.rookit.auto.javapoet.type.parameter; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.rookit.utils.optional.Optional; import org.rookit.utils.optional.OptionalFactory; import static java.util.Arrays.copyOf; final class BaseJavaPoetTypeParameter implements JavaPoetTypeParameter { private final OptionalFactory optionalFactory; private final ClassName className; private final TypeName[] arguments; BaseJavaPoetTypeParameter( final OptionalFactory optionalFactory, final ClassName className, final TypeName[] arguments) { this.optionalFactory = optionalFactory; this.className = className; this.arguments = copyOf(arguments, arguments.length); } @Override public ParameterizedTypeName buildTypeName() { return ParameterizedTypeName.get(this.className, this.arguments); } @Override public Optional<String> packageName() { return this.optionalFactory.of(this.className.packageName()); } }
dmoiseenko/wen
static/middlewares/main.serve.middleware.js
const send = require('koa-send'); const path = require('path'); const Router = require('koa-router'); const router = new Router(); const serve = ctx => send( ctx, ctx.path, { root: path.join(__dirname, '../../public/main'), maxage: 31536000 } ); router.get('/js/(.*)', serve); router.get('/css/(.*)', serve); router.get('/fonts/(.*)', serve); module.exports = () => router.routes();
KyuboNoh/HY
SimPEG/Mesh/BaseMesh.py
<reponame>KyuboNoh/HY import numpy as np from SimPEG import Utils class BaseMesh(object): """ BaseMesh does all the counting you don't want to do. BaseMesh should be inherited by meshes with a regular structure. :param numpy.array,list n: number of cells in each direction (dim, ) :param numpy.array,list x0: Origin of the mesh (dim, ) """ def __init__(self, n, x0=None): # Check inputs if x0 is None: x0 = np.zeros(len(n)) if not len(n) == len(x0): raise Exception("Dimension mismatch. x0 != len(n)") if len(n) > 3: raise Exception("Dimensions higher than 3 are not supported.") # Ensure x0 & n are 1D vectors self._n = np.array(n, dtype=int).ravel() self._x0 = np.array(x0, dtype=float).ravel() self._dim = len(self._x0) @property def x0(self): """ Origin of the mesh :rtype: numpy.array (dim, ) :return: x0 """ return self._x0 @property def dim(self): """ The dimension of the mesh (1, 2, or 3). :rtype: int :return: dim """ return self._dim @property def nC(self): """ Total number of cells in the mesh. :rtype: int :return: nC .. plot:: :include-source: from SimPEG import Mesh, np Mesh.TensorMesh([np.ones(n) for n in [2,3]]).plotGrid(centers=True,showIt=True) """ return self._n.prod() @property def nN(self): """ Total number of nodes :rtype: int :return: nN .. plot:: :include-source: from SimPEG import Mesh, np Mesh.TensorMesh([np.ones(n) for n in [2,3]]).plotGrid(nodes=True,showIt=True) """ return (self._n+1).prod() @property def nEx(self): """ Number of x-edges :rtype: int :return: nEx """ return (self._n + np.r_[0,1,1][:self.dim]).prod() @property def nEy(self): """ Number of y-edges :rtype: int :return: nEy """ return None if self.dim < 2 else (self._n + np.r_[1,0,1][:self.dim]).prod() @property def nEz(self): """ Number of z-edges :rtype: int :return: nEz """ return None if self.dim < 3 else (self._n + np.r_[1,1,0][:self.dim]).prod() @property def vnE(self): """ Total number of edges in each direction :rtype: numpy.array (dim, ) :return: [nEx, nEy, nEz] .. plot:: :include-source: from SimPEG import Mesh, np Mesh.TensorMesh([np.ones(n) for n in [2,3]]).plotGrid(edges=True,showIt=True) """ return np.array([x for x in [self.nEx, self.nEy, self.nEz] if not x is None]) @property def nE(self): """ Total number of edges. :rtype: int :return: sum([nEx, nEy, nEz]) """ return self.vnE.sum() @property def nFx(self): """ Number of x-faces :rtype: int :return: nFx """ return (self._n + np.r_[1,0,0][:self.dim]).prod() @property def nFy(self): """ Number of y-faces :rtype: int :return: nFy """ return None if self.dim < 2 else (self._n + np.r_[0,1,0][:self.dim]).prod() @property def nFz(self): """ Number of z-faces :rtype: int :return: nFz """ return None if self.dim < 3 else (self._n + np.r_[0,0,1][:self.dim]).prod() @property def vnF(self): """ Total number of faces in each direction :rtype: numpy.array (dim, ) :return: [nFx, nFy, nFz] .. plot:: :include-source: from SimPEG import Mesh, np Mesh.TensorMesh([np.ones(n) for n in [2,3]]).plotGrid(faces=True,showIt=True) """ return np.array([x for x in [self.nFx, self.nFy, self.nFz] if not x is None]) @property def nF(self): """ Total number of faces. :rtype: int :return: sum([nFx, nFy, nFz]) """ return self.vnF.sum() @property def normals(self): """ Face Normals :rtype: numpy.array (sum(nF), dim) :return: normals """ if self.dim == 2: nX = np.c_[np.ones(self.nFx), np.zeros(self.nFx)] nY = np.c_[np.zeros(self.nFy), np.ones(self.nFy)] return np.r_[nX, nY] elif self.dim == 3: nX = np.c_[np.ones(self.nFx), np.zeros(self.nFx), np.zeros(self.nFx)] nY = np.c_[np.zeros(self.nFy), np.ones(self.nFy), np.zeros(self.nFy)] nZ = np.c_[np.zeros(self.nFz), np.zeros(self.nFz), np.ones(self.nFz)] return np.r_[nX, nY, nZ] @property def tangents(self): """ Edge Tangents :rtype: numpy.array (sum(nE), dim) :return: normals """ if self.dim == 2: tX = np.c_[np.ones(self.nEx), np.zeros(self.nEx)] tY = np.c_[np.zeros(self.nEy), np.ones(self.nEy)] return np.r_[tX, tY] elif self.dim == 3: tX = np.c_[np.ones(self.nEx), np.zeros(self.nEx), np.zeros(self.nEx)] tY = np.c_[np.zeros(self.nEy), np.ones(self.nEy), np.zeros(self.nEy)] tZ = np.c_[np.zeros(self.nEz), np.zeros(self.nEz), np.ones(self.nEz)] return np.r_[tX, tY, tZ] def projectFaceVector(self, fV): """ Given a vector, fV, in cartesian coordinates, this will project it onto the mesh using the normals :param numpy.array fV: face vector with shape (nF, dim) :rtype: numpy.array with shape (nF, ) :return: projected face vector """ assert isinstance(fV, np.ndarray), 'fV must be an ndarray' assert len(fV.shape) == 2 and fV.shape[0] == self.nF and fV.shape[1] == self.dim, 'fV must be an ndarray of shape (nF x dim)' return np.sum(fV*self.normals, 1) def projectEdgeVector(self, eV): """ Given a vector, eV, in cartesian coordinates, this will project it onto the mesh using the tangents :param numpy.array eV: edge vector with shape (nE, dim) :rtype: numpy.array with shape (nE, ) :return: projected edge vector """ assert isinstance(eV, np.ndarray), 'eV must be an ndarray' assert len(eV.shape) == 2 and eV.shape[0] == self.nE and eV.shape[1] == self.dim, 'eV must be an ndarray of shape (nE x dim)' return np.sum(eV*self.tangents, 1) class BaseRectangularMesh(BaseMesh): """BaseRectangularMesh""" def __init__(self, n, x0=None): BaseMesh.__init__(self, n, x0) @property def nCx(self): """ Number of cells in the x direction :rtype: int :return: nCx """ return self._n[0] @property def nCy(self): """ Number of cells in the y direction :rtype: int :return: nCy or None if dim < 2 """ return None if self.dim < 2 else self._n[1] @property def nCz(self): """Number of cells in the z direction :rtype: int :return: nCz or None if dim < 3 """ return None if self.dim < 3 else self._n[2] @property def vnC(self): """ Total number of cells in each direction :rtype: numpy.array (dim, ) :return: [nCx, nCy, nCz] """ return np.array([x for x in [self.nCx, self.nCy, self.nCz] if not x is None]) @property def nNx(self): """ Number of nodes in the x-direction :rtype: int :return: nNx """ return self.nCx + 1 @property def nNy(self): """ Number of nodes in the y-direction :rtype: int :return: nNy or None if dim < 2 """ return None if self.dim < 2 else self.nCy + 1 @property def nNz(self): """ Number of nodes in the z-direction :rtype: int :return: nNz or None if dim < 3 """ return None if self.dim < 3 else self.nCz + 1 @property def vnN(self): """ Total number of nodes in each direction :rtype: numpy.array (dim, ) :return: [nNx, nNy, nNz] """ return np.array([x for x in [self.nNx, self.nNy, self.nNz] if not x is None]) @property def vnEx(self): """ Number of x-edges in each direction :rtype: numpy.array (dim, ) :return: vnEx """ return np.array([x for x in [self.nCx, self.nNy, self.nNz] if not x is None]) @property def vnEy(self): """ Number of y-edges in each direction :rtype: numpy.array (dim, ) :return: vnEy or None if dim < 2 """ return None if self.dim < 2 else np.array([x for x in [self.nNx, self.nCy, self.nNz] if not x is None]) @property def vnEz(self): """ Number of z-edges in each direction :rtype: numpy.array (dim, ) :return: vnEz or None if dim < 3 """ return None if self.dim < 3 else np.array([x for x in [self.nNx, self.nNy, self.nCz] if not x is None]) @property def vnFx(self): """ Number of x-faces in each direction :rtype: numpy.array (dim, ) :return: vnFx """ return np.array([x for x in [self.nNx, self.nCy, self.nCz] if not x is None]) @property def vnFy(self): """ Number of y-faces in each direction :rtype: numpy.array (dim, ) :return: vnFy or None if dim < 2 """ return None if self.dim < 2 else np.array([x for x in [self.nCx, self.nNy, self.nCz] if not x is None]) @property def vnFz(self): """ Number of z-faces in each direction :rtype: numpy.array (dim, ) :return: vnFz or None if dim < 3 """ return None if self.dim < 3 else np.array([x for x in [self.nCx, self.nCy, self.nNz] if not x is None]) ################################## # Redo the numbering so they are dependent of the vector numbers ################################## @property def nC(self): """ Total number of cells :rtype: int :return: nC """ return self.vnC.prod() @property def nN(self): """ Total number of nodes :rtype: int :return: nN """ return self.vnN.prod() @property def nEx(self): """ Number of x-edges :rtype: int :return: nEx """ return self.vnEx.prod() @property def nEy(self): """ Number of y-edges :rtype: int :return: nEy """ if self.dim < 2: return return self.vnEy.prod() @property def nEz(self): """ Number of z-edges :rtype: int :return: nEz """ if self.dim < 3: return return self.vnEz.prod() @property def nFx(self): """ Number of x-faces :rtype: int :return: nFx """ return self.vnFx.prod() @property def nFy(self): """ Number of y-faces :rtype: int :return: nFy """ if self.dim < 2: return return self.vnFy.prod() @property def nFz(self): """ Number of z-faces :rtype: int :return: nFz """ if self.dim < 3: return return self.vnFz.prod() def r(self, x, xType='CC', outType='CC', format='V'): """ Mesh.r is a quick reshape command that will do the best it can at giving you what you want. For example, you have a face variable, and you want the x component of it reshaped to a 3D matrix. Mesh.r can fulfil your dreams:: mesh.r(V, 'F', 'Fx', 'M') | | | { How: 'M' or ['V'] for a matrix (ndgrid style) or a vector (n x dim) } | | { What you want: ['CC'], 'N', 'F', 'Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', or 'Ez' } | { What is it: ['CC'], 'N', 'F', 'Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', or 'Ez' } { The input: as a list or ndarray } For example:: Xex, Yex, Zex = r(mesh.gridEx, 'Ex', 'Ex', 'M') # Separates each component of the Ex grid into 3 matrices XedgeVector = r(edgeVector, 'E', 'Ex', 'V') # Given an edge vector, this will return just the part on the x edges as a vector eX, eY, eZ = r(edgeVector, 'E', 'E', 'V') # Separates each component of the edgeVector into 3 vectors """ assert (type(x) == list or isinstance(x, np.ndarray)), "x must be either a list or a ndarray" assert xType in ['CC', 'N', 'F', 'Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', 'Ez'], "xType must be either 'CC', 'N', 'F', 'Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', or 'Ez'" assert outType in ['CC', 'N', 'F', 'Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', 'Ez'], "outType must be either 'CC', 'N', 'F', Fx', 'Fy', 'Fz', 'E', 'Ex', 'Ey', or 'Ez'" assert format in ['M', 'V'], "format must be either 'M' or 'V'" assert outType[:len(xType)] == xType, "You cannot change types when reshaping." assert xType in outType, 'You cannot change type of components.' if type(x) == list: for i, xi in enumerate(x): assert isinstance(x, np.ndarray), "x[%i] must be a numpy array" % i assert xi.size == x[0].size, "Number of elements in list must not change." x_array = np.ones((x.size, len(x))) # Unwrap it and put it in a np array for i, xi in enumerate(x): x_array[:, i] = Utils.mkvc(xi) x = x_array assert isinstance(x, np.ndarray), "x must be a numpy array" x = x[:] # make a copy. xTypeIsFExyz = len(xType) > 1 and xType[0] in ['F', 'E'] and xType[1] in ['x', 'y', 'z'] def outKernal(xx, nn): """Returns xx as either a matrix (shape == nn) or a vector.""" if format == 'M': return xx.reshape(nn, order='F') elif format == 'V': return Utils.mkvc(xx) def switchKernal(xx): """Switches over the different options.""" if xType in ['CC', 'N']: nn = (self._n) if xType == 'CC' else (self._n+1) assert xx.size == np.prod(nn), "Number of elements must not change." return outKernal(xx, nn) elif xType in ['F', 'E']: # This will only deal with components of fields, not full 'F' or 'E' xx = Utils.mkvc(xx) # unwrap it in case it is a matrix nn = self.vnF if xType == 'F' else self.vnE nn = np.r_[0, nn] nx = [0, 0, 0] nx[0] = self.vnFx if xType == 'F' else self.vnEx nx[1] = self.vnFy if xType == 'F' else self.vnEy nx[2] = self.vnFz if xType == 'F' else self.vnEz for dim, dimName in enumerate(['x', 'y', 'z']): if dimName in outType: assert self.dim > dim, ("Dimensions of mesh not great enough for %s%s", (xType, dimName)) assert xx.size == np.sum(nn), 'Vector is not the right size.' start = np.sum(nn[:dim+1]) end = np.sum(nn[:dim+2]) return outKernal(xx[start:end], nx[dim]) elif xTypeIsFExyz: # This will deal with partial components (x, y or z) lying on edges or faces if 'x' in xType: nn = self.vnFx if 'F' in xType else self.vnEx elif 'y' in xType: nn = self.vnFy if 'F' in xType else self.vnEy elif 'z' in xType: nn = self.vnFz if 'F' in xType else self.vnEz assert xx.size == np.prod(nn), 'Vector is not the right size.' return outKernal(xx, nn) # Check if we are dealing with a vector quantity isVectorQuantity = len(x.shape) == 2 and x.shape[1] == self.dim if outType in ['F', 'E']: assert ~isVectorQuantity, 'Not sure what to do with a vector vector quantity..' outTypeCopy = outType out = () for ii, dirName in enumerate(['x', 'y', 'z'][:self.dim]): outType = outTypeCopy + dirName out += (switchKernal(x),) return out elif isVectorQuantity: out = () for ii in range(x.shape[1]): out += (switchKernal(x[:, ii]),) return out else: return switchKernal(x)
szymanskirafal/tryread
tryread/books/migrations/0011_auto_20180613_1914.py
# Generated by Django 2.0.5 on 2018-06-13 19:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0010_auto_20180611_2122'), ] operations = [ migrations.RemoveField( model_name='dialog', name='chapter', ), migrations.DeleteModel( name='Dialog', ), ]
nrg12/VOOGASalad
src/structures/data/actions/move/CapSpeed.java
<gh_stars>0 package structures.data.actions.move; import structures.data.DataAction; import structures.data.actions.params.DoubleParam; public class CapSpeed extends DataAction { public CapSpeed() { init(new DoubleParam("Speed")); } @Override public String getTitle() { return "Cap Max Speed"; } @Override public String getDescription() { return String.format("Cap max speed to %s", get("Speed").getValue()); } @Override protected String getSyntax() { return "double max = %f; \n if (current().getVelocity().length() > max) {\ncurrent().setVelocity(current().getVelocity().setLength(max));\n}\n"; } }
thanexor/badmoviesquad
app/constants.js
export const TMDB_URL = 'https://www.themoviedb.org/'; export const MOVIE_URL = `${TMDB_URL}/movie`; // TODO: migrate all colors here export const COLORS = { white: 'hsl(0, 0%, 100%)', black: 'hsl(0, 0%, 0%)', gray: { 100: 'rgb(250, 250, 250)', 200: 'rgb(228, 228, 228)', 300: 'rgb(206, 206, 206)', 400: 'rgb(185, 184, 184)', 500: 'rgb(162, 162, 162)', 600: 'rgb(140, 140, 140)', 700: 'rgb(118, 118, 118)', 800: 'rgb(92, 92, 92)', 900: 'rgb(65, 65, 65)', 1000: 'rgb(15, 15, 15)', }, primary: '#FF00E2', primaryDark: '#B2009E', secondary: '#45FF00', secondaryDark: '#40A819', neutral: '#6BB251', purpleDark: '#260850', purpleSuperdark: '#12081f', purpleSuperdarkTransparent: 'hsla(265, 80%, 8%, 0.5)', pinkHot: 'hsl(340, 85%, 60%)', pinkHotter: 'hsl(340, 76%, 47%)', limeGreem: 'hsl(77, 100%, 59%)', limeGreemDark: 'hsl(77, 65%, 46%)', }; export const WEIGHTS = { 400: '400', 500: '500', 600: '600', 700: '700', 800: '800', 900: '900', };
stanolacko/JCloisterZone
src/main/java/com/jcloisterzone/board/TileSymmetry.java
package com.jcloisterzone.board; /** * Enumerates the symmetry conditions of a tile. */ public enum TileSymmetry { /** * No symmetry */ NONE, /** * Opposite edges are equal */ S2, /** * All edges are equal */ S4 }
krevelen/rivm-vacsim
java/episim-model/src/main/java/nl/rivm/cib/episim/model/vaccine/Vaccine.java
package nl.rivm.cib.episim.model.vaccine; import java.util.Collection; import java.util.Collections; import javax.measure.quantity.Dimensionless; import io.coala.enterprise.Actor; import io.coala.random.ProbabilityDistribution; import io.coala.random.QuantityDistribution; import io.coala.time.Proactive; import io.coala.time.Scheduler; import nl.rivm.cib.episim.model.disease.Condition; import nl.rivm.cib.episim.model.disease.infection.Pathogen; /** * {@link Vaccine}s trigger the immune system to protect against some * {@link Pathogen} * * @version $Id: cd03d05927307bcf1c67cba9943f563d29363423 $ * @author <NAME> */ public interface Vaccine extends Proactive { Collection<Pathogen> getTargets(); /** * @param condition the {@link Condition} to improve * @return a {@link ProbabilityDistribution} of the <em>actual</em> efficacy * for specified {@link Individual} 's traits (age, sex, &hellip;) */ ProbabilityDistribution<Boolean> getEfficacy( Condition condition ); /** * @param person the {@link Individual} to vaccinate * @return a {@link ProbabilityDistribution} of the <em>actual</em> delivery * method comfort (e.g. intravenous, needle-free patch, inhaled, * oral, micro-needle arrays, stratum corneum disruption) for * specified {@link Individual}'s traits (age, sex, &hellip;) */ QuantityDistribution<Dimensionless> getComfort( Actor.ID person ); /** * {@link Simple} implementation of {@link Vaccine} * * @version $Id: cd03d05927307bcf1c67cba9943f563d29363423 $ * @author <NAME> */ class Simple implements Vaccine { /** * @param scheduler the {@link Scheduler} * @param target the target {@link Pathogen} * @param efficacy <em>actual</em> efficacy distribution for everyone * @param comfort <em>actual</em> delivery method comfort distribution * for everyone * @return a {@link Simple} instance of {@link Vaccine} */ public static Simple of( final Scheduler scheduler, final Pathogen target, final ProbabilityDistribution<Boolean> efficacy, final QuantityDistribution<Dimensionless> comfort ) { return new Simple( scheduler, Collections.singleton( target ), efficacy, comfort ); } private final Scheduler scheduler; private final Collection<Pathogen> targets; private final ProbabilityDistribution<Boolean> efficacy; private final QuantityDistribution<Dimensionless> comfort; /** * {@link Simple} constructor * * @param scheduler the {@link Scheduler} * @param targets the target {@link Pathogen}s */ public Simple( final Scheduler scheduler, final Collection<Pathogen> targets, final ProbabilityDistribution<Boolean> efficacy, final QuantityDistribution<Dimensionless> comfort ) { this.scheduler = scheduler; this.targets = targets; this.efficacy = efficacy; this.comfort = comfort; } @Override public Scheduler scheduler() { return this.scheduler; } @Override public Collection<Pathogen> getTargets() { return this.targets; } @Override public ProbabilityDistribution<Boolean> getEfficacy( final Condition condition ) { return this.efficacy; } @Override public QuantityDistribution<Dimensionless> getComfort( final Actor.ID person ) { return this.comfort; } } }
maciej-barczak-red/pxCore
remote/rtRemoteMapper.h
<gh_stars>0 #ifndef __RT_REMOTE_ENDPOINT_MAPPER_H__ #define __RT_REMOTE_ENDPOINT_MAPPER_H__ #include "rtRemoteEndpoint.h" #include "rtError.h" #include <string> class rtRemoteEnvironment; class rtRemoteIMapper { public: virtual ~rtRemoteIMapper() { } public: virtual rtError registerEndpoint(std::string const& objectId, rtRemoteEndpointPtr const& endpoint) = 0; virtual rtError deregisterEndpoint(std::string const& objectId) = 0; virtual rtError lookupEndpoint(std::string const& objectId, rtRemoteEndpointPtr& endpoint) = 0; virtual bool isRegistered(std::string const& objectId) = 0; protected: rtRemoteIMapper(rtRemoteEnvironment* env) : m_env(env) { } protected: rtRemoteEnvironment* m_env; }; #endif
VenusProtocol/venus-protocol-docs
src/components/Docs/VenusJS/Introduction.js
import React from 'react'; import styled from 'styled-components'; import Label from 'components/Basic/Label'; import Description from 'components/Basic/Description'; const GovernorAlphaWrapper = styled.div` margin-bottom: 50px; `; function GovernorAlpha() { return ( <GovernorAlphaWrapper id="venusJS-introduction"> <Label title marginBottom> Introduction </Label> <Description> Venus.js is a JavaScript SDK for Binance Smart Chain and the Venus Protocol. It wraps around Ethers.js, which is its only dependency. It is designed for both the web browser and Node.js. </Description> <Description> The SDK is currently in open beta. For bugs reports and feature requests, either create an issue in the GitHub repository or send a message in the Development channel of the Venus Telegram. </Description> </GovernorAlphaWrapper> ); } export default GovernorAlpha;
McSources/LeetCode
src/main/java/leetcode/Test.java
<gh_stars>0 package leetcode; /** * @author machao * @date 2021/6/27 */ public class Test { public static void main(String[] args) { } }
netflix-tianbin/skywalking-study
apm-protocol/apm-network/target/generated-sources/protobuf/java/org/apache/skywalking/apm/network/register/v2/ServiceAndNetworkAddressMapping.java
<filename>apm-protocol/apm-network/target/generated-sources/protobuf/java/org/apache/skywalking/apm/network/register/v2/ServiceAndNetworkAddressMapping.java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: register/Register.proto package org.apache.skywalking.apm.network.register.v2; /** * Protobuf type {@code ServiceAndNetworkAddressMapping} */ public final class ServiceAndNetworkAddressMapping extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:ServiceAndNetworkAddressMapping) ServiceAndNetworkAddressMappingOrBuilder { // Use ServiceAndNetworkAddressMapping.newBuilder() to construct. private ServiceAndNetworkAddressMapping(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ServiceAndNetworkAddressMapping() { serviceId_ = 0; serviceInstanceId_ = 0; networkAddress_ = ""; networkAddressId_ = 0; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private ServiceAndNetworkAddressMapping( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!input.skipField(tag)) { done = true; } break; } case 8: { serviceId_ = input.readInt32(); break; } case 16: { serviceInstanceId_ = input.readInt32(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); networkAddress_ = s; break; } case 32: { networkAddressId_ = input.readInt32(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.skywalking.apm.network.register.v2.RegisterOuterClass.internal_static_ServiceAndNetworkAddressMapping_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.skywalking.apm.network.register.v2.RegisterOuterClass.internal_static_ServiceAndNetworkAddressMapping_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.class, org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.Builder.class); } public static final int SERVICEID_FIELD_NUMBER = 1; private int serviceId_; /** * <code>int32 serviceId = 1;</code> */ public int getServiceId() { return serviceId_; } public static final int SERVICEINSTANCEID_FIELD_NUMBER = 2; private int serviceInstanceId_; /** * <code>int32 serviceInstanceId = 2;</code> */ public int getServiceInstanceId() { return serviceInstanceId_; } public static final int NETWORKADDRESS_FIELD_NUMBER = 3; private volatile java.lang.Object networkAddress_; /** * <code>string networkAddress = 3;</code> */ public java.lang.String getNetworkAddress() { java.lang.Object ref = networkAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkAddress_ = s; return s; } } /** * <code>string networkAddress = 3;</code> */ public com.google.protobuf.ByteString getNetworkAddressBytes() { java.lang.Object ref = networkAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NETWORKADDRESSID_FIELD_NUMBER = 4; private int networkAddressId_; /** * <code>int32 networkAddressId = 4;</code> */ public int getNetworkAddressId() { return networkAddressId_; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (serviceId_ != 0) { output.writeInt32(1, serviceId_); } if (serviceInstanceId_ != 0) { output.writeInt32(2, serviceInstanceId_); } if (!getNetworkAddressBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, networkAddress_); } if (networkAddressId_ != 0) { output.writeInt32(4, networkAddressId_); } } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (serviceId_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, serviceId_); } if (serviceInstanceId_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, serviceInstanceId_); } if (!getNetworkAddressBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, networkAddress_); } if (networkAddressId_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(4, networkAddressId_); } memoizedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping)) { return super.equals(obj); } org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping other = (org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping) obj; boolean result = true; result = result && (getServiceId() == other.getServiceId()); result = result && (getServiceInstanceId() == other.getServiceInstanceId()); result = result && getNetworkAddress() .equals(other.getNetworkAddress()); result = result && (getNetworkAddressId() == other.getNetworkAddressId()); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICEID_FIELD_NUMBER; hash = (53 * hash) + getServiceId(); hash = (37 * hash) + SERVICEINSTANCEID_FIELD_NUMBER; hash = (53 * hash) + getServiceInstanceId(); hash = (37 * hash) + NETWORKADDRESS_FIELD_NUMBER; hash = (53 * hash) + getNetworkAddress().hashCode(); hash = (37 * hash) + NETWORKADDRESSID_FIELD_NUMBER; hash = (53 * hash) + getNetworkAddressId(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code ServiceAndNetworkAddressMapping} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:ServiceAndNetworkAddressMapping) org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMappingOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.skywalking.apm.network.register.v2.RegisterOuterClass.internal_static_ServiceAndNetworkAddressMapping_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.skywalking.apm.network.register.v2.RegisterOuterClass.internal_static_ServiceAndNetworkAddressMapping_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.class, org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.Builder.class); } // Construct using org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); serviceId_ = 0; serviceInstanceId_ = 0; networkAddress_ = ""; networkAddressId_ = 0; return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.skywalking.apm.network.register.v2.RegisterOuterClass.internal_static_ServiceAndNetworkAddressMapping_descriptor; } public org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping getDefaultInstanceForType() { return org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.getDefaultInstance(); } public org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping build() { org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping buildPartial() { org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping result = new org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping(this); result.serviceId_ = serviceId_; result.serviceInstanceId_ = serviceInstanceId_; result.networkAddress_ = networkAddress_; result.networkAddressId_ = networkAddressId_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping) { return mergeFrom((org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping other) { if (other == org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping.getDefaultInstance()) return this; if (other.getServiceId() != 0) { setServiceId(other.getServiceId()); } if (other.getServiceInstanceId() != 0) { setServiceInstanceId(other.getServiceInstanceId()); } if (!other.getNetworkAddress().isEmpty()) { networkAddress_ = other.networkAddress_; onChanged(); } if (other.getNetworkAddressId() != 0) { setNetworkAddressId(other.getNetworkAddressId()); } onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int serviceId_ ; /** * <code>int32 serviceId = 1;</code> */ public int getServiceId() { return serviceId_; } /** * <code>int32 serviceId = 1;</code> */ public Builder setServiceId(int value) { serviceId_ = value; onChanged(); return this; } /** * <code>int32 serviceId = 1;</code> */ public Builder clearServiceId() { serviceId_ = 0; onChanged(); return this; } private int serviceInstanceId_ ; /** * <code>int32 serviceInstanceId = 2;</code> */ public int getServiceInstanceId() { return serviceInstanceId_; } /** * <code>int32 serviceInstanceId = 2;</code> */ public Builder setServiceInstanceId(int value) { serviceInstanceId_ = value; onChanged(); return this; } /** * <code>int32 serviceInstanceId = 2;</code> */ public Builder clearServiceInstanceId() { serviceInstanceId_ = 0; onChanged(); return this; } private java.lang.Object networkAddress_ = ""; /** * <code>string networkAddress = 3;</code> */ public java.lang.String getNetworkAddress() { java.lang.Object ref = networkAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); networkAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string networkAddress = 3;</code> */ public com.google.protobuf.ByteString getNetworkAddressBytes() { java.lang.Object ref = networkAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); networkAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string networkAddress = 3;</code> */ public Builder setNetworkAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } networkAddress_ = value; onChanged(); return this; } /** * <code>string networkAddress = 3;</code> */ public Builder clearNetworkAddress() { networkAddress_ = getDefaultInstance().getNetworkAddress(); onChanged(); return this; } /** * <code>string networkAddress = 3;</code> */ public Builder setNetworkAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); networkAddress_ = value; onChanged(); return this; } private int networkAddressId_ ; /** * <code>int32 networkAddressId = 4;</code> */ public int getNetworkAddressId() { return networkAddressId_; } /** * <code>int32 networkAddressId = 4;</code> */ public Builder setNetworkAddressId(int value) { networkAddressId_ = value; onChanged(); return this; } /** * <code>int32 networkAddressId = 4;</code> */ public Builder clearNetworkAddressId() { networkAddressId_ = 0; onChanged(); return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; } // @@protoc_insertion_point(builder_scope:ServiceAndNetworkAddressMapping) } // @@protoc_insertion_point(class_scope:ServiceAndNetworkAddressMapping) private static final org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping(); } public static org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ServiceAndNetworkAddressMapping> PARSER = new com.google.protobuf.AbstractParser<ServiceAndNetworkAddressMapping>() { public ServiceAndNetworkAddressMapping parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ServiceAndNetworkAddressMapping(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ServiceAndNetworkAddressMapping> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ServiceAndNetworkAddressMapping> getParserForType() { return PARSER; } public org.apache.skywalking.apm.network.register.v2.ServiceAndNetworkAddressMapping getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
tomasz-herman/GModeling
src/main/java/pl/edu/pw/mini/mg1/graphics/Shader.java
<reponame>tomasz-herman/GModeling package pl.edu.pw.mini.mg1.graphics; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.GL4; import com.jogamp.opengl.util.GLBuffers; import org.joml.Matrix4fc; import org.joml.Vector3fc; import pl.edu.pw.mini.mg1.utils.IOUtils; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; public class Shader { private final int programID; public Shader(GL4 gl, String vertexShaderPath, String fragmentShaderPath) { List<Integer> shaderList = new ArrayList<>(); shaderList.add(createShader(gl, GL4.GL_VERTEX_SHADER, IOUtils.readResource(vertexShaderPath))); shaderList.add(createShader(gl, GL4.GL_FRAGMENT_SHADER, IOUtils.readResource(fragmentShaderPath))); programID = createProgram(gl, shaderList); shaderList.forEach(gl::glDeleteShader); } public Shader(GL4 gl, String vertexShaderPath, String fragmentShaderPath, String geometryShaderPath) { List<Integer> shaderList = new ArrayList<>(); shaderList.add(createShader(gl, GL4.GL_VERTEX_SHADER, IOUtils.readResource(vertexShaderPath))); shaderList.add(createShader(gl, GL4.GL_FRAGMENT_SHADER, IOUtils.readResource(fragmentShaderPath))); shaderList.add(createShader(gl, GL4.GL_GEOMETRY_SHADER, IOUtils.readResource(geometryShaderPath))); programID = createProgram(gl, shaderList); shaderList.forEach(gl::glDeleteShader); } public Shader(GL4 gl, String vertexShaderPath, String fragmentShaderPath, String tesselationControlShader, String tesselationEvaluationShader) { List<Integer> shaderList = new ArrayList<>(); shaderList.add(createShader(gl, GL4.GL_VERTEX_SHADER, IOUtils.readResource(vertexShaderPath))); shaderList.add(createShader(gl, GL4.GL_FRAGMENT_SHADER, IOUtils.readResource(fragmentShaderPath))); shaderList.add(createShader(gl, GL4.GL_TESS_CONTROL_SHADER, IOUtils.readResource(tesselationControlShader))); shaderList.add(createShader(gl, GL4.GL_TESS_EVALUATION_SHADER, IOUtils.readResource(tesselationEvaluationShader))); programID = createProgram(gl, shaderList); shaderList.forEach(gl::glDeleteShader); } public Shader(GL4 gl, String vertexShaderPath, String fragmentShaderPath, String tesselationControlShader, String tesselationEvaluationShader, String geometryShader) { List<Integer> shaderList = new ArrayList<>(); shaderList.add(createShader(gl, GL4.GL_VERTEX_SHADER, IOUtils.readResource(vertexShaderPath))); shaderList.add(createShader(gl, GL4.GL_FRAGMENT_SHADER, IOUtils.readResource(fragmentShaderPath))); shaderList.add(createShader(gl, GL4.GL_TESS_CONTROL_SHADER, IOUtils.readResource(tesselationControlShader))); shaderList.add(createShader(gl, GL4.GL_TESS_EVALUATION_SHADER, IOUtils.readResource(tesselationEvaluationShader))); shaderList.add(createShader(gl, GL4.GL_GEOMETRY_SHADER, IOUtils.readResource(geometryShader))); programID = createProgram(gl, shaderList); shaderList.forEach(gl::glDeleteShader); } public void loadInteger(GL4 gl, String name, int value) { int location = gl.glGetUniformLocation(programID, name); gl.glUniform1i(location, value); } public void loadFloat(GL4 gl, String name, float value) { int location = gl.glGetUniformLocation(programID, name); gl.glUniform1f(location, value); } public void loadVector3f(GL4 gl, String name, Vector3fc vector) { int location = gl.glGetUniformLocation(programID, name); gl.glUniform3f(location, vector.x(), vector.y(), vector.z()); } public void loadMatrix4f(GL4 gl, String name, Matrix4fc matrix) { int location = gl.glGetUniformLocation(programID, name); gl.glUniformMatrix4fv(location, 1, false, matrix.get(Buffers.newDirectFloatBuffer(16))); } private int createProgram(GL4 gl, List<Integer> shaderList) { int program = gl.glCreateProgram(); shaderList.forEach(shader -> gl.glAttachShader(program, shader)); gl.glLinkProgram(program); IntBuffer status = GLBuffers.newDirectIntBuffer(1); gl.glGetProgramiv(program, GL4.GL_LINK_STATUS, status); if (status.get(0) == GL4.GL_FALSE) { IntBuffer infoLogLength = GLBuffers.newDirectIntBuffer(1); gl.glGetProgramiv(program, GL4.GL_INFO_LOG_LENGTH, infoLogLength); ByteBuffer bufferInfoLog = GLBuffers.newDirectByteBuffer(infoLogLength.get(0)); gl.glGetProgramInfoLog(program, infoLogLength.get(0), null, bufferInfoLog); byte[] bytes = new byte[infoLogLength.get(0)]; bufferInfoLog.get(bytes); String strInfoLog = new String(bytes); System.err.println("Linker failure: " + strInfoLog); } shaderList.forEach(shader -> gl.glDetachShader(program, shader)); return program; } private int createShader(GL4 gl, int shaderType, String shaderFile) { int shader = gl.glCreateShader(shaderType); String[] lines = {shaderFile}; IntBuffer length = GLBuffers.newDirectIntBuffer(new int[]{lines[0].length()}); gl.glShaderSource(shader, 1, lines, length); gl.glCompileShader(shader); IntBuffer status = GLBuffers.newDirectIntBuffer(1); gl.glGetShaderiv(shader, GL4.GL_COMPILE_STATUS, status); if (status.get(0) == GL4.GL_FALSE) { IntBuffer infoLogLength = GLBuffers.newDirectIntBuffer(1); gl.glGetShaderiv(shader, GL4.GL_INFO_LOG_LENGTH, infoLogLength); ByteBuffer bufferInfoLog = GLBuffers.newDirectByteBuffer(infoLogLength.get(0)); gl.glGetShaderInfoLog(shader, infoLogLength.get(0), null, bufferInfoLog); byte[] bytes = new byte[infoLogLength.get(0)]; bufferInfoLog.get(bytes); String strInfoLog = new String(bytes); String strShaderType = switch (shaderType) { case GL4.GL_VERTEX_SHADER -> "vertex"; case GL4.GL_GEOMETRY_SHADER -> "geometry"; case GL4.GL_FRAGMENT_SHADER -> "fragment"; case GL4.GL_TESS_CONTROL_SHADER -> "control"; case GL4.GL_TESS_EVALUATION_SHADER -> "evaluation"; default -> ""; }; System.err.println("Compiler failure in " + strShaderType + " shader: " + strInfoLog); } return shader; } public int getProgramID() { return programID; } public void dispose(GL4 gl) { gl.glDeleteProgram(programID); } }
sm2774us/amazon_interview_prep_2021
solutions/python3/587.py
# http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull.py class Solution(object): def outerTrees(self, points): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. Implements Andrew's monotone chain algorithm. O(n log n) complexity. """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. # points = sorted(set(points)) points = sorted(points, key=lambda p: (p.x, p.y)) # Boring case: no points or a single point, possibly repeated multiple times. if len(points) <= 1: return points # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. # Returns a positive value, if OAB makes a counter-clockwise turn, # negative for clockwise turn, and zero if the points are collinear. def cross(o, a, b): # return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) # Build lower hull lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(points): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the # beginning of the other list. # return lower[:-1] + upper[:-1] return list(set(lower[:-1] + upper[:-1]))
peterdonnelly1/u24_lymphocyte
archive/lym_pipeline/prediction/color_stats.py
import sys import os import numpy as np import time from PIL import Image APS = 100; TileFolder = sys.argv[1] + '/'; heat_map_out = 'patch-level-color.txt'; def whiteness(png): wh = (np.std(png[:,:,0].flatten()) + np.std(png[:,:,1].flatten()) + np.std(png[:,:,2].flatten())) / 3.0; return wh; def blackness(png): bk = np.mean(png); return bk; def redness(png): rd = np.mean((png[:,:,0] >= 190) * (png[:,:,1] <= 100) * (png[:,:,2] <= 100)); return rd; def load_data(): X = np.zeros(shape=(1000000, 3), dtype=np.float32); coor = np.zeros(shape=(1000000, 2), dtype=np.int32); ind = 0; for fn in os.listdir(TileFolder): full_fn = TileFolder + '/' + fn; if not os.path.isfile(full_fn): continue; if len(fn.split('_')) < 4: continue; x_off = float(fn.split('_')[0]); y_off = float(fn.split('_')[1]); svs_pw = float(fn.split('_')[2]); png_pw = float(fn.split('_')[3].split('.png')[0]); png = np.array(Image.open(full_fn).convert('RGB')); for x in range(0, png.shape[1], APS): if x + APS > png.shape[1]: continue; for y in range(0, png.shape[0], APS): if y + APS > png.shape[0]: continue; X[ind, 0] = whiteness(png[y:y+APS, x:x+APS, :]); X[ind, 1] = blackness(png[y:y+APS, x:x+APS, :]); X[ind, 2] = redness(png[y:y+APS, x:x+APS, :]); coor[ind, 0] = np.int32(x_off + (x + APS/2) * svs_pw / png_pw); coor[ind, 1] = np.int32(y_off + (y + APS/2) * svs_pw / png_pw); ind += 1; X = X[0:ind]; coor = coor[0:ind]; return X, coor; def split_validation(): Wh, coor = load_data(); fid = open(TileFolder + '/' + heat_map_out, 'w'); for idx in range(0, Wh.shape[0]): fid.write('{} {} {} {} {}\n'.format(coor[idx][0], coor[idx][1], Wh[idx][0], Wh[idx][1], Wh[idx][2])); fid.close(); def main(): split_validation(); if __name__ == "__main__": main();
shhan3927/Study
CCI/3-4/main.cpp
#include <iostream> #include "Stack.h" using namespace std; class MyQueue { public: void Add(int data) { Stack<int> buffer; while(!stack.Empty()) { buffer.Push(stack.Pop()); } stack.Push(data); while(!buffer.Empty()) { stack.Push(buffer.Pop()); } } int Peek() { return stack.Top(); } void Remove() { stack.Pop(); } bool Empty() { return stack.Empty(); } private: Stack<int> stack; }; int main() { MyQueue queue; queue.Add(1); queue.Add(2); queue.Add(3); queue.Add(4); queue.Add(5); while(!queue.Empty()) { cout << queue.Peek() << endl; queue.Remove(); } return 0; }
nickbaum/st2
st2tests/integration/orquesta/base.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import os import retrying import shutil import six import tempfile import unittest2 from st2client import client as st2 from st2client import models from st2common.constants import action as action_constants LIVEACTION_LAUNCHED_STATUSES = [ action_constants.LIVEACTION_STATUS_REQUESTED, action_constants.LIVEACTION_STATUS_SCHEDULED, action_constants.LIVEACTION_STATUS_RUNNING ] def retry_on_exceptions(exc): return isinstance(exc, AssertionError) class WorkflowControlTestCaseMixin(object): def _create_temp_file(self): _, temp_file_path = tempfile.mkstemp() os.chmod(temp_file_path, 0o755) # nosec return temp_file_path def _delete_temp_file(self, temp_file_path): if temp_file_path and os.path.exists(temp_file_path): if os.path.isdir(temp_file_path): shutil.rmtree(temp_file_path) else: os.remove(temp_file_path) class TestWorkflowExecution(unittest2.TestCase): @classmethod def setUpClass(cls): cls.st2client = st2.Client(base_url='http://127.0.0.1') def _execute_workflow(self, action, parameters=None, execute_async=True, expected_status=None, expected_result=None): ex = models.LiveAction(action=action, parameters=(parameters or {})) ex = self.st2client.executions.create(ex) self.assertIsNotNone(ex.id) self.assertEqual(ex.action['ref'], action) self.assertIn(ex.status, LIVEACTION_LAUNCHED_STATUSES) if execute_async: return ex if expected_status is None: expected_status = action_constants.LIVEACTION_STATUS_SUCCEEDED self.assertIn(expected_status, action_constants.LIVEACTION_STATUSES) ex = self._wait_for_completion(ex) self.assertEqual(ex.status, expected_status) self.assertDictEqual(ex.result, expected_result) return ex @retrying.retry( retry_on_exception=retry_on_exceptions, wait_fixed=3000, stop_max_delay=900000) def _wait_for_state(self, ex, states): if isinstance(states, six.string_types): states = [states] for state in states: if state not in action_constants.LIVEACTION_STATUSES: raise ValueError('Status %s is not valid.' % state) try: ex = self.st2client.executions.get_by_id(ex.id) self.assertIn(ex.status, states) except: if ex.status in action_constants.LIVEACTION_COMPLETED_STATES: raise Exception( 'Execution is in completed state "%s" and ' 'does not match expected state(s). %s' % (ex.status, ex.result) ) else: raise return ex def _get_children(self, ex): return self.st2client.executions.query(parent=ex.id) @retrying.retry( retry_on_exception=retry_on_exceptions, wait_fixed=3000, stop_max_delay=900000) def _wait_for_task(self, ex, task, status=None, num_task_exs=1): ex = self.st2client.executions.get_by_id(ex.id) task_exs = [ task_ex for task_ex in self._get_children(ex) if task_ex.context.get('orquesta', {}).get('task_name', '') == task ] try: self.assertEqual(len(task_exs), num_task_exs) except: if ex.status in action_constants.LIVEACTION_COMPLETED_STATES: raise Exception( 'Execution is in completed state and does not ' 'match expected number of tasks.' ) else: raise if status is not None: try: self.assertTrue(all([task_ex.status == status for task_ex in task_exs])) except: if ex.status in action_constants.LIVEACTION_COMPLETED_STATES: raise Exception( 'Execution is in completed state and not all tasks ' 'match expected status "%s".' % status ) else: raise return task_exs @retrying.retry( retry_on_exception=retry_on_exceptions, wait_fixed=3000, stop_max_delay=900000) def _wait_for_completion(self, ex): ex = self._wait_for_state(ex, action_constants.LIVEACTION_COMPLETED_STATES) try: self.assertTrue(hasattr(ex, 'result')) except: if ex.status in action_constants.LIVEACTION_COMPLETED_STATES: raise Exception( 'Execution is in completed state and does not ' 'contain expected result.' ) else: raise return ex
markyangchangliang/framework
spring-cloud-framework/app/system/src/main/java/com/markyang/framework/app/system/repository/ExportFieldRepository.java
<gh_stars>1-10 package com.markyang.framework.app.system.repository; import com.markyang.framework.service.core.repository.FrameworkRepository; import com.markyang.framework.pojo.entity.system.ExportField; /** * 导出数据字段(ExportField)仓库类 * * @author yangchangliang * @version 1 * @date 2020-03-25 18:16:18 */ public interface ExportFieldRepository extends FrameworkRepository<ExportField> { }
dkuerner/sechub
sechub-developertools/src/main/java/com/daimler/sechub/developertools/admin/ConfigProvider.java
<gh_stars>0 // SPDX-License-Identifier: MIT package com.daimler.sechub.developertools.admin; public interface ConfigProvider { public String getApiToken(); public String getUser(); public String getServer(); public int getPort(); public void handleClientError(String statusText); }
CharLemAznable/eql
src/test/java/org/n3r/eql/impl/BooleanTest.java
package org.n3r.eql.impl; import org.junit.Test; import org.n3r.eql.Eql; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BooleanTest { @Test public void test() { new Eql("mysql").execute("drop table if exists eql_boolean"); new Eql("mysql").execute("create table eql_boolean(id tinyint(1) primary key, found tinyint(1) default 0)"); new Eql("mysql").params(true).execute("insert into eql_boolean values(1, ##)"); new Eql("mysql").params(false).execute("insert into eql_boolean values(0, ##)"); boolean found; found = new Eql("mysql").returnType(boolean.class).limit(1).execute("select found from eql_boolean where id = 1"); assertThat(found, is(true)); found = new Eql("mysql").returnType(boolean.class).limit(1).execute("select found from eql_boolean where id = 0"); assertThat(found, is(false)); found = new Eql("mysql").returnType(Boolean.class).limit(1).execute("select found from eql_boolean where id = 1"); assertThat(found, is(true)); found = new Eql("mysql").returnType(Boolean.class).limit(1).execute("select found from eql_boolean where id = 0"); assertThat(found, is(false)); BooleanObject booleanObject; booleanObject = new Eql("mysql").returnType(BooleanObject.class).limit(1).execute("select id, found from eql_boolean where id = 1"); assertThat(booleanObject.toString(), is(equalTo("{id=1, found=true}"))); booleanObject = new Eql("mysql").returnType(BooleanObject.class).limit(1).execute("select id, found from eql_boolean where id = 0"); assertThat(booleanObject.toString(), is(equalTo("{id=0, found=false}"))); List<BooleanObject> booleanObjects = new Eql("mysql").returnType(BooleanObject.class).execute("select id, found from eql_boolean order by id"); assertThat(booleanObjects.toString(), is(equalTo("[{id=0, found=false}, {id=1, found=true}]"))); BooleanObject2 booleanObject2; booleanObject2 = new Eql("mysql").returnType(BooleanObject2.class).limit(1).execute("select id, found from eql_boolean where id = 1"); assertThat(booleanObject2.toString(), is(equalTo("{id=1, found=true}"))); booleanObject2 = new Eql("mysql").returnType(BooleanObject2.class).limit(1).execute("select id, found from eql_boolean where id = 0"); assertThat(booleanObject2.toString(), is(equalTo("{id=0, found=false}"))); List<BooleanObject2> booleanObject2s = new Eql("mysql").returnType(BooleanObject2.class).execute("select id, found from eql_boolean order by id"); assertThat(booleanObject2s.toString(), is(equalTo("[{id=0, found=false}, {id=1, found=true}]"))); } public static class BooleanObject { private int id; private boolean found; public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isFound() { return found; } public void setFound(boolean found) { this.found = found; } @Override public String toString() { return "{" + "id=" + id + ", found=" + found + '}'; } } public static class BooleanObject2 { private int id; private Boolean found; public int getId() { return id; } public void setId(int id) { this.id = id; } public Boolean isFound() { return found; } public void setFound(Boolean found) { this.found = found; } @Override public String toString() { return "{" + "id=" + id + ", found=" + found + '}'; } } }
reality-scheveningen/reality-website
lib/sync/download-synced-assets.js
const _ = require('lodash') const path = require('path') const url = require('url') const download = require('download') module.exports = exports = function (e) { e.downloadedAssets = _.flatten( e.sync.assets.map(asset => { const items = [] _.forEach(asset.fields.file, file => { const localPath = url.parse('https:' + file.url).pathname items.push({ remotePath: 'https:' + file.url, localPath: localPath, targetFolder: e.config.assetPath + path.dirname(localPath), absolutePath: e.config.assetPath + localPath }) }) return items }) ) return Promise.all( e.downloadedAssets.map(asset => { return download( asset.remotePath, asset.targetFolder ) }) ).then(() => e) }
InjectiveLabs/injective-explorer-mintscan-backend
chain-exporter/exporter/block.go
<filename>chain-exporter/exporter/block.go package exporter import ( "github.com/InjectiveLabs/injective-explorer-mintscan-backend/chain-exporter/schema" sdk "github.com/cosmos/cosmos-sdk/types" tmctypes "github.com/tendermint/tendermint/rpc/core/types" ) // getBlock exports block information. func (ex *Exporter) getBlock(block *tmctypes.ResultBlock) (*schema.Block, error) { proposerAddr := sdk.ConsAddress(block.Block.ProposerAddress).String() b := schema.NewBlock(schema.Block{ Height: block.Block.Height, Proposer: proposerAddr, Moniker: ex.db.QueryValidatorMoniker(proposerAddr), BlockHash: block.BlockID.Hash.String(), ParentHash: block.Block.Header.LastBlockID.Hash.String(), NumPrecommits: int64(len(block.Block.LastCommit.Signatures)), NumTxs: int64(len(block.Block.Txs)), Timestamp: block.Block.Time, }) return b, nil }
sousaw/BTE-Barna
test/kappa_Tsweep_test.cpp
<reponame>sousaw/BTE-Barna<filename>test/kappa_Tsweep_test.cpp<gh_stars>1-10 // Copyright 2015-2020 The ALMA Project Developers // // 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. /// @file /// Verify that the kappa_Tsweep executable works correctly. #include <cstdlib> #include <iostream> #include <functional> #include <fstream> #include <string> #include <boost/filesystem.hpp> #include "gtest/gtest.h" #include <io_utils.hpp> #include <Eigen/Dense> #include <cmakevars.hpp> #include <utilities.hpp> #include <where_is_kappa_Tsweep.hpp> // Randomly-named directory to store the output of the program. std::string targetdir; class G_Environment : public ::testing::Environment { public: virtual ~G_Environment() { } virtual void SetUp() { std::string path_prefix( boost::filesystem::path(kappa_Tsweep).parent_path().string()); // BUILD XML INPUT FILE std::string xmlfilename = (boost::filesystem::path(path_prefix) / boost::filesystem::path("test_kappa_Tsweep.xml")) .string(); std::ofstream xmlwriter(xmlfilename); targetdir = (boost::filesystem::path("test_results") / boost::filesystem::unique_path("kappa_Tsweep_%%%%-%%%%-%%%%-%%%%")) .string(); xmlwriter << "<Tsweep>" << std::endl; xmlwriter << " <H5repository root_directory=\""; auto repository_root = boost::filesystem::path(TEST_RESOURCE_DIR); xmlwriter << repository_root.string() << "\"/>" << std::endl; xmlwriter << " <compound directory=\"Si\" base=\"Si\" gridA=\"12\" " "gridB=\"12\" gridC=\"12\"/>" << std::endl; xmlwriter << " <sweep type=\"lin\" start=\"300\" stop=\"500\" points=\"3\"/>" << std::endl; xmlwriter << " <transportAxis x=\"0\" y=\"0\" z=\"1\"/>" << std::endl; xmlwriter << " <fullBTE iterative=\"true\"/>" << std::endl; xmlwriter << " <outputHeatCapacity/>" << std::endl; xmlwriter << " <target directory=\"" << targetdir << "\" file=\"AUTO\"/>" << std::endl; xmlwriter << "</Tsweep>" << std::endl; xmlwriter.close(); // RUN EXECUTABLE std::string command = (boost::filesystem::path(path_prefix) / boost::filesystem::path("kappa_Tsweep")) .string() + " " + xmlfilename; ASSERT_EQ(std::system(command.c_str()), 0); } virtual void TearDown() { } }; TEST(kappa_Tsweep_case, kappa_Tsweep_test) { Eigen::MatrixXd data = alma::read_from_csv( (boost::filesystem::path(targetdir) / boost::filesystem::path("Si_12_12_12_0,0,1_300_500.Tsweep")) .string(), ',', 1); std::cout.precision(10); Eigen::IOFormat fmt(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", ", ", "", "", "", ";"); std::cout << "data =" << std::endl << data.format(fmt) << std::endl; Eigen::MatrixXd data_ref(3, 4); data_ref << 300, 135.282, 141.295, 1625830, 400, 97.9002, 102.868, 1782430, 500, 77.2684, 81.482, 1864400; for (int ncol = 0; ncol < 4; ncol++) { double residue = (data.col(ncol) - data_ref.col(ncol)).norm() / data_ref.col(ncol).norm(); EXPECT_TRUE(alma::almost_equal(residue, 0.0, 1e-3, 1e-3)); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(new G_Environment); return RUN_ALL_TESTS(); }
LSFLK/GIG-SDK
tests/client/get_entity_test.go
package client import ( "testing" ) func TestThatGetEntityWorks(t *testing.T) { result, err := testClient.GetEntity("<NAME>a") if err != nil { t.Errorf("match string for partially equal strings failed. %s == %s", result, "") } }
fniephaus/homebrew-cask
Casks/gyazo.rb
<reponame>fniephaus/homebrew-cask cask :v1 => 'gyazo' do version '2.0' sha256 '41242a421ee0c2b467ac0ff7fa1baa895c824e940bc5aee92a4ec2bf8e204eb3' url "https://gyazo.s3.amazonaws.com/setup/Gyazo_#{version}.dmg" homepage 'https://gyazo.com/' license :unknown app 'Gyazo.app' app 'Gyazo GIF.app' end
DamieFC/chromium
extensions/common/user_script.h
// Copyright 2013 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 EXTENSIONS_COMMON_USER_SCRIPT_H_ #define EXTENSIONS_COMMON_USER_SCRIPT_H_ #include <memory> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/strings/string_piece.h" #include "extensions/common/mojom/host_id.mojom.h" #include "extensions/common/mojom/run_location.mojom-shared.h" #include "extensions/common/script_constants.h" #include "extensions/common/url_pattern.h" #include "extensions/common/url_pattern_set.h" #include "url/gurl.h" namespace base { class Pickle; class PickleIterator; } namespace extensions { // Represents a user script, either a standalone one, or one that is part of an // extension. class UserScript { public: // The file extension for standalone user scripts. static const char kFileExtension[]; static std::string GenerateUserScriptID(); // Check if a URL should be treated as a user script and converted to an // extension. static bool IsURLUserScript(const GURL& url, const std::string& mime_type); // Get the valid user script schemes for the current process. If // canExecuteScriptEverywhere is true, this will return ALL_SCHEMES. static int ValidUserScriptSchemes(bool canExecuteScriptEverywhere = false); // Holds script file info. class File { public: File(const base::FilePath& extension_root, const base::FilePath& relative_path, const GURL& url); File(); File(const File& other); ~File(); const base::FilePath& extension_root() const { return extension_root_; } const base::FilePath& relative_path() const { return relative_path_; } const GURL& url() const { return url_; } void set_url(const GURL& url) { url_ = url; } // If external_content_ is set returns it as content otherwise it returns // content_ const base::StringPiece GetContent() const { if (external_content_.data()) return external_content_; else return content_; } void set_external_content(const base::StringPiece& content) { external_content_ = content; } void set_content(const base::StringPiece& content) { content_.assign(content.begin(), content.end()); } // Serialization support. The content and FilePath members will not be // serialized! void Pickle(base::Pickle* pickle) const; void Unpickle(const base::Pickle& pickle, base::PickleIterator* iter); private: // Where the script file lives on the disk. We keep the path split so that // it can be localized at will. base::FilePath extension_root_; base::FilePath relative_path_; // The url to this script file. GURL url_; // The script content. It can be set to either loaded_content_ or // externally allocated string. base::StringPiece external_content_; // Set when the content is loaded by LoadContent std::string content_; }; using FileList = std::vector<std::unique_ptr<File>>; // Type of a API consumer instance that user scripts will be injected on. enum ConsumerInstanceType { TAB, WEBVIEW }; // Constructor. Default the run location to document end, which is like // Greasemonkey and probably more useful for typical scripts. UserScript(); ~UserScript(); // Performs a copy of all fields except file contents. static std::unique_ptr<UserScript> CopyMetadataFrom(const UserScript& other); const std::string& name_space() const { return name_space_; } void set_name_space(const std::string& name_space) { name_space_ = name_space; } const std::string& name() const { return name_; } void set_name(const std::string& name) { name_ = name; } const std::string& version() const { return version_; } void set_version(const std::string& version) { version_ = version; } const std::string& description() const { return description_; } void set_description(const std::string& description) { description_ = description; } // The place in the document to run the script. mojom::RunLocation run_location() const { return run_location_; } void set_run_location(mojom::RunLocation location) { run_location_ = location; } // Whether to emulate greasemonkey when running this script. bool emulate_greasemonkey() const { return emulate_greasemonkey_; } void set_emulate_greasemonkey(bool val) { emulate_greasemonkey_ = val; } // Whether to match all frames, or only the top one. bool match_all_frames() const { return match_all_frames_; } void set_match_all_frames(bool val) { match_all_frames_ = val; } // Whether to match the origin as a fallback if the URL cannot be used // directly. MatchOriginAsFallbackBehavior match_origin_as_fallback() const { return match_origin_as_fallback_; } void set_match_origin_as_fallback(MatchOriginAsFallbackBehavior val) { match_origin_as_fallback_ = val; } // The globs, if any, that determine which pages this script runs against. // These are only used with "standalone" Greasemonkey-like user scripts. const std::vector<std::string>& globs() const { return globs_; } void add_glob(const std::string& glob) { globs_.push_back(glob); } void clear_globs() { globs_.clear(); } const std::vector<std::string>& exclude_globs() const { return exclude_globs_; } void add_exclude_glob(const std::string& glob) { exclude_globs_.push_back(glob); } void clear_exclude_globs() { exclude_globs_.clear(); } // The URLPatterns, if any, that determine which pages this script runs // against. const URLPatternSet& url_patterns() const { return url_set_; } void add_url_pattern(const URLPattern& pattern); const URLPatternSet& exclude_url_patterns() const { return exclude_url_set_; } void add_exclude_url_pattern(const URLPattern& pattern); // List of js scripts for this user script FileList& js_scripts() { return js_scripts_; } const FileList& js_scripts() const { return js_scripts_; } // List of css scripts for this user script FileList& css_scripts() { return css_scripts_; } const FileList& css_scripts() const { return css_scripts_; } const std::string& extension_id() const { return host_id_.id; } const mojom::HostID& host_id() const { return host_id_; } void set_host_id(const mojom::HostID& host_id) { host_id_ = host_id; } const ConsumerInstanceType& consumer_instance_type() const { return consumer_instance_type_; } void set_consumer_instance_type( const ConsumerInstanceType& consumer_instance_type) { consumer_instance_type_ = consumer_instance_type; } const std::string& id() const { return user_script_id_; } void set_id(std::string id) { user_script_id_ = std::move(id); } // TODO(lazyboy): Incognito information is extension specific, it doesn't // belong here. We should be able to determine this in the renderer/ where it // is used. bool is_incognito_enabled() const { return incognito_enabled_; } void set_incognito_enabled(bool enabled) { incognito_enabled_ = enabled; } // Returns true if the script should be applied to the specified URL, false // otherwise. bool MatchesURL(const GURL& url) const; // Returns true if the script should be applied to the given // |effective_document_url|. It is the caller's responsibility to calculate // |effective_document_url| based on match_origin_as_fallback(). bool MatchesDocument(const GURL& effective_document_url, bool is_subframe) const; // Serializes the UserScript into a pickle. The content of the scripts and // paths to UserScript::Files will not be serialized! void Pickle(base::Pickle* pickle) const; // Deserializes the script from a pickle. Note that this always succeeds // because presumably we were the one that pickled it, and we did it // correctly. void Unpickle(const base::Pickle& pickle, base::PickleIterator* iter); private: // base::Pickle helper functions used to pickle the individual types of // components. void PickleGlobs(base::Pickle* pickle, const std::vector<std::string>& globs) const; void PickleHostID(base::Pickle* pickle, const mojom::HostID& host_id) const; void PickleURLPatternSet(base::Pickle* pickle, const URLPatternSet& pattern_list) const; void PickleScripts(base::Pickle* pickle, const FileList& scripts) const; // Unpickle helper functions used to unpickle individual types of components. void UnpickleGlobs(const base::Pickle& pickle, base::PickleIterator* iter, std::vector<std::string>* globs); void UnpickleHostID(const base::Pickle& pickle, base::PickleIterator* iter, mojom::HostID* host_id); void UnpickleURLPatternSet(const base::Pickle& pickle, base::PickleIterator* iter, URLPatternSet* pattern_list); void UnpickleScripts(const base::Pickle& pickle, base::PickleIterator* iter, FileList* scripts); // The location to run the script inside the document. mojom::RunLocation run_location_ = mojom::RunLocation::kDocumentIdle; // The namespace of the script. This is used by Greasemonkey in the same way // as XML namespaces. Only used when parsing Greasemonkey-style scripts. std::string name_space_; // The script's name. Only used when parsing Greasemonkey-style scripts. std::string name_; // A longer description. Only used when parsing Greasemonkey-style scripts. std::string description_; // A version number of the script. Only used when parsing Greasemonkey-style // scripts. std::string version_; // Greasemonkey-style globs that determine pages to inject the script into. // These are only used with standalone scripts. std::vector<std::string> globs_; std::vector<std::string> exclude_globs_; // URLPatterns that determine pages to inject the script into. These are // only used with scripts that are part of extensions. URLPatternSet url_set_; URLPatternSet exclude_url_set_; // List of js scripts defined in content_scripts FileList js_scripts_; // List of css scripts defined in content_scripts FileList css_scripts_; // The ID of the host this script is a part of. The |ID| of the // |host_id| can be empty if the script is a "standlone" user script. mojom::HostID host_id_; // The type of the consumer instance that the script will be injected. ConsumerInstanceType consumer_instance_type_ = TAB; // The globally-unique id associated with this user script. An empty string // indicates an invalid id. std::string user_script_id_; // Whether we should try to emulate Greasemonkey's APIs when running this // script. bool emulate_greasemonkey_ = false; // Whether the user script should run in all frames, or only just the top one. bool match_all_frames_ = false; // Whether the user script should run in frames whose initiator / precursor // origin matches a match pattern, if an appropriate URL cannot be found for // the frame for matching purposes, such as in the case of about:, data:, and // other schemes. MatchOriginAsFallbackBehavior match_origin_as_fallback_ = MatchOriginAsFallbackBehavior::kNever; // True if the script should be injected into an incognito tab. bool incognito_enabled_ = false; DISALLOW_COPY_AND_ASSIGN(UserScript); }; using UserScriptList = std::vector<std::unique_ptr<UserScript>>; } // namespace extensions #endif // EXTENSIONS_COMMON_USER_SCRIPT_H_