text
stringlengths
27
775k
<?php namespace Swoole\Coroutine; use Swoole; use Swoole\Protocol\RPCServer; class RPC extends Swoole\Client\RPC { static $pool = array(); function __construct($id = null) { parent::__construct($id); //基于Swoole扩展 if (!$this->haveSwoole or class_exists('Swoole\Coroutine\Client', false) === false) { throw new \RuntimeException("require swoole-2.x extension."); } } /** * @param $key * @return \SplQueue */ protected static function getPool($key) { if (!isset(self::$pool[$key])) { self::$pool[$key] = new \SplQueue(); } return self::$pool[$key]; } protected function select($read, $write, $error, $timeout) { return count($read); } protected function getConnection($host, $port) { $pool = self::getPool($host . ':' . $port); if (count($pool) > 0) { $socket = $pool->pop(); } else { $socket = new Client(SWOOLE_SOCK_TCP); $socket->set(array( 'open_length_check' => true, 'package_max_length' => $this->packet_maxlen, 'package_length_type' => 'N', 'package_body_offset' => RPCServer::HEADER_SIZE, 'package_length_offset' => 0, )); /** * 尝试重连一次 */ for ($i = 0; $i < 2; $i++) { $ret = $socket->connect($host, $port, $this->timeout); if ($ret === false and ($socket->errCode == 114 or $socket->errCode == 115)) { //强制关闭,重连 $socket->close(); continue; } else { break; } } $socket->host = $host; $socket->port = $port; } return $socket; } /** * @param $socket Client */ protected function freeConnection($socket) { $pool = self::getPool($socket->host . ':' . $socket->port); $pool->push($socket); } }
/* * Copyright University of Basel, Graphics and Vision Research Group * * 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 scalismo.faces.momo import breeze.linalg.DenseVector /** coefficients describing a Morphable Model instance */ case class MoMoCoefficients(shape: DenseVector[Double], color: DenseVector[Double], expression: DenseVector[Double]) { def *(f: Float): MoMoCoefficients = this * f.toDouble def *(d: Double): MoMoCoefficients = copy(shape = shape * d, color = color * d, expression = expression * d) def +(other: MoMoCoefficients): MoMoCoefficients = copy(shape = shape + other.shape, color = color + other.color, expression = expression + other.expression) def -(other: MoMoCoefficients): MoMoCoefficients = copy(shape = shape - other.shape, color = color - other.color, expression = expression - other.expression) } object MoMoCoefficients { def apply(shape: IndexedSeq[Double], color: IndexedSeq[Double], expression: IndexedSeq[Double]) = new MoMoCoefficients(DenseVector(shape.toArray), DenseVector(color.toArray), DenseVector(expression.toArray)) def apply(shape: IndexedSeq[Double], color: IndexedSeq[Double]) = new MoMoCoefficients(DenseVector(shape.toArray), DenseVector(color.toArray), DenseVector.zeros[Double](0)) def apply(shape: DenseVector[Double], color: DenseVector[Double]) = new MoMoCoefficients(shape, color, DenseVector.zeros[Double](0)) /** get 0 coefficients of specified length */ def zeros(shapeComponents: Int, colorComponents: Int, expressionComponents: Int): MoMoCoefficients = { new MoMoCoefficients( DenseVector.zeros(shapeComponents), DenseVector.zeros(colorComponents), DenseVector.zeros(expressionComponents)) } }
insert into hero(name) values('Ms Nice'); insert into hero(name) values('Nurco'); insert into hero(name) values('Bombastico'); insert into hero(name) values('Fennel'); insert into hero(name) values('Magnostic'); insert into hero(name) values('Duck Man'); insert into hero(name) values('Silly Putty Man'); insert into hero(name) values('Dr Low IQ');
#!/usr/bin/env python3 # Compute the cryptographic hash value of a file # or directory. Metadata is not taken into account. import os, sys import hashlib def eprint(s): print(s,file=sys.stderr) def new_hasher(): return hashlib.sha256() BLOCKSIZE = 2**16 def hash_file(h,path): with open(path,"rb") as f: while True: buf = f.read(BLOCKSIZE) if len(buf)==0: break h.update(buf) return h def hash_rec(path): h = new_hasher() if os.path.isfile(path): h = new_hasher() hash_file(h,path) h.update(path.encode("utf-8")) elif os.path.isdir(path): a = [] for item in os.listdir(path): a.append(os.path.join(path,item)) a.sort() for item in a: hrec = hash_rec(item) h.update(hrec.digest()) h.update(path.encode("utf-8")) else: eprint("Strange file detected: {}".format(path)) sys.exit(1) return h path = sys.argv[1] if os.path.isfile(path): print(hash_file(new_hasher(),path).hexdigest()) elif os.path.isdir(path): os.chdir(path) print(hash_rec("./").hexdigest()) else: eprint("Error: path '{}' cannot be accessed.".format(path))
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // test <type_traits> header, part 1 #define TEST_NAME "<type_traits>, part 1" #include "tdefs.h" #include "typetr.h" #include <type_traits> // TESTS static void t_wrappers() { // test integral_constant, true_type, false_type typedef STD integral_constant<int, 3> XX; T_INTEGRAL_CONSTANT(XX, int, 3); T_INTEGRAL_CONSTANT(STD true_type, bool, true); T_INTEGRAL_CONSTANT(STD false_type, bool, false); } static void t_is_void() { // test is_void<T> for various types T_TEST_CV(is_void, void, true); T_TEST_CV(is_void, char, false); T_TEST_CV(is_void, signed char, false); T_TEST_CV(is_void, unsigned char, false); T_TEST_CV(is_void, wchar_t, false); T_TEST_CV(is_void, short, false); T_TEST_CV(is_void, unsigned short, false); T_TEST_CV(is_void, int, false); T_TEST_CV(is_void, unsigned int, false); T_TEST_CV(is_void, long, false); T_TEST_CV(is_void, unsigned long, false); T_TEST_CV(is_void, long long, false); T_TEST_CV(is_void, unsigned long long, false); T_TEST_CV(is_void, float, false); T_TEST_CV(is_void, double, false); T_TEST_CV(is_void, long double, false); T_TEST_CV(is_void, int*, false); T_TEST(is_void, int&, false); T_TEST_CV(is_void, A, false); T_TEST_CV(is_void, B, false); T_TEST_CV(is_void, C, false); T_TEST_CV(is_void, D, false); T_TEST_CV(is_void, U, false); T_TEST_CV(is_void, pmo, false); T_TEST_CV(is_void, pmoc, false); T_TEST_CV(is_void, pmov, false); T_TEST_CV(is_void, pmocv, false); T_TEST_CV(is_void, pmf, false); T_TEST_CV(is_void, pmfc, false); T_TEST_CV(is_void, pmfv, false); T_TEST_CV(is_void, pmfcv, false); T_TEST_CV(is_void, arr_t, false); T_TEST_CV(is_void, enum_t, false); T_TEST_CV(is_void, pf, false); T_TEST(is_void, func, false); T_TEST_CV(is_void, void*, false); } static void t_is_integral() { // test is_integral<T> for various types T_TEST_CV(is_integral, void, false); T_TEST_CV(is_integral, char, true); T_TEST_CV(is_integral, signed char, true); T_TEST_CV(is_integral, unsigned char, true); T_TEST_CV(is_integral, wchar_t, true); T_TEST_CV(is_integral, short, true); T_TEST_CV(is_integral, unsigned short, true); T_TEST_CV(is_integral, int, true); T_TEST_CV(is_integral, unsigned int, true); T_TEST_CV(is_integral, long, true); T_TEST_CV(is_integral, unsigned long, true); T_TEST_CV(is_integral, long long, true); T_TEST_CV(is_integral, unsigned long long, true); T_TEST_CV(is_integral, float, false); T_TEST_CV(is_integral, double, false); T_TEST_CV(is_integral, long double, false); T_TEST_CV(is_integral, int*, false); T_TEST(is_integral, int&, false); T_TEST_CV(is_integral, A, false); T_TEST_CV(is_integral, B, false); T_TEST_CV(is_integral, C, false); T_TEST_CV(is_integral, D, false); T_TEST_CV(is_integral, U, false); T_TEST_CV(is_integral, pmo, false); T_TEST_CV(is_integral, pmoc, false); T_TEST_CV(is_integral, pmov, false); T_TEST_CV(is_integral, pmocv, false); T_TEST_CV(is_integral, pmf, false); T_TEST_CV(is_integral, pmfc, false); T_TEST_CV(is_integral, pmfv, false); T_TEST_CV(is_integral, pmfcv, false); T_TEST_CV(is_integral, arr_t, false); T_TEST_CV(is_integral, enum_t, false); T_TEST_CV(is_integral, pf, false); T_TEST(is_integral, func, false); T_TEST_CV(is_integral, void*, false); } static void t_is_floating_point() { // test is_floating_point<T> for various types T_TEST_CV(is_floating_point, void, false); T_TEST_CV(is_floating_point, char, false); T_TEST_CV(is_floating_point, signed char, false); T_TEST_CV(is_floating_point, unsigned char, false); T_TEST_CV(is_floating_point, wchar_t, false); T_TEST_CV(is_floating_point, short, false); T_TEST_CV(is_floating_point, unsigned short, false); T_TEST_CV(is_floating_point, int, false); T_TEST_CV(is_floating_point, unsigned int, false); T_TEST_CV(is_floating_point, long, false); T_TEST_CV(is_floating_point, unsigned long, false); T_TEST_CV(is_floating_point, long long, false); T_TEST_CV(is_floating_point, unsigned long long, false); T_TEST_CV(is_floating_point, float, true); T_TEST_CV(is_floating_point, double, true); T_TEST_CV(is_floating_point, long double, true); T_TEST_CV(is_floating_point, int*, false); T_TEST(is_floating_point, int&, false); T_TEST_CV(is_floating_point, A, false); T_TEST_CV(is_floating_point, B, false); T_TEST_CV(is_floating_point, C, false); T_TEST_CV(is_floating_point, D, false); T_TEST_CV(is_floating_point, U, false); T_TEST_CV(is_floating_point, pmo, false); T_TEST_CV(is_floating_point, pmoc, false); T_TEST_CV(is_floating_point, pmov, false); T_TEST_CV(is_floating_point, pmocv, false); T_TEST_CV(is_floating_point, pmf, false); T_TEST_CV(is_floating_point, pmfc, false); T_TEST_CV(is_floating_point, pmfv, false); T_TEST_CV(is_floating_point, pmfcv, false); T_TEST_CV(is_floating_point, arr_t, false); T_TEST_CV(is_floating_point, enum_t, false); T_TEST_CV(is_floating_point, pf, false); T_TEST(is_floating_point, func, false); T_TEST_CV(is_floating_point, void*, false); } static void t_is_array() { // test is_array<T> for various types T_TEST_CV(is_array, void, false); T_TEST_CV(is_array, char, false); T_TEST_CV(is_array, signed char, false); T_TEST_CV(is_array, unsigned char, false); T_TEST_CV(is_array, wchar_t, false); T_TEST_CV(is_array, short, false); T_TEST_CV(is_array, unsigned short, false); T_TEST_CV(is_array, int, false); T_TEST_CV(is_array, unsigned int, false); T_TEST_CV(is_array, long, false); T_TEST_CV(is_array, unsigned long, false); T_TEST_CV(is_array, long long, false); T_TEST_CV(is_array, unsigned long long, false); T_TEST_CV(is_array, float, false); T_TEST_CV(is_array, double, false); T_TEST_CV(is_array, long double, false); T_TEST_CV(is_array, int*, false); T_TEST(is_array, int&, false); T_TEST_CV(is_array, A, false); T_TEST_CV(is_array, B, false); T_TEST_CV(is_array, B, false); T_TEST_CV(is_array, C, false); T_TEST_CV(is_array, D, false); T_TEST_CV(is_array, U, false); T_TEST_CV(is_array, pmo, false); T_TEST_CV(is_array, pmoc, false); T_TEST_CV(is_array, pmov, false); T_TEST_CV(is_array, pmocv, false); T_TEST_CV(is_array, pmf, false); T_TEST_CV(is_array, pmfc, false); T_TEST_CV(is_array, pmfv, false); T_TEST_CV(is_array, pmfcv, false); T_TEST_CV(is_array, arr_t, true); T_TEST_CV(is_array, enum_t, false); T_TEST_CV(is_array, pf, false); T_TEST(is_array, func, false); T_TEST_CV(is_array, void*, false); } static void t_is_pointer() { // test is_pointer<T> for various types T_TEST_CV(is_pointer, void, false); T_TEST_CV(is_pointer, char, false); T_TEST_CV(is_pointer, signed char, false); T_TEST_CV(is_pointer, unsigned char, false); T_TEST_CV(is_pointer, wchar_t, false); T_TEST_CV(is_pointer, short, false); T_TEST_CV(is_pointer, unsigned short, false); T_TEST_CV(is_pointer, int, false); T_TEST_CV(is_pointer, unsigned int, false); T_TEST_CV(is_pointer, long, false); T_TEST_CV(is_pointer, unsigned long, false); T_TEST_CV(is_pointer, long long, false); T_TEST_CV(is_pointer, unsigned long long, false); T_TEST_CV(is_pointer, float, false); T_TEST_CV(is_pointer, double, false); T_TEST_CV(is_pointer, long double, false); T_TEST_CV(is_pointer, int*, true); T_TEST(is_pointer, int&, false); T_TEST_CV(is_pointer, A, false); T_TEST_CV(is_pointer, B, false); T_TEST_CV(is_pointer, C, false); T_TEST_CV(is_pointer, D, false); T_TEST_CV(is_pointer, U, false); T_TEST_CV(is_pointer, pmo, false); T_TEST_CV(is_pointer, pmoc, false); T_TEST_CV(is_pointer, pmov, false); T_TEST_CV(is_pointer, pmocv, false); T_TEST_CV(is_pointer, pmf, false); T_TEST_CV(is_pointer, pmfc, false); T_TEST_CV(is_pointer, pmfv, false); T_TEST_CV(is_pointer, pmfcv, false); T_TEST_CV(is_pointer, arr_t, false); T_TEST_CV(is_pointer, enum_t, false); T_TEST_CV(is_pointer, pf, true); T_TEST(is_pointer, func, false); T_TEST_CV(is_pointer, void*, true); } static void t_is_lvalue_reference() { // test is_lvalue_reference<T> for various types T_TEST_CV(is_lvalue_reference, void, false); T_TEST_CV(is_lvalue_reference, char, false); T_TEST_CV(is_lvalue_reference, signed char, false); T_TEST_CV(is_lvalue_reference, unsigned char, false); T_TEST_CV(is_lvalue_reference, wchar_t, false); T_TEST_CV(is_lvalue_reference, short, false); T_TEST_CV(is_lvalue_reference, unsigned short, false); T_TEST_CV(is_lvalue_reference, int, false); T_TEST_CV(is_lvalue_reference, unsigned int, false); T_TEST_CV(is_lvalue_reference, long, false); T_TEST_CV(is_lvalue_reference, unsigned long, false); T_TEST_CV(is_lvalue_reference, long long, false); T_TEST_CV(is_lvalue_reference, unsigned long long, false); T_TEST_CV(is_lvalue_reference, float, false); T_TEST_CV(is_lvalue_reference, double, false); T_TEST_CV(is_lvalue_reference, long double, false); T_TEST_CV(is_lvalue_reference, int*, false); T_TEST(is_lvalue_reference, int&, true); T_TEST(is_lvalue_reference, int&&, false); T_TEST_CV(is_lvalue_reference, A, false); T_TEST_CV(is_lvalue_reference, C, false); T_TEST_CV(is_lvalue_reference, D, false); T_TEST_CV(is_lvalue_reference, U, false); T_TEST_CV(is_lvalue_reference, pmo, false); T_TEST_CV(is_lvalue_reference, pmoc, false); T_TEST_CV(is_lvalue_reference, pmov, false); T_TEST_CV(is_lvalue_reference, pmocv, false); T_TEST_CV(is_lvalue_reference, pmf, false); T_TEST_CV(is_lvalue_reference, pmfc, false); T_TEST_CV(is_lvalue_reference, pmfv, false); T_TEST_CV(is_lvalue_reference, pmfcv, false); T_TEST_CV(is_lvalue_reference, arr_t, false); T_TEST_CV(is_lvalue_reference, enum_t, false); T_TEST_CV(is_lvalue_reference, pf, false); T_TEST(is_lvalue_reference, func, false); T_TEST_CV(is_lvalue_reference, void*, false); } static void t_is_rvalue_reference() { // test is_rvalue_reference<T> for various types T_TEST_CV(is_rvalue_reference, void, false); T_TEST_CV(is_rvalue_reference, char, false); T_TEST_CV(is_rvalue_reference, signed char, false); T_TEST_CV(is_rvalue_reference, unsigned char, false); T_TEST_CV(is_rvalue_reference, wchar_t, false); T_TEST_CV(is_rvalue_reference, short, false); T_TEST_CV(is_rvalue_reference, unsigned short, false); T_TEST_CV(is_rvalue_reference, int, false); T_TEST_CV(is_rvalue_reference, unsigned int, false); T_TEST_CV(is_rvalue_reference, long, false); T_TEST_CV(is_rvalue_reference, unsigned long, false); T_TEST_CV(is_rvalue_reference, long long, false); T_TEST_CV(is_rvalue_reference, unsigned long long, false); T_TEST_CV(is_rvalue_reference, float, false); T_TEST_CV(is_rvalue_reference, double, false); T_TEST_CV(is_rvalue_reference, long double, false); T_TEST_CV(is_rvalue_reference, int*, false); T_TEST(is_rvalue_reference, int&, false); T_TEST(is_rvalue_reference, int&&, true); T_TEST_CV(is_rvalue_reference, A, false); T_TEST_CV(is_rvalue_reference, C, false); T_TEST_CV(is_rvalue_reference, D, false); T_TEST_CV(is_rvalue_reference, U, false); T_TEST_CV(is_rvalue_reference, pmo, false); T_TEST_CV(is_rvalue_reference, pmoc, false); T_TEST_CV(is_rvalue_reference, pmov, false); T_TEST_CV(is_rvalue_reference, pmocv, false); T_TEST_CV(is_rvalue_reference, pmf, false); T_TEST_CV(is_rvalue_reference, pmfc, false); T_TEST_CV(is_rvalue_reference, pmfv, false); T_TEST_CV(is_rvalue_reference, pmfcv, false); T_TEST_CV(is_rvalue_reference, arr_t, false); T_TEST_CV(is_rvalue_reference, enum_t, false); T_TEST_CV(is_rvalue_reference, pf, false); T_TEST(is_rvalue_reference, func, false); T_TEST_CV(is_rvalue_reference, void*, false); } static void t_is_reference() { // test is_reference<T> for various types T_TEST_CV(is_reference, void, false); T_TEST_CV(is_reference, char, false); T_TEST_CV(is_reference, signed char, false); T_TEST_CV(is_reference, unsigned char, false); T_TEST_CV(is_reference, wchar_t, false); T_TEST_CV(is_reference, short, false); T_TEST_CV(is_reference, unsigned short, false); T_TEST_CV(is_reference, int, false); T_TEST_CV(is_reference, unsigned int, false); T_TEST_CV(is_reference, long, false); T_TEST_CV(is_reference, unsigned long, false); T_TEST_CV(is_reference, long long, false); T_TEST_CV(is_reference, unsigned long long, false); T_TEST_CV(is_reference, float, false); T_TEST_CV(is_reference, double, false); T_TEST_CV(is_reference, long double, false); T_TEST_CV(is_reference, int*, false); T_TEST(is_reference, int&, true); T_TEST(is_reference, int&&, true); T_TEST_CV(is_reference, A, false); T_TEST_CV(is_reference, C, false); T_TEST_CV(is_reference, D, false); T_TEST_CV(is_reference, U, false); T_TEST_CV(is_reference, pmo, false); T_TEST_CV(is_reference, pmoc, false); T_TEST_CV(is_reference, pmov, false); T_TEST_CV(is_reference, pmocv, false); T_TEST_CV(is_reference, pmf, false); T_TEST_CV(is_reference, pmfc, false); T_TEST_CV(is_reference, pmfv, false); T_TEST_CV(is_reference, pmfcv, false); T_TEST_CV(is_reference, arr_t, false); T_TEST_CV(is_reference, enum_t, false); T_TEST_CV(is_reference, pf, false); T_TEST(is_reference, func, false); T_TEST_CV(is_reference, void*, false); } static void t_is_member_object_pointer() { // test is_member_object_pointer<T> for various types T_TEST_CV(is_member_object_pointer, void, false); T_TEST_CV(is_member_object_pointer, char, false); T_TEST_CV(is_member_object_pointer, signed char, false); T_TEST_CV(is_member_object_pointer, unsigned char, false); T_TEST_CV(is_member_object_pointer, wchar_t, false); T_TEST_CV(is_member_object_pointer, short, false); T_TEST_CV(is_member_object_pointer, unsigned short, false); T_TEST_CV(is_member_object_pointer, int, false); T_TEST_CV(is_member_object_pointer, unsigned int, false); T_TEST_CV(is_member_object_pointer, long, false); T_TEST_CV(is_member_object_pointer, unsigned long, false); T_TEST_CV(is_member_object_pointer, long long, false); T_TEST_CV(is_member_object_pointer, unsigned long long, false); T_TEST_CV(is_member_object_pointer, float, false); T_TEST_CV(is_member_object_pointer, double, false); T_TEST_CV(is_member_object_pointer, long double, false); T_TEST_CV(is_member_object_pointer, int*, false); T_TEST(is_member_object_pointer, int&, false); T_TEST_CV(is_member_object_pointer, A, false); T_TEST_CV(is_member_object_pointer, B, false); T_TEST_CV(is_member_object_pointer, C, false); T_TEST_CV(is_member_object_pointer, D, false); T_TEST_CV(is_member_object_pointer, U, false); T_TEST_CV(is_member_object_pointer, pmo, true); T_TEST_CV(is_member_object_pointer, pmoc, true); T_TEST_CV(is_member_object_pointer, pmov, true); T_TEST_CV(is_member_object_pointer, pmocv, true); T_TEST_CV(is_member_object_pointer, pmf, false); T_TEST_CV(is_member_object_pointer, pmfc, false); T_TEST_CV(is_member_object_pointer, pmfv, false); T_TEST_CV(is_member_object_pointer, pmfcv, false); T_TEST_CV(is_member_object_pointer, arr_t, false); T_TEST_CV(is_member_object_pointer, enum_t, false); T_TEST_CV(is_member_object_pointer, pf, false); T_TEST(is_member_object_pointer, func, false); T_TEST_CV(is_member_object_pointer, void*, false); } static void t_is_member_function_pointer() { // test is_member_function_pointer<T> for various types T_TEST_CV(is_member_function_pointer, void, false); T_TEST_CV(is_member_function_pointer, char, false); T_TEST_CV(is_member_function_pointer, signed char, false); T_TEST_CV(is_member_function_pointer, unsigned char, false); T_TEST_CV(is_member_function_pointer, wchar_t, false); T_TEST_CV(is_member_function_pointer, short, false); T_TEST_CV(is_member_function_pointer, unsigned short, false); T_TEST_CV(is_member_function_pointer, int, false); T_TEST_CV(is_member_function_pointer, unsigned int, false); T_TEST_CV(is_member_function_pointer, long, false); T_TEST_CV(is_member_function_pointer, unsigned long, false); T_TEST_CV(is_member_function_pointer, long long, false); T_TEST_CV(is_member_function_pointer, unsigned long long, false); T_TEST_CV(is_member_function_pointer, float, false); T_TEST_CV(is_member_function_pointer, double, false); T_TEST_CV(is_member_function_pointer, long double, false); T_TEST_CV(is_member_function_pointer, int*, false); T_TEST(is_member_function_pointer, int&, false); T_TEST_CV(is_member_function_pointer, A, false); T_TEST_CV(is_member_function_pointer, B, false); T_TEST_CV(is_member_function_pointer, C, false); T_TEST_CV(is_member_function_pointer, D, false); T_TEST_CV(is_member_function_pointer, U, false); T_TEST_CV(is_member_function_pointer, pmo, false); T_TEST_CV(is_member_function_pointer, pmoc, false); T_TEST_CV(is_member_function_pointer, pmov, false); T_TEST_CV(is_member_function_pointer, pmocv, false); T_TEST_CV(is_member_function_pointer, pmf, true); T_TEST_CV(is_member_function_pointer, pmfc, true); T_TEST_CV(is_member_function_pointer, pmfv, true); T_TEST_CV(is_member_function_pointer, pmfcv, true); T_TEST_CV(is_member_function_pointer, arr_t, false); T_TEST_CV(is_member_function_pointer, enum_t, false); T_TEST_CV(is_member_function_pointer, pf, false); T_TEST(is_member_function_pointer, func, false); T_TEST_CV(is_member_function_pointer, void*, false); typedef void (B::*pf0)(); typedef void (B::*pf1)(int); typedef void (B::*pf2)(int, int); typedef void (B::*pf3)(int, int, int); typedef void (B::*pf4)(int, int, int, int); typedef void (B::*pf5)(int, int, int, int, int); CHECK(STD is_member_function_pointer<pf0>::value); CHECK(STD is_member_function_pointer<pf1>::value); CHECK(STD is_member_function_pointer<pf2>::value); CHECK(STD is_member_function_pointer<pf3>::value); CHECK(STD is_member_function_pointer<pf4>::value); CHECK(STD is_member_function_pointer<pf5>::value); } void t_sequence() { // test integer_sequence typedef STD integer_sequence<size_t> s0; CHECK_TYPE(size_t, s0::value_type); CHECK_INT(s0().size(), 0); typedef STD integer_sequence<size_t, 2> s1; CHECK_TYPE(size_t, s1::value_type); CHECK_INT(s1().size(), 1); typedef STD integer_sequence<size_t, 4, 5> s2; CHECK_TYPE(size_t, s2::value_type); CHECK_INT(s2().size(), 2); typedef STD make_integer_sequence<int, 0> si0; CHECK_TYPE(si0, STD integer_sequence<int>); typedef STD make_integer_sequence<int, 1> si1; typedef STD integer_sequence<int, 0> si1a; CHECK_TYPE(si1, si1a); typedef STD make_integer_sequence<int, 2> si2; typedef STD integer_sequence<int, 0, 1> si2a; CHECK_TYPE(si2, si2a); typedef STD make_index_sequence<2> si2b; typedef STD index_sequence_for<int, float> si2d; CHECK_TYPE(si2b, si2d); CHECK_TYPE(s0, STD index_sequence<>); CHECK_TYPE(s1, STD index_sequence<2>); typedef STD index_sequence<4, 5> s2x; CHECK_TYPE(s2, s2x); typedef STD index_sequence<0, 1> si2c; CHECK_TYPE(si2b, si2c); } void t_aliases() { // test template aliases typedef int Ty; CHECK_TYPE(STD remove_const_t<Ty>, STD remove_const<Ty>::type); CHECK_TYPE(STD remove_volatile_t<Ty>, STD remove_volatile<Ty>::type); CHECK_TYPE(STD remove_cv_t<Ty>, STD remove_cv<Ty>::type); CHECK_TYPE(STD add_const_t<Ty>, STD add_const<Ty>::type); CHECK_TYPE(STD add_volatile_t<Ty>, STD add_volatile<Ty>::type); CHECK_TYPE(STD add_cv_t<Ty>, STD add_cv<Ty>::type); CHECK_TYPE(STD remove_reference_t<Ty>, STD remove_reference<Ty>::type); CHECK_TYPE(STD add_lvalue_reference_t<Ty>, STD add_lvalue_reference<Ty>::type); CHECK_TYPE(STD add_rvalue_reference_t<Ty>, STD add_rvalue_reference<Ty>::type); CHECK_TYPE(STD make_signed_t<Ty>, STD make_signed<Ty>::type); CHECK_TYPE(STD make_unsigned_t<Ty>, STD make_unsigned<Ty>::type); CHECK_TYPE(STD remove_extent_t<Ty>, STD remove_extent<Ty>::type); CHECK_TYPE(STD remove_all_extents_t<Ty>, STD remove_all_extents<Ty>::type); CHECK_TYPE(STD remove_pointer_t<Ty>, STD remove_pointer<Ty>::type); CHECK_TYPE(STD add_pointer_t<Ty>, STD add_pointer<Ty>::type); { typedef STD aligned_storage_t<10, 4> Ty1; typedef STD aligned_storage<10, 4>::type Ty2; CHECK_TYPE(Ty1, Ty2); } { typedef STD aligned_union_t<10, int> Ty1; typedef STD aligned_union<10, int>::type Ty2; CHECK_TYPE(Ty1, Ty2); } CHECK_TYPE(STD decay_t<Ty>, STD decay<Ty>::type); { typedef STD enable_if_t<true, Ty> Ty1; typedef STD enable_if<true, Ty>::type Ty2; CHECK_TYPE(Ty1, Ty2); } { typedef STD conditional_t<true, Ty, Ty> Ty1; typedef STD conditional<true, Ty, Ty>::type Ty2; CHECK_TYPE(Ty1, Ty2); } { typedef STD common_type_t<Ty, Ty> Ty1; typedef STD common_type<Ty, Ty>::type Ty2; CHECK_TYPE(Ty1, Ty2); } CHECK_TYPE(STD underlying_type_t<enum_t>, STD underlying_type<enum_t>::type); { #if _HAS_CXX17 CHECK_TYPE(STD invoke_result_t<pf>, STD invoke_result<pf>::type); #else CHECK_TYPE(STD result_of_t<pf()>, STD result_of<pf()>::type); #endif // _HAS_CXX17 } } void test_main() { // test type traits t_wrappers(); t_is_void(); t_is_integral(); t_is_floating_point(); t_is_array(); t_is_pointer(); t_is_lvalue_reference(); t_is_rvalue_reference(); t_is_reference(); t_is_member_object_pointer(); t_is_member_function_pointer(); t_sequence(); t_aliases(); }
namespace Microsoft.Maui.Handlers { public partial interface IPageHandler : IContentViewHandler { } }
using System; using System.Collections.Generic; using System.Text; namespace uplink.NET.Models { /// <summary> /// The list of part upload found with a search operation /// </summary> public class UploadPartsList { /// <summary> /// The items within this list /// </summary> public List<Part> Items { get; set; } public UploadPartsList() { Items = new List<Part>(); } } }
<?php namespace We7\V172; defined('IN_IA') or exit('Access Denied'); /** * [WeEngine System] Copyright (c) 2013 WE7.CC * Time: 1520315760 * @version 1.7.2 */ class CreateJobTable { /** * 执行更新 */ public function up() { if (!pdo_tableexists('job')) { $table = tablename('job'); $sql = "CREATE TABLE IF NOT EXISTS $table ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` int(11) NOT NULL DEFAULT 0 COMMENT '任务类型 10 删除公众号数据 20 同步粉丝 ', `uniacid` int(11) NOT NULL DEFAULT 0 COMMENT 'uniacid', `payload` varchar(255) NOT NULL DEFAULT '' COMMENT '任务附加参数', `status` tinyint(3) NOT NULL DEFAULT '0' COMMENT '1 完成,0 新建', `doing` tinyint(3) NOT NULL DEFAULT '0' COMMENT '0 未开始执行,1 正在执行中 不允许任务并列执行', `title` varchar(22) NOT NULL DEFAULT '' COMMENT '任务中文描述', `handled` int(11) NOT NULL DEFAULT '0' COMMENT '已处理数量', `total` int(11) NOT NULL DEFAULT '0' COMMENT '处理总数量', `create_time` int(11) NOT NULL DEFAULT '0' COMMENT '开始时间', `update_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间', `end_time` int(11) NOT NULL DEFAULT '0' COMMENT '结束时间', PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;"; pdo_run($sql); } } /** * 回滚更新 */ public function down() { } }
package ksm import ( "errors" "strings" "github.com/hashicorp/vault/sdk/framework" "github.com/keeper-security/secrets-manager-go/core" ) var ( errFieldDataNil = errors.New("field data passed for updating was nil") errBadConfigFormat = errors.New("config string is not a valid JSON/Base64") ) // Config holds all configuration for the backend. type Config struct { // KsmAppConfig stores the application configuration. KsmAppConfig string `json:"ksm_config"` } // NewConfig returns a pre-configured Config struct. func NewConfig() *Config { return &Config{} } // Update updates the configuration from the given field data only when the data is different. func (c *Config) Update(d *framework.FieldData) (bool, error) { if d == nil { // NOTE: Use of the path framework ensures `d` is never nil. return false, errFieldDataNil } // Track changes to the configuration. var changed bool if appConfig, ok := d.GetOk(keyKsmAppConfig); ok { if nv := strings.TrimSpace(appConfig.(string)); c.KsmAppConfig != nv { if err := validateConfigStr(nv); err != nil { return false, err } // config with token only - use it to generate new config if parts := strings.Split(nv, ":"); len(parts) == 2 { if cfg, err := NewClientConfig(nv); err != nil { return false, err } else if strings.TrimSpace(cfg) != "" { nv = cfg } } c.KsmAppConfig = nv changed = true } } return changed, nil } func validateConfigStr(cfg string) error { // check if config is actually a binding token if parts := strings.Split(cfg, ":"); len(parts) == 2 { if keyBytes := core.Base64ToBytes(parts[1]); len(keyBytes) == 32 { return nil } } // not a binding token - check if it is base64 encoded jsonCfg := strings.TrimSpace(core.Base64ToString(cfg)) if jsonCfg == "" { jsonCfg = cfg // not base64 - restore original string } // verify it is correct JSON if v := core.JsonToDict(string(jsonCfg)); len(v) == 0 { return errBadConfigFormat } return nil }
# frozen_string_literal: true require 'spec_helper' RSpec.describe AuthorizedProjectUpdate::PeriodicRecalculateService do subject(:service) { described_class.new } describe '#execute' do let(:batch_size) { 2 } let_it_be(:users) { create_list(:user, 4) } before do stub_const('AuthorizedProjectUpdate::PeriodicRecalculateService::BATCH_SIZE', batch_size) User.delete([users[1], users[2]]) end it 'calls AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker' do (1..User.maximum(:id)).each_slice(batch_size).with_index(1) do |batch, index| delay = AuthorizedProjectUpdate::PeriodicRecalculateService::DELAY_INTERVAL * index expect(AuthorizedProjectUpdate::UserRefreshOverUserRangeWorker).to( receive(:perform_in).with(delay, *batch.minmax)) end service.execute end end end
from rest_framework import views from rest_framework.permissions import AllowAny from rest_framework.response import Response from .models import Legal, AppUrls from .serializers import TermsSerializer, PolicySerializer class TermsView(views.APIView): serializer_class = TermsSerializer permission_classes = (AllowAny,) def get(self, request, *args, **kwargs): data = Legal.objects.all().first() return Response(data.terms if data else None) class PolicyView(views.APIView): serializer_class = PolicySerializer permission_classes = (AllowAny,) def get(self, request, *args, **kwargs): data = Legal.objects.all().first() return Response(data.policy if data else None) class AppUrlsView(views.APIView): serializer_class = PolicySerializer permission_classes = (AllowAny,) def get(self, request, *args, **kwargs): data = AppUrls.objects.all().first() return Response({'google': data.google, 'apple': data.apple} if data else None)
// <auto-generated> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace KyGunCo.Counterpoint.Sdk.Entities { // VI_PS_ORD_WITH_CELL_DETAILS public class ViPsOrdWithCellDetail { public long DocId { get; set; } // DOC_ID public int LinSeqNo { get; set; } // LIN_SEQ_NO public int SeqNo { get; set; } // SEQ_NO public string StrId { get; set; } // STR_ID (length: 10) public string StaId { get; set; } // STA_ID (length: 10) public string TktNo { get; set; } // TKT_NO (length: 15) public Guid LinGuid { get; set; } // LIN_GUID public string LinTyp { get; set; } // LIN_TYP (length: 1) public Guid? LinkLinGuid { get; set; } // LINK_LIN_GUID public string Ref { get; set; } // REF (length: 50) public string SlsRep { get; set; } // SLS_REP (length: 10) public string IsValRet { get; set; } // IS_VAL_RET (length: 1) public string IsKitPar { get; set; } // IS_KIT_PAR (length: 1) public Guid? ParLinGuid { get; set; } // PAR_LIN_GUID public string ParItemNo { get; set; } // PAR_ITEM_NO (length: 20) public decimal? KitCompQty { get; set; } // KIT_COMP_QTY public string KitCompQtyUnitFlg { get; set; } // KIT_COMP_QTY_UNIT_FLG (length: 1) public decimal? KitCompUpcharge { get; set; } // KIT_COMP_UPCHARGE public string KitCompItemNo { get; set; } // KIT_COMP_ITEM_NO (length: 20) public string KitCompDim1Upr { get; set; } // KIT_COMP_DIM_1_UPR (length: 15) public string KitCompDim2Upr { get; set; } // KIT_COMP_DIM_2_UPR (length: 15) public string KitCompDim3Upr { get; set; } // KIT_COMP_DIM_3_UPR (length: 15) public string KitSubsTyp { get; set; } // KIT_SUBS_TYP (length: 1) public string KitPrcAdjTyp { get; set; } // KIT_PRC_ADJ_TYP (length: 1) public string KitAdjPrcLvl { get; set; } // KIT_ADJ_PRC_LVL (length: 1) public string StkLocId { get; set; } // STK_LOC_ID (length: 10) public string PrcLocId { get; set; } // PRC_LOC_ID (length: 10) public string PftCtr { get; set; } // PFT_CTR (length: 20) public string Barcod { get; set; } // BARCOD (length: 20) public string RndmWeightBarcod { get; set; } // RNDM_WEIGHT_BARCOD (length: 20) public string ItemNo { get; set; } // ITEM_NO (length: 20) public string Descr { get; set; } // DESCR (length: 50) public string CategCod { get; set; } // CATEG_COD (length: 10) public string SubcatCod { get; set; } // SUBCAT_COD (length: 10) public string ItemVendNo { get; set; } // ITEM_VEND_NO (length: 15) public string ItemTyp { get; set; } // ITEM_TYP (length: 1) public string TrkMeth { get; set; } // TRK_METH (length: 1) public string IsFoodStmpElig { get; set; } // IS_FOOD_STMP_ELIG (length: 1) public string IsFoodStmpLin { get; set; } // IS_FOOD_STMP_LIN (length: 1) public int? QtyDecs { get; set; } // QTY_DECS public int? PrcDecs { get; set; } // PRC_DECS public string TareCod { get; set; } // TARE_COD (length: 10) public decimal? TareWeight { get; set; } // TARE_WEIGHT public int? TareCodIdx { get; set; } // TARE_COD_IDX public decimal? UnitWeight { get; set; } // UNIT_WEIGHT public decimal? UnitCube { get; set; } // UNIT_CUBE public string NormIsTxbl { get; set; } // NORM_IS_TXBL (length: 1) public string IsTxbl { get; set; } // IS_TXBL (length: 1) public string HasTaxOvrd { get; set; } // HAS_TAX_OVRD (length: 1) public string NormTaxCateg { get; set; } // NORM_TAX_CATEG (length: 10) public string TaxCateg { get; set; } // TAX_CATEG (length: 10) public string TaxDsplyFlg { get; set; } // TAX_DSPLY_FLG (length: 1) public decimal? QtySold { get; set; } // QTY_SOLD public decimal QtyNumer { get; set; } // QTY_NUMER public decimal QtyDenom { get; set; } // QTY_DENOM public string QtyUnit { get; set; } // QTY_UNIT (length: 15) public string SellUnit { get; set; } // SELL_UNIT (length: 1) public decimal? OrigQty { get; set; } // ORIG_QTY public decimal? QtyShipped { get; set; } // QTY_SHIPPED public decimal? QtyRet { get; set; } // QTY_RET public decimal? QtyEntd { get; set; } // QTY_ENTD public decimal? QtyPckd { get; set; } // QTY_PCKD public decimal? QtyPckvrfd { get; set; } // QTY_PCKVRFD public decimal? QtyInvcd { get; set; } // QTY_INVCD public decimal? QtyToFill { get; set; } // QTY_TO_FILL public string IsSingleCell { get; set; } // IS_SINGLE_CELL (length: 1) public string Dim1Upr { get; set; } // DIM_1_UPR (length: 15) public string Dim2Upr { get; set; } // DIM_2_UPR (length: 15) public string Dim3Upr { get; set; } // DIM_3_UPR (length: 15) public string SerDescr { get; set; } // SER_DESCR (length: 53) public string DisplayLabel1 { get; set; } // DisplayLabel1 (length: 10) public string DisplayLabel2 { get; set; } // DisplayLabel2 (length: 10) public string DisplayLabel3 { get; set; } // DisplayLabel3 (length: 10) public string DisplayDim1Value { get; set; } // DisplayDim1Value (length: 15) public string DisplayDim2Value { get; set; } // DisplayDim2Value (length: 15) public string DisplayDim3Value { get; set; } // DisplayDim3Value (length: 15) public int? DisplayDim1SeqNo { get; set; } // DisplayDim1SeqNo public int? DisplayDim2SeqNo { get; set; } // DisplayDim2SeqNo public int? DisplayDim3SeqNo { get; set; } // DisplayDim3SeqNo public string CellDescr { get; set; } // CELL_DESCR (length: 47) public int? EcSeqNo { get; set; } // EC_SEQ_NO public decimal? EcOrdTotQtyExpectd { get; set; } // EC_ORD_TOT_QTY_EXPECTD public long? GftRgstryId { get; set; } // GFT_RGSTRY_ID public string PoPreqNo { get; set; } // PO_PREQ_NO (length: 15) public string PoOrdNo { get; set; } // PO_ORD_NO (length: 20) public int? PoLinSeqNo { get; set; } // PO_LIN_SEQ_NO public string PoRecvrNo { get; set; } // PO_RECVR_NO (length: 15) public int? PoRecvrLinSeqNo { get; set; } // PO_RECVR_LIN_SEQ_NO public decimal? PoQtyExpectd { get; set; } // PO_QTY_EXPECTD public decimal? PoTotQtyRecvd { get; set; } // PO_TOT_QTY_RECVD public int? PoRecvrCnt { get; set; } // PO_RECVR_CNT public string PoOrdDescr { get; set; } // PO_ORD_DESCR (length: 85) public string PoRecvStat { get; set; } // PO_RECV_STAT (length: 1) public long? DocIdExt { get; set; } // DOC_ID_EXT public int? LinSeqNoExt { get; set; } // LIN_SEQ_NO_EXT public string UserTradeInProcessed { get; set; } // USER_TRADE_IN_PROCESSED (length: 1) public int? UserRentalAmmoCount { get; set; } // USER_RENTAL_AMMO_COUNT public decimal? UserBuybackPrc { get; set; } // USER_BUYBACK_PRC public string UserBuybackTradeinItemNo { get; set; } // USER_BUYBACK_TRADEIN_ITEM_NO (length: 20) public string UserBuybackTradeinDescr { get; set; } // USER_BUYBACK_TRADEIN_DESCR (length: 30) public string UserBuybackTradeinSerNo { get; set; } // USER_BUYBACK_TRADEIN_SER_NO (length: 30) public string UserBuybackTradeinItemNote { get; set; } // USER_BUYBACK_TRADEIN_ITEM_NOTE (length: 2147483647) public decimal? UserTradeinBuybackExtCost { get; set; } // USER_TRADEIN_BUYBACK_EXT_COST public string UserBuybackTradeinTrxType { get; set; } // USER_BUYBACK_TRADEIN_TRX_TYPE (length: 10) public decimal? UserBuybackTradeinConsideration { get; set; } // USER_BUYBACK_TRADEIN_CONSIDERATION public string UserBuybackTradeinRecvrNo { get; set; } // USER_BUYBACK_TRADEIN_RECVR_NO (length: 15) public int? UserBuybackTradeinRecvrLinSeqNo { get; set; } // USER_BUYBACK_TRADEIN_RECVR_LIN_SEQ_NO public string UserTradeinBuybackProcessed { get; set; } // USER_TRADEIN_BUYBACK_PROCESSED (length: 1) public string UserConsignmentItemNo { get; set; } // USER_CONSIGNMENT_ITEM_NO (length: 20) public string UserConsignmentDescr { get; set; } // USER_CONSIGNMENT_DESCR (length: 30) public string UserConsignmentSerNo { get; set; } // USER_CONSIGNMENT_SER_NO (length: 30) public string UserConsignmentItemNote { get; set; } // USER_CONSIGNMENT_ITEM_NOTE (length: 2147483647) public decimal? UserConsignmentExtCost { get; set; } // USER_CONSIGNMENT_EXT_COST public string UserConsignmentTrxType { get; set; } // USER_CONSIGNMENT_TRX_TYPE (length: 10) public decimal? UserConsignmentConsideration { get; set; } // USER_CONSIGNMENT_CONSIDERATION public string UserConsignmentRecvrNo { get; set; } // USER_CONSIGNMENT_RECVR_NO (length: 15) public int? UserConsignmentRecvrLinSeqNo { get; set; } // USER_CONSIGNMENT_RECVR_LIN_SEQ_NO public string UserConsignmentProcessed { get; set; } // USER_CONSIGNMENT_PROCESSED (length: 1) public string UserConsignmentPayoutItemNo { get; set; } // USER_CONSIGNMENT_PAYOUT_ITEM_NO (length: 20) public string UserConsignmentPayoutLocId { get; set; } // USER_CONSIGNMENT_PAYOUT_LOC_ID (length: 10) public string UserConsignmentPayoutSerNo { get; set; } // USER_CONSIGNMENT_PAYOUT_SER_NO (length: 30) public DateTime? UserConsignmentPayoutRecvdDt { get; set; } // USER_CONSIGNMENT_PAYOUT_RECVD_DT public string UserIntakeType { get; set; } // USER_INTAKE_TYPE (length: 15) public string UserIntakeDocNo { get; set; } // USER_INTAKE_DOC_NO (length: 15) } } // </auto-generated>
#pragma once class Config { private: Config() { loadData(); } Config( const Config& ); Config & operator = (const Config &); char mqttUsername[33]; char mqttPassword[33]; char mqttIp[16]; int mqttPort; void loadData(); public: static Config& instance() { static Config _instance; return _instance; } ~Config() {} char* getMqttUsername(); char* getMqttPassword(); char* getMqttIp(); int getMqttPort(); };
# Pokedex ### How to run cd pokedex npm install npm start And open your browser to `localhost:1234`
using System.Diagnostics.CodeAnalysis; namespace Modbus4Net.Device { /// <summary> /// Modbus IP master device. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1706:ShortAcronymsShouldBeUppercase", Justification = "Breaking change.")] internal class ModbusIpMaster : ModbusMaster { /// <summary> /// Modbus IP master device. /// </summary> /// <param name="transport">Transport used by this master.</param> public ModbusIpMaster(IModbusTransport transport) : base(transport) { } } }
import React from 'react' import GroupSlider from 'antd-group-slider' import 'antd-group-slider/dist/index.css' import 'antd/dist/antd.css' const App = () => { return ( <div style={{ display: 'flex', width: '100%', justifyContent: 'center', flexDirection: 'column', alignItems: 'center' }} > <div className='header'> <div className='header__title'>antd-group-slider</div> <img className='header__logo' src='./favicon.png' alt='logo' /> </div> <h3> NPM:{' '} <a href='https://www.npmjs.com/package/antd-group-slider' target='_blank' rel='noopener noreferrer' > https://www.npmjs.com/package/antd-group-slider </a> </h3> <h3> GitHub:{' '} <a href='https://github.com/huyennbl/antd-group-slider' target='_blank' rel='noopener noreferrer' > https://github.com/huyennbl/antd-group-slider </a> </h3> <p className='intro'> <strong>antd-group-slider</strong> provides a group of sliders that help to input multiple related range-data. It has data sync between sliders on every range change that which would help the user to avoid accidental missing range during actions. </p> <p className='note'> Please first have a look at{' '} <a target='_blank' rel='noopener noreferrer' href='https://ant.design/components/slider/' > Ant Slider </a>{' '} to have a general idea of the use case of this component. </p> <div className='example'> <div className='example__code'> <pre>{'<GroupSlider />'}</pre> </div> <GroupSlider /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider initialValues={{ ranges: [ [0, 25], [50, 100] ], descriptions: ['First', 'Third'] }} />`} </pre> </div> <GroupSlider initialValues={{ ranges: [ [0, 25], [50, 100] ], descriptions: ['First', 'Third'] }} /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider initialValues={{ ranges: [ [0, 25], [50, 100] ], descriptions: ['First', 'Second'] }} initialValuesConfig={{ fillGaps: false }} />`} </pre> </div> <GroupSlider initialValues={{ ranges: [ [0, 25], [50, 100] ], descriptions: ['First', 'Second'] }} initialValuesConfig={{ fillGaps: false }} /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider min={100} max={500} addButtonText='More range' removeButtonText='Remove last' />`} </pre> </div> <GroupSlider min={100} max={500} addButtonText='More range' removeButtonText='Remove last' /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider descriptionConfig={{ placeholder: 'Waiting for description of range {{range}}', leftText: 'Description of {{range}}: ' }} />`} </pre> </div> <GroupSlider descriptionConfig={{ placeholder: 'Waiting for description of range {{range}}', leftText: 'Description of {{range}}: ' }} /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider descriptionConfig={{ leftAddonText: 'Description of {{range}}: ', // addonText only works with type='input' type: 'input' }} />`} </pre> </div> <GroupSlider descriptionConfig={{ leftAddonText: 'Description of {{range}}: ', // addonText only works with type='input' type: 'input' }} /> </div> <div className='example'> <div className='example__code'> <pre>{`<GroupSlider descriptionConfig={{ type: 'none' }} />`} </pre> </div> <GroupSlider descriptionConfig={{ type: 'none' }} /> </div> <div className='example'> <div className='example__code'> <pre>{'<GroupSlider showDivider />'}</pre> </div> <GroupSlider showDivider /> </div> </div> ) } export default App
#include <stdio.h> #include <stdlib.h> #define MAX 100007 struct node{ int x; struct node* pre,*next; }; typedef struct node node; void ins(node* now,node* pre); void del(node* now); void init(void); node* newnode(int x); node* head,*q[MAX],*tail; int main(void) { int N,M,i; scanf("%d",&N); head=newnode(0); tail=newnode(0); head->next=tail; tail->pre=head; node* now=newnode(1); ins(now,head); for(i=2;i<=N;++i){ int who,type; scanf("%d%d",&who,&type); now=newnode(i); if(type) ins(now,q[who]); else ins(now,q[who]->pre); } scanf("%d",&M); for(i=0;i<M;++i){ int x; scanf("%d",&x); del(q[x]); } for(now=head->next;now!=tail;now=now->next) printf("%d ",now->x); putchar('\n'); return 0; } void ins(node* now,node* pre) { now->next=pre->next; now->next->pre=now; pre->next=now; now->pre=pre; q[now->x]=now; } void del(node* now) { if(now==NULL) return; now->pre->next=now->next; now->next->pre=now->pre; q[now->x]=NULL; free(now); } node* newnode(int x) { node* r=(node*)malloc(sizeof(node)); r->x=x; r->pre=NULL; r->next=NULL; }
DEFINE RECORD CDD$TOP.AD.AD_JOURNAL DESCRIPTION IS /*Depreciation Units Journal*/. AD_JOURNAL_CDD STRUCTURE. /* Element = DEP_OBJECT Description = Depreciation object */ DEP_OBJECT DATATYPE IS TEXT SIZE IS 1. /* Element = DATE Description = Date */ ACTION_DATE DATATYPE IS TEXT SIZE IS 8. /* Element = STATIONMAN Description = Station man (operator) */ STATIONMAN DATATYPE IS TEXT SIZE IS 10. END AD_JOURNAL_CDD STRUCTURE. END AD_JOURNAL.
module Consular # Defines the abstract definition of a core. This needs to be # subclassed and have the appropriate methods defined so that # the CLI runner knows how to execute the Termfile on # each core. You will need to add the core to Consular like so: # # Consular.add_core self # class Core attr_accessor :termfile # Instantiated the hash from the Termfile into the # core. # # @param [String] path # Path to Termfile # # @api public def initialize(path) @termfile = Consular::DSL.new(path).to_hash end # Method called by runner to execute the Termfile setup # on the core. # # @api public def setup! raise NotImplementedError, ".setup! needs to be defined for it to be ran by `consular setup`" end # Method called by the runner to execute the Termfile # on the core. # # @api public def process! raise NotImplementedError, ".process! needs to be defined for it to be ran by `consular start`" end class << self # Checks to see if the current system/terminal is the right # one to use for this core. This is called by the CLI to check # if a particular core should be used. # # @return [Boolean] Whether the current system is valid. # # @api public def valid_system? raise NotImplementedError, ".valid_system? needs to be defined for Consular to determine what system is belongs to." end # Captures the current terminal settings for the system. It will # return a hash format like that of Consular::DSL so that Consular # can write it back out into a Termfile. # # @return [Hash] Consular style hash. # # @api public def capture! raise NotImplementedError, "capture! is currently unavailable for this core." end end end end
package sbtBom import sbt._ trait BomSbtKeys { lazy val targetBomFile: SettingKey[sbt.File] = settingKey[File]("target file to store the generated bom") lazy val makeBom: TaskKey[sbt.File] = taskKey[File]("Generates bom file which includes all project dependencies") lazy val listBom: TaskKey[String] = taskKey[String]("Returns a bom which includes all project dependencies") }
# Copyright 2015 Hitachi Data Systems # # 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 copy import testtools from ironicclient import exc from ironicclient.tests.unit import utils import ironicclient.v1.port NODE_UUID = '55555555-4444-3333-2222-111111111111' CONNECTOR1 = {'uuid': '11111111-2222-3333-4444-555555555555', 'node_uuid': NODE_UUID, 'type': 'iqn', 'connector_id': 'iqn.2010-10.org.openstack:test', 'extra': {}} CONNECTOR2 = {'uuid': '66666666-7777-8888-9999-000000000000', 'node_uuid': NODE_UUID, 'type': 'wwpn', 'connector_id': '1234567890543216', 'extra': {}} CREATE_CONNECTOR = copy.deepcopy(CONNECTOR1) del CREATE_CONNECTOR['uuid'] CREATE_CONNECTOR_WITH_UUID = copy.deepcopy(CONNECTOR1) UPDATED_CONNECTOR = copy.deepcopy(CONNECTOR1) NEW_CONNECTOR_ID = '1234567890123456' UPDATED_CONNECTOR['connector_id'] = NEW_CONNECTOR_ID fake_responses = { '/v1/volume/connectors': { 'GET': ( {}, {"connectors": [CONNECTOR1]}, ), 'POST': ( {}, CONNECTOR1, ), }, '/v1/volume/connectors/?detail=True': { 'GET': ( {}, {"connectors": [CONNECTOR1]}, ), }, '/v1/volume/connectors/?fields=uuid,connector_id': { 'GET': ( {}, {"connectors": [CONNECTOR1]}, ), }, '/v1/volume/connectors/%s' % CONNECTOR1['uuid']: { 'GET': ( {}, CONNECTOR1, ), 'DELETE': ( {}, None, ), 'PATCH': ( {}, UPDATED_CONNECTOR, ), }, '/v1/volume/connectors/%s?fields=uuid,connector_id' % CONNECTOR1['uuid']: { 'GET': ( {}, CONNECTOR1, ), }, '/v1/volume/connectors/?detail=True&node=%s' % NODE_UUID: { 'GET': ( {}, {"connectors": [CONNECTOR1]}, ), }, '/v1/volume/connectors/?node=%s' % NODE_UUID: { 'GET': ( {}, {"connectors": [CONNECTOR1]}, ), } } fake_responses_pagination = { '/v1/volume/connectors': { 'GET': ( {}, {"connectors": [CONNECTOR1], "next": "http://127.0.0.1:6385/v1/volume/connectors/?marker=%s" % CONNECTOR1['uuid']} ), }, '/v1/volume/connectors/?limit=1': { 'GET': ( {}, {"connectors": [CONNECTOR1], "next": "http://127.0.0.1:6385/v1/volume/connectors/?limit=1" "&marker=%s" % CONNECTOR1['uuid']} ), }, '/v1/volume/connectors/?limit=1&marker=%s' % CONNECTOR1['uuid']: { 'GET': ( {}, {"connectors": [CONNECTOR2]} ), }, '/v1/volume/connectors/?marker=%s' % CONNECTOR1['uuid']: { 'GET': ( {}, {"connectors": [CONNECTOR2]} ), }, } fake_responses_sorting = { '/v1/volume/connectors/?sort_key=updated_at': { 'GET': ( {}, {"connectors": [CONNECTOR2, CONNECTOR1]} ), }, '/v1/volume/connectors/?sort_dir=desc': { 'GET': ( {}, {"connectors": [CONNECTOR2, CONNECTOR1]} ), }, } class VolumeConnectorManagerTestBase(testtools.TestCase): def _validate_obj(self, expect, obj): self.assertEqual(expect['uuid'], obj.uuid) self.assertEqual(expect['type'], obj.type) self.assertEqual(expect['connector_id'], obj.connector_id) self.assertEqual(expect['node_uuid'], obj.node_uuid) def _validate_list(self, expect_request, expect_connectors, actual_connectors): self.assertEqual(expect_request, self.api.calls) self.assertEqual(len(expect_connectors), len(actual_connectors)) for expect, obj in zip(expect_connectors, actual_connectors): self._validate_obj(expect, obj) class VolumeConnectorManagerTest(VolumeConnectorManagerTestBase): def setUp(self): super(VolumeConnectorManagerTest, self).setUp() self.api = utils.FakeAPI(fake_responses) self.mgr = ironicclient.v1.volume_connector.VolumeConnectorManager( self.api) def test_volume_connectors_list(self): volume_connectors = self.mgr.list() expect = [ ('GET', '/v1/volume/connectors', {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_by_node(self): volume_connectors = self.mgr.list(node=NODE_UUID) expect = [ ('GET', '/v1/volume/connectors/?node=%s' % NODE_UUID, {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_by_node_detail(self): volume_connectors = self.mgr.list(node=NODE_UUID, detail=True) expect = [ ('GET', '/v1/volume/connectors/?detail=True&node=%s' % NODE_UUID, {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_detail(self): volume_connectors = self.mgr.list(detail=True) expect = [ ('GET', '/v1/volume/connectors/?detail=True', {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connector_list_fields(self): volume_connectors = self.mgr.list(fields=['uuid', 'connector_id']) expect = [ ('GET', '/v1/volume/connectors/?fields=uuid,connector_id', {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connector_list_detail_and_fields_fail(self): self.assertRaises(exc.InvalidAttribute, self.mgr.list, detail=True, fields=['uuid', 'connector_id']) def test_volume_connectors_show(self): volume_connector = self.mgr.get(CONNECTOR1['uuid']) expect = [ ('GET', '/v1/volume/connectors/%s' % CONNECTOR1['uuid'], {}, None), ] self.assertEqual(expect, self.api.calls) self._validate_obj(CONNECTOR1, volume_connector) def test_volume_connector_show_fields(self): volume_connector = self.mgr.get(CONNECTOR1['uuid'], fields=['uuid', 'connector_id']) expect = [ ('GET', '/v1/volume/connectors/%s?fields=uuid,connector_id' % CONNECTOR1['uuid'], {}, None), ] self.assertEqual(expect, self.api.calls) self.assertEqual(CONNECTOR1['uuid'], volume_connector.uuid) self.assertEqual(CONNECTOR1['connector_id'], volume_connector.connector_id) def test_create(self): volume_connector = self.mgr.create(**CREATE_CONNECTOR) expect = [ ('POST', '/v1/volume/connectors', {}, CREATE_CONNECTOR), ] self.assertEqual(expect, self.api.calls) self._validate_obj(CONNECTOR1, volume_connector) def test_create_with_uuid(self): volume_connector = self.mgr.create(**CREATE_CONNECTOR_WITH_UUID) expect = [ ('POST', '/v1/volume/connectors', {}, CREATE_CONNECTOR_WITH_UUID), ] self.assertEqual(expect, self.api.calls) self._validate_obj(CREATE_CONNECTOR_WITH_UUID, volume_connector) def test_delete(self): volume_connector = self.mgr.delete(CONNECTOR1['uuid']) expect = [ ('DELETE', '/v1/volume/connectors/%s' % CONNECTOR1['uuid'], {}, None), ] self.assertEqual(expect, self.api.calls) self.assertIsNone(volume_connector) def test_update(self): patch = {'op': 'replace', 'connector_id': NEW_CONNECTOR_ID, 'path': '/connector_id'} volume_connector = self.mgr.update( volume_connector_id=CONNECTOR1['uuid'], patch=patch) expect = [ ('PATCH', '/v1/volume/connectors/%s' % CONNECTOR1['uuid'], {}, patch), ] self.assertEqual(expect, self.api.calls) self._validate_obj(UPDATED_CONNECTOR, volume_connector) class VolumeConnectorManagerPaginationTest(VolumeConnectorManagerTestBase): def setUp(self): super(VolumeConnectorManagerPaginationTest, self).setUp() self.api = utils.FakeAPI(fake_responses_pagination) self.mgr = ironicclient.v1.volume_connector.VolumeConnectorManager( self.api) def test_volume_connectors_list_limit(self): volume_connectors = self.mgr.list(limit=1) expect = [ ('GET', '/v1/volume/connectors/?limit=1', {}, None), ] expect_connectors = [CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_marker(self): volume_connectors = self.mgr.list(marker=CONNECTOR1['uuid']) expect = [ ('GET', '/v1/volume/connectors/?marker=%s' % CONNECTOR1['uuid'], {}, None), ] expect_connectors = [CONNECTOR2] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_pagination_no_limit(self): volume_connectors = self.mgr.list(limit=0) expect = [ ('GET', '/v1/volume/connectors', {}, None), ('GET', '/v1/volume/connectors/?marker=%s' % CONNECTOR1['uuid'], {}, None) ] expect_connectors = [CONNECTOR1, CONNECTOR2] self._validate_list(expect, expect_connectors, volume_connectors) class VolumeConnectorManagerSortingTest(VolumeConnectorManagerTestBase): def setUp(self): super(VolumeConnectorManagerSortingTest, self).setUp() self.api = utils.FakeAPI(fake_responses_sorting) self.mgr = ironicclient.v1.volume_connector.VolumeConnectorManager( self.api) def test_volume_connectors_list_sort_key(self): volume_connectors = self.mgr.list(sort_key='updated_at') expect = [ ('GET', '/v1/volume/connectors/?sort_key=updated_at', {}, None) ] expect_connectors = [CONNECTOR2, CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors) def test_volume_connectors_list_sort_dir(self): volume_connectors = self.mgr.list(sort_dir='desc') expect = [ ('GET', '/v1/volume/connectors/?sort_dir=desc', {}, None) ] expect_connectors = [CONNECTOR2, CONNECTOR1] self._validate_list(expect, expect_connectors, volume_connectors)
/* * Copyright 2021 Alexi Bre * * 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 tech.alexib.yaba.android.ui.home import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalBottomSheetLayout import androidx.compose.material.ModalBottomSheetValue import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.TimeZone import kotlinx.datetime.todayAt import org.koin.androidx.compose.getViewModel import tech.alexib.yaba.android.R import tech.alexib.yaba.android.ui.AddSpace import tech.alexib.yaba.android.ui.components.LoadingScreenWithCrossFade import tech.alexib.yaba.android.ui.components.NoSpendingInSelectedRange import tech.alexib.yaba.android.ui.components.SlideInContent import tech.alexib.yaba.android.ui.components.SpendingWidget import tech.alexib.yaba.android.ui.components.TotalCashBalanceRow import tech.alexib.yaba.android.ui.components.TransactionItem import tech.alexib.yaba.android.util.rememberFlowWithLifecycle import tech.alexib.yaba.data.store.HomeScreenAction import tech.alexib.yaba.data.store.HomeScreenState import tech.alexib.yaba.model.RangeOption import tech.alexib.yaba.model.Transaction @Composable fun Home( navigateToPlaidLinkScreen: () -> Unit, navigateToTransactionsScreen: () -> Unit ) { val viewModel: HomeViewModel = getViewModel() Home( viewModel = viewModel, navigateToPlaidLinkScreen = navigateToPlaidLinkScreen, navigateToTransactionsScreen = navigateToTransactionsScreen ) } @Composable private fun Home( viewModel: HomeViewModel, navigateToPlaidLinkScreen: () -> Unit, navigateToTransactionsScreen: () -> Unit ) { val state by rememberFlowWithLifecycle(flow = viewModel.state) .collectAsState(initial = HomeScreenState.Empty) Home(state) { action -> when (action) { is HomeScreenAction.NavigateToPlaidLinkScreen -> navigateToPlaidLinkScreen() is HomeScreenAction.NavigateToTransactionsScreen -> navigateToTransactionsScreen() is HomeScreenAction.SetSpendingWidgetDateRange -> viewModel.submit(action) } } } @Composable private fun Home( state: HomeScreenState, actioner: (HomeScreenAction) -> Unit ) { val coroutineScope = rememberCoroutineScope() val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden) ModalBottomSheetLayout( sheetState = sheetState, sheetContent = { val modifier = Modifier .verticalScroll(rememberScrollState()) DateRangeBottomSheet(modifier) { rangeOption -> coroutineScope.launch { sheetState.hide() } actioner(HomeScreenAction.SetSpendingWidgetDateRange(rangeOption)) } } ) { LoadingScreenWithCrossFade(state.loading) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { AddSpace() SlideInContent(visible = state.userItemCount == 0L) { Button( onClick = { actioner(HomeScreenAction.NavigateToPlaidLinkScreen) }, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text( text = stringResource(id = R.string.link_first_institution), style = MaterialTheme.typography.button ) } } SlideInContent( visible = state.currentCashBalance != null && state.userItemCount != 0L ) { TotalCashBalanceRow(state.currentCashBalance) AddSpace() } SlideInContent(visible = state.recentTransactions.isNotEmpty()) { RecentTransactions(transactions = state.recentTransactions) { actioner(HomeScreenAction.NavigateToTransactionsScreen) } } var spendingVisible by remember { mutableStateOf(false) } state.spendingByCategory?.let { when { it.spend.isEmpty() -> SlideInContent(visible = spendingVisible) { NoSpendingInSelectedRange(it.rangeOption.name) { coroutineScope.launch { sheetState.show() } } } else -> SlideInContent(visible = spendingVisible) { SpendingWidget(it) { coroutineScope.launch { sheetState.show() } } } } } LaunchedEffect(key1 = state.spendingByCategory == null) { delay(500) spendingVisible = true } } } } } @Composable private fun RecentTransactions( transactions: List<Transaction>, onSelectAllTransactions: () -> Unit ) { Card( modifier = Modifier .fillMaxWidth() .wrapContentHeight(align = Alignment.Top) .padding(4.dp) .clickable { onSelectAllTransactions() }, elevation = 3.dp ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { // only pulls 5 transactions transactions.forEach { Row { TransactionItem(transaction = it) { onSelectAllTransactions() } } } Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { TextButton(onClick = { onSelectAllTransactions() }) { Text(text = stringResource(id = R.string.view_all_transactions)) } } } } } @Suppress("ComplexMethod") @Composable private fun DateRangeBottomSheet( modifier: Modifier = Modifier, handleSelect: (RangeOption) -> Unit ) { val today = remember { Clock.System.todayAt(TimeZone.currentSystemDefault()) } Column( modifier = modifier .fillMaxWidth() .background(MaterialTheme.colors.background), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { val buttonModifier = Modifier .fillMaxWidth() val months = today.monthNumber fun Int.monthString() = when (this) { 1 -> "January" 2 -> "February" 3 -> "March" 4 -> "April" 5 -> "May" 6 -> "June" 7 -> "July" 8 -> "August" 9 -> "September" 10 -> "October" 11 -> "November" 12 -> "December" else -> throw IllegalArgumentException("month cannot be $this") } (1..months).forEach { val buttonColors = if (it == months) { ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.primary) } else ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.surface) TextButton( onClick = { handleSelect(RangeOption.values()[it - 1]) }, colors = buttonColors, modifier = buttonModifier ) { Text(text = it.monthString()) } Divider() } val whiteButtons = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.surface) TextButton( onClick = { handleSelect(RangeOption.ThisYear) }, colors = whiteButtons, modifier = buttonModifier ) { Text(text = "This year") } Divider() TextButton( onClick = { handleSelect(RangeOption.LastYear) }, colors = whiteButtons, modifier = buttonModifier ) { Text(text = "Last year") } Divider() TextButton( onClick = { handleSelect(RangeOption.AllTime) }, colors = whiteButtons, modifier = buttonModifier ) { Text(text = "All time") } } }
require 'Config' module OpenshiftReliability class ClusterUser def initialize() @userkey=$config.keys+"admin.kubeconfig" end def get_projects() projects=[] res=exec("oc get projects --no-headers") if res[:status] ==0 && ! res[:output].nil? && res[:output].length>0 res[:output].split(/\n/).each do |line| project_name=line.split(/\s/)[0] next if project_name == "default" || project_name =~ /.*openshift.*/ projects.push( project_name) end end return projects end def delete_project(project_name) exec("oc delete project #{project_name}") end def exec(cmd) $exec.shell_exec( "#{cmd} --config=#{@userkey}" ) end def delete_user(user_name) exec("oc delete user #{user_name}") #deleting identity also because if the same user is created it wont have problem exec("oc delete identity htpasswd_auth:#{user_name}") end def create_ds(project_name) exec("oc create -f /root/svt/reliability/daemonset-pause-test.yaml -n #{project_name}") end def label_ds_nodes() exec ("oc label nodes -l region=primary --overwrite ds-node=true") end def unlabel_ds_nodes() exec ("oc label nodes -l region=primary --overwrite ds-node=false") end end end
import 'package:flutter/material.dart'; /// 스크롤업 버튼 구현 페이지 class WithScrollUpButton extends StatefulWidget { /// 스크롤업 버튼을 가질 리스트뷰로 컨트롤러를 포함해야 함 final ListView listView; /// 버튼 색상 /// 기본값 `Theme.of(context).accentColor` final Color? buttonColor; /// 버튼 투명도 /// 기본값 `0.8` final double buttonOpacity; /// 버튼 아이콘 /// 기본값 `Icons.keyboard_arrow_up` final IconData buttonIcon; /// 미니 버튼 사용 여부 /// 기본값 `false` final bool buttonMini; /// 버튼 바깥 여백 /// 기본값 `const EdgeInsets.all(12.0)` final EdgeInsetsGeometry buttonMargin; const WithScrollUpButton({ Key? key, required this.listView, this.buttonColor, this.buttonOpacity = 0.8, this.buttonIcon = Icons.keyboard_arrow_up, this.buttonMini = false, this.buttonMargin = const EdgeInsets.all(12.0) }) : assert(buttonOpacity >= 0.0 && buttonOpacity <= 1.0), super(key: key); @override _WithScrollUpButtonState createState() => _WithScrollUpButtonState(); } class _WithScrollUpButtonState extends State<WithScrollUpButton> with SingleTickerProviderStateMixin { late AnimationController _animationController; late Animation<Offset> _slideAnimation; bool _visibleScrollUpButton = false; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 200) ); _slideAnimation = Tween<Offset>( begin: const Offset(0.0, 1.0), end: const Offset(0.0, 0.0) ).animate(_animationController); widget.listView.controller?.addListener(() { if (widget.listView.controller?.offset == 0.0) { if (_visibleScrollUpButton) { _animationController.reverse(); _visibleScrollUpButton = false; } } else { if (!_visibleScrollUpButton) { _animationController.forward(); _visibleScrollUpButton = true; } } }); } @override Widget build(BuildContext context) { return Stack( alignment: AlignmentDirectional.bottomEnd, children: <Widget>[ widget.listView, _buildScrollUpButton() ], ); } Widget _buildScrollUpButton() { return SlideTransition( position: _slideAnimation, child: Container( margin: widget.buttonMargin, child: Opacity( opacity: widget.buttonOpacity, child: FloatingActionButton( backgroundColor: widget.buttonColor ?? Theme.of(context).accentColor, mini: widget.buttonMini, child: Icon(widget.buttonIcon), onPressed: () { widget.listView.controller?.animateTo( 0.0, duration: const Duration(milliseconds: 250), curve: Curves.fastOutSlowIn ); }, ), ), ), ); } }
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="author" content="Pawel 'kilab' Balicki - kilab.pl" /> <title>SimpleAdmin</title> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" /> <link rel="stylesheet" type="text/css" href="css/navi.css" media="screen" /> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function(){ $(".box .h_title").not(this).next("ul").hide("normal"); $(".box .h_title").not(this).next("#home").show("normal"); $(".box").children(".h_title").click( function() { $(this).next("ul").slideToggle(); }); }); </script> </head> <body> <div class="wrap"> <div id="header"> <div id="top"> <div id="content"> <div id="sidebar"> <div class="box"> <div class="h_title">&#8250; About Us</div> <ul id="home"> <li class="b1"><a class="icon view_page" href="admin/infoaboutus.php">Info of Car Pooling</a></li> <li class="b2"><a class="icon report" href="admin/tandc.php">Terms And Condition</a></li> <li class="b1"><a class="icon add_page" href="admin/trust.php">Trust</a></li> <li class="b2"><a class="icon config" href="admin/choice.php">Choice</a></li> <li class="b2"><a class="icon config" href="admin/insurance.php">Insurance</a></li> </ul> </div> <div class="box" > <div class="h_title">&#8250; About Ridesharing</div> <ul id="home"> <li class="b1"><a class="icon page" href="admin/ridesharing.php">Ridesharing</a></li> <li class="b2"><a class="icon add_page" href="admin/searchforride.php">How to search for ride?</a></li> <li class="b1"><a class="icon photo" href="admin/bookride.php">How to book a ride?</a></li> <li class="b2"><a class="icon category" href="admin/payforride.php">How to pay for a ride?</a></li> </ul> </div> <div class="box"> <div class="h_title">&#8250; Car Pooling</div> <ul id="home"> <li class="b1"><a class="icon users" href="admin/aimofepickup.php">Aim of Car Pooling</a></li> <li class="b2"><a class="icon add_user" href="admin/howitworks.php">How it works?</a></li> </ul> </div> </div> </div> </body> </html>
import { } from 'jasmine'; import capivara from '../../src/index'; // describe('test create component', () => { // const template = ` // <my-component id="demo"></my-component> // `; // const element = document.createElement('div'); // element.innerHTML = template; // });
package cn.woolsen.material.animations import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.graphics.drawable.DrawableCompat import androidx.fragment.app.Fragment class SharedElementFragment2 : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.activity_sharedelement_fragment2, container, false) val sample = arguments!!.getSerializable(EXTRA_SAMPLE) as Sample val squareBlue = view.findViewById<ImageView>(R.id.square_blue) DrawableCompat.setTint(squareBlue.drawable, sample.color) return view } companion object { private const val EXTRA_SAMPLE = "sample" @JvmStatic fun newInstance(sample: Sample): SharedElementFragment2 { return SharedElementFragment2().apply { arguments = Bundle().apply { putSerializable(EXTRA_SAMPLE, sample) } } } } }
<?php namespace Honeybadger; use Honeybadger\Backtrace\Line; /** * Tests Honeybadger\Backtrace. * * @group honeybadger */ class BacktraceTest extends \PHPUnit_Framework_TestCase { public function test_parse_drops_null_lines() { $callback = function($line) { if ($line['file'] == 'dropme.php') return NULL; return $line; }; $lines = array( array( 'file' => 'dropme.php', 'line' => 1, 'function' => '', ), array( 'file' => '[PROJECT_ROOT]/app.php', 'line' => 789, 'function' => 'get', ), ); $backtrace = Backtrace::parse($lines, array( 'filters' => array($callback), )); $this->assertEquals(array(Line::parse($lines[1])), $backtrace->lines); } public function test_parse_returns_backtrace_containing_parsed_lines() { $unparsed_lines = array( array( 'file' => 'hello.php', 'line' => 1, 'function' => 'world', ), array( 'file' => 'world.php', 'line' => 2, 'function' => 'hello', ), ); $backtrace = Backtrace::parse($unparsed_lines); $expected_lines = array( new Line('hello.php', 1, 'world'), new Line('world.php', 2, 'hello'), ); $this->assertEquals($expected_lines, $backtrace->lines); } public function test_attributes_read_only() { $attributes = array('lines', 'application_lines'); $line = new Backtrace; foreach ($attributes as $attribute) { $line->$attribute; try { $line->$attribute = 'foo'; } catch (\Exception $ex) { continue; } $this->fail('An exception was not raised for '.$line); } } public function test_lines() { $lines = array( new Line('[PROJECT_ROOT]/models/user.php', 3, 'find'), new Line('[PROJECT_ROOT]/app.php', 789, 'get'), new Line('[PROJECT_ROOT]/vendor/some_lib.php', 456, 'run'), new Line('/usr/local/share/some_other_lib.php', 123, 'execute'), ); $backtrace = new Backtrace($lines); $this->assertEquals($lines, $backtrace->lines); } public function test_application_lines_exclude_non_project_lines() { $lines = array( new Line('[PROJECT_ROOT]/models/user.php', 3, 'find'), new Line('[PROJECT_ROOT]/app.php', 789, 'get'), new Line('[PROJECT_ROOT]/vendor/some_lib.php', 456, 'run'), new Line('/usr/local/share/some_other_lib.php', 123, 'execute'), ); $backtrace = new Backtrace($lines); $this->assertEquals(array($lines[0], $lines[1]), $backtrace->application_lines); } public function test_has_lines() { $backtrace = new Backtrace; $this->assertFalse($backtrace->has_lines()); $backtrace = new Backtrace(array( new Line('super_cool_file.php', 3, 'super_cool_method') )); $this->assertTrue($backtrace->has_lines()); } public function test_has_application_lines() { $backtrace = new Backtrace; $this->assertFalse($backtrace->has_application_lines()); $backtrace = new Backtrace(array( new Line('[PROJECT_ROOT]/super_cool_file.php', 3, 'super_cool_method') )); $this->assertTrue($backtrace->has_application_lines()); } public function test_string_conversion_returns_ruby_style_backtrace() { $lines = array( new Line('yet_another_lame_example.php', 1337, 'leet'), new Line('yet_another_lame_example.php', 7331, 'teel'), ); $backtrace = new Backtrace($lines); $expected = "yet_another_lame_example.php:1337:in `leet'\n"; $expected .= "yet_another_lame_example.php:7331:in `teel'"; $this->assertEquals($expected, (string) $backtrace); } public function test_to_array_returns_each_line_as_array() { $lines = array( new Line('some_file.php', 21, 'baz'), new Line('another_file.php', 33, 'bar'), ); $backtrace = new Backtrace($lines); $expected = array( array( 'file' => 'some_file.php', 'number' => 21, 'method' => 'baz', ), array( 'file' => 'another_file.php', 'number' => 33, 'method' => 'bar', ), ); $this->assertEquals($expected, $backtrace->to_array()); } public function test_to_json() { $lines = array( new Line('foo', 11, 'bar'), new Line('baz', 2, 'something'), ); $backtrace = new Backtrace($lines); $expected = json_encode(array( array( 'file' => 'foo', 'number' => 11, 'method' => 'bar', ), array( 'file' => 'baz', 'number' => 2, 'method' => 'something', ), )); $this->assertEquals($expected, $backtrace->to_json()); } }
import { PageConfig as AliPageConfig } from 'remax/ali'; const config: AliPageConfig = { defaultTitle: 'Ali Page', titleBarColor: '#323239', }; export default config;
class SubReportUtil { static final SubReportUtil _instance = SubReportUtil._internal(); Map<String, String> statusLabelToIdName = { "ODP": "odp", "ODP Selesai Pemantauan": "odpsp", "PDP": "pdp", "PDP Sembuh": "pdps", "PDP Meninggal": "pdpm", "Orang Tidak Bergejala (OTG)": "otg", "Positif": "positive", "Positif Sembuh": "recovered", "Positif Meninggal": "death", }; Map<String, String> statusIdNameToLabel = {}; factory SubReportUtil() { return _instance; } SubReportUtil._internal(){ for (final ma in statusLabelToIdName.entries) { statusIdNameToLabel[ma.value] = ma.key; } } }
package solution import ( "math/rand" "reflect" "testing" ) func TestCountSmallerExample(t *testing.T) { input := []int{5, 2, 6, 1} expect := []int{2, 1, 1, 0} got := countSmaller(input) assertequal(t, got, expect) } func TestCountSmallerFuzz(t *testing.T) { n := 1000 nums := make([]int, n) for trial := 0; trial < 1000; trial++ { for i := 0; i < n; i++ { nums[i] = int(rand.Int31()) } got := countSmaller(nums) expect := naive(nums) assertequal(t, got, expect) } } // naive implementation of countSmaller. func naive(nums []int) []int { n := len(nums) counts := make([]int, n) for i, num := range nums { for j := i + 1; j < n; j++ { if nums[j] < num { counts[i]++ } } } return counts } func assertequal(t *testing.T, got, expect []int) { if !reflect.DeepEqual(got, expect) { t.Fatalf("got %v; expect %v", got, expect) } }
#include "PluginProcessor.h" #include "PluginEditor.h" ModularAudioProcessorEditor::ModularAudioProcessorEditor( ModularAudioProcessor& p) : juce::AudioProcessorEditor(&p), audioProcessor(p) { setSize(500, 400); addAndMakeVisible(aSlider_); aSlider_.setValue(1.0); aSlider_.setRange(0.01, 2.0, 0.001); aSlider_.onValueChange = [this] { a_ = aSlider_.getValue(); repaint(); }; // addAndMakeVisible(module1_); // addAndMakeVisible(module2_); // addAndMakeVisible(module3_); } void ModularAudioProcessorEditor::paint(juce::Graphics& g) { auto colorID = juce::ResizableWindow::backgroundColourId; g.fillAll(getLookAndFeel().findColour(colorID)); if (isDragging_) { g.setColour(juce::Colours::white); g.drawLine(juce::Line {start_, end_}.toFloat(), 10.0f); g.setColour(juce::Colours::red); } auto a = a_ * (-1); auto b = 2; auto c = 2; auto f = [a, b, c](auto x) { return a * (x * x) + (b * x) + c; }; auto path = juce::Path {}; path.startNewSubPath(-400, f(-400)); for (auto x = -399; x < 400; x += 1) { path.lineTo(x + 250, f(x) + 300); } g.strokePath(path, juce::PathStrokeType(5.0f)); } void ModularAudioProcessorEditor::resized() { auto area = getLocalBounds(); aSlider_.setBounds(area.removeFromTop(50)); // auto moduleWidth = area.getWidth() / 3; // module1_.setBounds(area.removeFromLeft(moduleWidth)); // module2_.setBounds(area.removeFromLeft(moduleWidth)); // module3_.setBounds(area.removeFromLeft(moduleWidth)); } void ModularAudioProcessorEditor::mouseDown(juce::MouseEvent const& event) { } void ModularAudioProcessorEditor::mouseDrag(juce::MouseEvent const& event) { start_.x = event.mouseDownPosition.x; start_.y = event.mouseDownPosition.y; end_.x = event.x; end_.y = event.y; isDragging_ = true; repaint(); } void ModularAudioProcessorEditor::mouseUp(juce::MouseEvent const& event) { isDragging_ = false; repaint(); }
<?php function _syslog($msg) { $trace = debug_backtrace(); $caller = $trace[1]; $parent = $caller['function']; if (isset($caller['class'])) { $parent = $caller['class'] . '::' . $parent; } return error_log( "{$parent}: {$msg}" ); } function notimplemented() { header('HTTP/1.1 501 Not Implemented'); die("This functionality is yet to be implemented"); } function unauthorized($text) { header('HTTP/1.1 401 Unauthorized'); _syslog("unauth:" . $text); die($text); } function badrequest($text) { header('HTTP/1.1 400 Bad Request'); _syslog("badreq:" . $text); die($text); } function remoteerror($text) { header('HTTP/1.1 421 Misdirected Request'); _syslog("remote_err:" . $text); die($text); } function httpok($text) { header('HTTP/1.1 200 OK'); _syslog("ok:" . $text); echo($text); exit(0); } function accepted() { header('HTTP/1.1 202 Accepted'); _syslog("accepted:"); exit(0); } function verify_token($token) { $request = curl_init(); curl_setopt($request, CURLOPT_URL, 'https://tokens.indieauth.com/token'); curl_setopt($request, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded', "Authorization: Bearer {$token}" )); curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($request); curl_close($request); parse_str(urldecode($response), $verification); if (! isset($verification['scope']) ) { unauthorized('missing "scope"'); } if (! isset($verification['me']) ) { unauthorized('missing "me"'); } if ( ! stristr($verification['me'], '{{ site.name }}') ) { unauthorized('wrong domain'); } } function save_to_wallabag($url) { $wallabag_url = "{{ wallabag["url"] }}"; $data = array( "client_id" => "{{ wallabag["client_id"] }}", "client_secret" => "{{ wallabag["client_secret"] }}", "username" => "{{ wallabag["username"] }}", "password" => "{{ wallabag["password"] }}", "grant_type" => "password" ); $request = curl_init(); curl_setopt($request, CURLOPT_URL, "{$wallabag_url}/oauth/v2/token"); curl_setopt($request, CURLOPT_POST, 1); curl_setopt($request, CURLOPT_POSTFIELDS,http_build_query($data)); curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($request); curl_close($request); try { $wallabag_token = json_decode($response, true); } catch (Exception $e) { remoteerror("failed to parse response from wallabag: " . $response); } if (! isset($wallabag_token['access_token']) ) { remoteerror("failed to obtain access token from wallabag: " . $response); } $data = array( "url" => $url, "archive" => 1 ); $headers = array( 'Content-Type: application/x-www-form-urlencoded', "Authorization: Bearer ". $wallabag_token["access_token"] ); $request = curl_init(); curl_setopt($request, CURLOPT_URL, "{$wallabag_url}/api/entries"); curl_setopt($request, CURLOPT_POST, 1); curl_setopt($request, CURLOPT_POSTFIELDS,http_build_query($data)); curl_setopt($request, CURLOPT_HTTPHEADER, $headers); curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($request); curl_close($request); try { $is_saved = json_decode($response, true); accepted(); } catch (Exception $e) { remoteerror("failed to parse response to save from wallabag: " . $response); } } function maybe_array_pop($x) { if(is_array($x)) { return array_pop($x); } else { return $x; } } if (!empty($_GET)) { if ( ! isset($_GET['q']) ) { badrequest('please POST a micropub request'); } if ( isset($_GET['q']['config']) ) { httpok('{{tags|tojson(indent=4)}}'); } if(isset($_GET['q']['syndicate-to'])) { httpok(json_encode(array('syndicate-to' => array()))); } badrequest('please POST a micropub request'); } $raw = file_get_contents("php://input"); $decoded = 'null'; try { $decoded = json_decode($raw, true); } catch (Exception $e) { _syslog('failed to decode JSON, trying decoding form data'); } if($decoded == 'null' or empty($decoded)) { try { parse_str($raw, $decoded); } catch (Exception $e) { _syslog('failed to decoding form data as well'); badrequest('invalid POST contents'); } } $token = ''; if (isset($decoded['access_token'])) { $token = $decoded['access_token']; unset($decoded['access_token']); } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) { $token = trim(str_replace('Bearer', '', $_SERVER['HTTP_AUTHORIZATION'])); } if (empty($token)) { unauthorized('missing token'); } else { verify_token($token); } /* likes and bookmarks */ $bookmark_url = ''; if(isset($decoded["properties"]) && isset($decoded["properties"]["like-of"])) { $bookmark_url = maybe_array_pop($decoded["properties"]["like-of"]); } elseif(isset($decoded["like-of"])) { $bookmark_url = maybe_array_pop($decoded["like-of"]); } if(!empty($bookmark_url)) { save_to_wallabag($bookmark_url); accepted(); } else { /* save everything else into the queue for now */ $t = microtime(true); $fpath = "/web/petermolnar.net/queue/{$t}.json"; if(!is_dir(dirname($fpath))) { mkdir(dirname($fpath), 0755, true); } $c = json_encode($decoded, JSON_PRETTY_PRINT); if (file_put_contents($fpath, $c)) { accepted(); } } /* fallback to not implemented */ notimplemented();
import time import pyautogui from .point import point from pywinauto import application from pyautogui import ( moveTo, keyDown, keyUp, press ) def moveClick(target, sleep=True): """ Parameters ---------- target : Returns ------- """ pyautogui.moveTo(target.x, target.y, 1, tween=pyautogui.easeInOutQuad) pyautogui.moveTo(target.x, target.y, 1) time.sleep(0.1) pyautogui.mouseDown() time.sleep(0.1) pyautogui.mouseUp() if sleep: time.sleep(0) class window: """ """ def __init__(self, exe, reference): try: self.app = application.Application(backend="uia").connect(path = exe) self.dlg = self.app.window(title_re=reference) except: self.app = application.Application(backend="uia").start(exe) time.sleep(30) self.dlg = self.app.window(title_re=reference) @staticmethod def center(control): rect = control.rectangle() left = rect.left top = rect.top bottom = rect.bottom right = rect.right x = int(left - (left - right)/2) y = int(bottom - (bottom - top)/2) return point(x, y) def move(self, target): control = self.get(target) center = window.center(control) moveTo(center.x, center.y, 1) moveTo(center.x + 1, center.y + 1, 1) def click(self, target, value = ""): control = self.get(target, value) center = window.center(control) moveClick(center) def search(self, target, value): control = self.find(target, value) center = window.center(control) moveClick(center, sleep=False) def find(self, target, value): for index in range(4): for element in target.options: control = self.dlg.child_window(auto_id = element, found_index = index) found = window.value(control) if (found == value): return control @staticmethod def value(control): return control.legacy_properties()['Name'] def click_if(self, target, condition): control = self.get(target) if (window.value(control) == condition): self.click(target) def get(self, target, value=""): self.app.top_window().set_focus() if value == "": return self.dlg.child_window(auto_id = target) for index in range(4): control = self.dlg.child_window(auto_id = target, found_index=index) if (window.value(control) == value): return control
<?php namespace yii2lab\domain\events; /** * Class QueryEvent * * @package yii2lab\domain\events * @deprecated */ class QueryEvent extends MethodEvent { }
<!-- Copyright 2019 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> # TBMv3 [Experimental] This directory contains files for TBMv3, an experimental new metric authoring platform based on Perfetto.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class MyModel extends CI_Model{ public function action($act, $table, $data=null, $where=null){ if(!is_null($where)){ $this->db->where($where); } switch ($act) { case 'input' : $this->db->insert($table,$data); break; case 'update' : $this->db->update($table,$data); break; case 'delete' : $this->db->delete($table); break; default: break; } } public function addData($table, $data){ if($this->db->insert($table, $data) === FALSE){ $msg = $this->db->error('message'); return array( 'msg' => $msg['message'], 'header' => 'GAGAL', 'icon' => 'error', 'err' => TRUE ); } return array( 'msg' => 'Insert Sukses', 'header' => 'BERHASIL', 'icon' => 'success', 'err' => FALSE ); } public function updateData($table, $data, $where){ $this->db->where($where); if($this->db->update($table, $data) === FALSE){ $msg = $this->db->error('message'); return array( 'msg' => $msg['message'], 'header' => 'GAGAL', 'icon' => 'error', 'err' => TRUE ); } return array( 'msg' => 'Update Sukses', 'header' => 'BERHASIL', 'icon' => 'success', 'err' => FALSE ); } public function sess_privilage(){ $this->session->unset_userdata('list_akses'); $id = $this->session->userdata('akses'); $this->db->where(['id' => $id]); $list_akses = $this->db->get('access')->row_array(); $this->session->set_userdata('list_akses', $list_akses); } } ?>
import { Component, OnInit, ViewChild } from '@angular/core'; import { ModalDirective, PopoverDirective } from 'ng2-bootstrap/ng2-bootstrap'; import { NotificationService } from '../shared'; import { TodoService } from './todo.service'; import { Todo } from './todo.model'; @Component({ selector: 'dml-todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.scss'] }) export class TodoComponent implements OnInit { todo: Todo; todos: Todo[]; content: string ="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." @ViewChild('staticModal') public staticModal: ModalDirective; @ViewChild('adiarTemplate') public adiarTemplate: PopoverDirective; public itemsPerPage: number = 10; public totalItems: number = 0; public currentPage: number = 1; constructor(private service: TodoService, private notificationService: NotificationService) { } ngOnInit() { this.list(); } pageChanged(event: any): void { this.currentPage = event.page; this.list(); } list() { this.service.list(this.currentPage, this.itemsPerPage).subscribe( result => { this.totalItems = 20; // backend must send the total items for proper pagination config this.todos = result; }, error => { this.notificationService.error('Não foi possível carregar a lista de todos!'); this.totalItems = 20; this.todos = error; } ); } delete(todo: Todo) { this.service.delete(todo).subscribe( () => { this.todo = null; this.staticModal.hide(); this.list(); }, error => { this.notificationService.error('Não foi possível remover o usuário!'); } ); } adiar(todo, days) { // todo :) } setStatus(todo, status) { } }
# asy-brewer: ColorBrewer palettes for Asymptote [Asymptote](https://asymptote.sourceforge.io) is vector graphics language for technical drawing. It ships with a number of base modules including `palettes` which provides a number of colour palettes. This module supplements these with Cynthia Brewer and Mark Hadden's ColorBrewer palettes (http://colorbrewer2.org/). The ColorBrewer palettes were designed for maps, allowing effective differentiation of different colours in neighbouring regions, but they are also useful for other applications. [HarrowerBrewer2003](https://www.tandfonline.com/doi/abs/10.1179/000870403235002042): Harrower, Mark, and Cynthia A. Brewer. "ColorBrewer. org: an online tool for selecting colour schemes for maps." *The Cartographic Journal* 40.1 (2003): 27-37. This module provides three functions returning different types of palettes: - **Sequential**: suited to data that ranges from low to high values either on an ordinal scale (e.g. cold, warm, hot) or on a numerical scale - **Diverging**: used when a critical data class or break point needs to be emphasised - **Qualitative**: used for data that does not imply order, but difference in kind Example Usage: ``` access brewer; size(100); pen[] cols = brewer.Qualitative("Paired", 6); fill(unitcircle, cols[0]); ``` Included in this repository is the file `demo.asy` which gives a further example of usage of the module which produces the figure below. ![Colour Demo](https://github.com/seancarmody/asy-brewer/raw/main/images/demo.png) Also included in this repository is `brewer.json` which provides all of the ColorBrewer palettes in [JSON](https://www.json.org/json-en.html) format.
import { TestBed } from '@angular/core/testing'; import { Inject } from '@angular/core'; import { DoneWhen } from '../../../test-helper/doneWhen'; import { Subject } from 'rxjs/Subject'; import { from as fromStatic } from 'rxjs/observable/from'; import { of } from 'rxjs/observable/of'; import { delay, tap, finalize, last, skip, take } from 'rxjs/operators'; import { DATABASE } from '../../app.tokens'; import { DbRefBuilder } from '../../firebase/db-ref-builder'; import { MessageStreamOptimizer } from './message-stream-optimizer'; import { createSkipText } from '../util/skip-helper'; import { MessageKind } from '@machinelabs/models'; let databaseStub; // it's important to recreate the stubs for every test to not // have one test cause side effects for another test function createStubs() { databaseStub = { ref: arg => { return { once: _arg => {}, set: _arg => Promise.resolve(_arg), on: () => {} }; } }; } describe('MessageStreamOptimizer', () => { let db; let messageStreamOptimizer: MessageStreamOptimizer; const partitionSize = 2; const fullFetchTreshold = 6; beforeEach(() => { createStubs(); TestBed.configureTestingModule({ providers: [{ provide: DATABASE, useValue: databaseStub }, DbRefBuilder] }); db = TestBed.get(DbRefBuilder); messageStreamOptimizer = new MessageStreamOptimizer(db, partitionSize, fullFetchTreshold); }); describe('.listenForMessages()', () => { it('should fetch entire messages if message count is below treshold', () => { const availableMessages = [ { kind: MessageKind.Stdout, data: 'some-text', index: 0 }, { kind: MessageKind.Stdout, data: 'other-text', index: 1 }, { kind: MessageKind.Stdout, data: 'other-text', index: 2 }, { kind: MessageKind.Stdout, data: 'other-text', index: 3 }, { kind: MessageKind.ExecutionFinished, data: '', index: 4 } ]; const allMessages = fromStatic(availableMessages); spyOn(messageStreamOptimizer, 'getAllMessages').and.returnValue(allMessages); spyOn(messageStreamOptimizer, 'getTailMessage').and.returnValue(allMessages.pipe(last())); spyOn(messageStreamOptimizer, 'getHeadMessages'); spyOn(messageStreamOptimizer, 'getTailMessages'); spyOn(messageStreamOptimizer, 'getLiveMessages'); const seenMessages = []; messageStreamOptimizer .listenForMessages(1) .pipe( tap(message => seenMessages.push(message)), finalize(() => { expect(availableMessages).toEqual(seenMessages); expect(messageStreamOptimizer.getTailMessage).toHaveBeenCalledTimes(1); expect(messageStreamOptimizer.getAllMessages).toHaveBeenCalledTimes(1); expect(messageStreamOptimizer.getHeadMessages).not.toHaveBeenCalled(); expect(messageStreamOptimizer.getTailMessages).not.toHaveBeenCalled(); }) ) .subscribe(); }); it('should fetch head, tail and live messages if message count is below treshold', done => { const doneWhen = new DoneWhen(done).calledNTimes(1); const availableMessages = [ { kind: MessageKind.Stdout, data: 'some-text', index: 0 }, { kind: MessageKind.Stdout, data: 'other-text', index: 1 }, { kind: MessageKind.Stdout, data: 'other-text', index: 2 }, { kind: MessageKind.Stdout, data: 'other-text', index: 3 }, { kind: MessageKind.Stdout, data: 'other-text', index: 4 }, { kind: MessageKind.Stdout, data: 'other-text', index: 5 }, { kind: MessageKind.Stdout, data: 'other-text', index: 6 }, { kind: MessageKind.Stdout, data: 'other-text', index: 7 }, { kind: MessageKind.Stdout, data: 'other-text', index: 8 } ]; const allMessages = fromStatic(availableMessages); // TODO: This isn't really simulating live messages since they aren't async. const liveMessages = of( { kind: MessageKind.Stdout, data: 'other-text', index: 9 }, { kind: MessageKind.ExecutionFinished, data: '', index: 10 } ).pipe(delay(1000)); spyOn(messageStreamOptimizer, 'getAllMessages').and.returnValue(allMessages); spyOn(messageStreamOptimizer, 'getTailMessage').and.returnValue(allMessages.pipe(last())); spyOn(messageStreamOptimizer, 'getHeadMessages').and.returnValue(allMessages.pipe(take(2))); spyOn(messageStreamOptimizer, 'getTailMessages').and.returnValue(allMessages.pipe(skip(8))); spyOn(messageStreamOptimizer, 'getLiveMessages').and.returnValue(liveMessages); const seenMessages = []; const expectedMessages = [ { kind: MessageKind.Stdout, data: 'some-text', index: 0 }, { kind: MessageKind.Stdout, data: 'other-text', index: 1 }, { kind: MessageKind.Stdout, data: createSkipText(4) }, { kind: MessageKind.Stdout, data: 'other-text', index: 8 }, { kind: MessageKind.Stdout, data: 'other-text', index: 9 }, { kind: MessageKind.ExecutionFinished, data: '', index: 10 } ]; messageStreamOptimizer .listenForMessages(1) .pipe( tap(message => seenMessages.push(message)), finalize(() => { expect(expectedMessages).toEqual(seenMessages); expect(messageStreamOptimizer.getTailMessage).toHaveBeenCalledTimes(1); expect(messageStreamOptimizer.getAllMessages).not.toHaveBeenCalled(); expect(messageStreamOptimizer.getHeadMessages).toHaveBeenCalledTimes(1); expect(messageStreamOptimizer.getTailMessages).toHaveBeenCalledTimes(1); doneWhen.call(); }) ) .subscribe(); }); }); });
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:guess_the_move/bloc/user_settings_bloc.dart'; import 'package:guess_the_move/components/switch_selector.dart'; import 'package:guess_the_move/model/game_mode.dart'; import 'package:guess_the_move/model/live_analysis_response.dart'; import 'package:guess_the_move/screens/game_modes/components/live_analysis/components/game_played_move_feedback.dart'; import 'package:guess_the_move/theme/theme.dart'; class GameLiveAnalysisResults extends StatelessWidget { final GameModeEnum gameMode; final UserSettingsState userSettingsState; final Stream<LiveAnalysisResponse?> liveAnalysisResponseStream; final bool fetchingLiveAnalysisResponse; final bool noMovePlayedYet; final bool liveAnalysisActivated; final String? errorMessage; final Function(bool) onLiveAnalysisSwitchChanged; GameLiveAnalysisResults( {required this.gameMode, required this.userSettingsState, required this.liveAnalysisResponseStream, required this.fetchingLiveAnalysisResponse, required this.noMovePlayedYet, required this.liveAnalysisActivated, required this.errorMessage, required this.onLiveAnalysisSwitchChanged, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return StreamBuilder( stream: liveAnalysisResponseStream, builder: (final BuildContext context, final AsyncSnapshot<LiveAnalysisResponse?> snapshot) { return Container( decoration: BoxDecoration( color: appTheme(context, userSettingsState.userSettings.themeMode).cardBackgroundColor, borderRadius: BorderRadius.circular(10.0), ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: _buildContents(context, snapshot), ), ), ); }, ); } List<Widget> _buildContents(final BuildContext context, final AsyncSnapshot<LiveAnalysisResponse?> snapshot) { if (!liveAnalysisActivated) { return [ SwitchSelector( initialValue: true, title: 'Live-Analyse', padding: const EdgeInsets.only(bottom: 5), titleSize: 16, gameMode: gameMode, onChanged: onLiveAnalysisSwitchChanged, ), Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: Center( child: Text('Die Live-Analyse ist derzeit deaktiviert'), ), ), ]; } if (fetchingLiveAnalysisResponse) { return [ SwitchSelector( initialValue: true, title: 'Live-Analyse', padding: const EdgeInsets.only(bottom: 5), titleSize: 16, gameMode: gameMode, onChanged: onLiveAnalysisSwitchChanged, ), Container(height: 10), Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: CircularProgressIndicator(), ), Container(height: 10), ]; } if (errorMessage != null) { return [ SwitchSelector( initialValue: true, title: 'Live-Analyse', padding: const EdgeInsets.only(bottom: 5), titleSize: 16, gameMode: gameMode, onChanged: onLiveAnalysisSwitchChanged, ), Container(height: 5), Text(errorMessage!, textAlign: TextAlign.justify), ]; } if (!snapshot.hasData || noMovePlayedYet) { return []; } final movePlayed = snapshot.data!.evaluatedMove; return [ SwitchSelector( initialValue: true, title: 'Live-Analyse', padding: const EdgeInsets.all(0), titleSize: 16, gameMode: gameMode, onChanged: onLiveAnalysisSwitchChanged, ), GamePlayedMoveFeedback( gameMode: gameMode, userSettingsState: userSettingsState, move: movePlayed.move, turn: snapshot.data!.turn, moveType: movePlayed.moveType, pv: movePlayed.pv, signedCpScore: movePlayed.signedCPScore, ), ..._buildAlternativeMove(context, snapshot), ]; } List<Widget> _buildAlternativeMove(final BuildContext context, final AsyncSnapshot<LiveAnalysisResponse?> snapshot) { final movePlayed = snapshot.data!.evaluatedMove; final alternativeMove = snapshot.data!.alternativeMoves.where((move) => move != movePlayed).toList(); if (alternativeMove.isEmpty) { return []; } return [ Container(height: 15), Text( 'Alternative', style: TextStyle( color: appTheme(context, userSettingsState.userSettings.themeMode).gameModeThemes[gameMode]!.accentColor, fontWeight: FontWeight.bold, fontSize: 16, ), ), GamePlayedMoveFeedback( gameMode: gameMode, userSettingsState: userSettingsState, move: alternativeMove.first.move, turn: snapshot.data!.turn, moveType: alternativeMove.first.moveType, pv: alternativeMove.first.pv, signedCpScore: alternativeMove.first.signedCPScore, ), ]; } }
rm -rf ./esubot/bin echo Delete //bin successful. rm -rf ./esubot/obj echo Delete //obj successful. echo Now dotnet will publish new version on win-x64. dotnet publish -r win-x64 -c Release
Software Design 2021年4月号 ディープラーニングではじめるソフトウェア高速化入門 第6回 サンプルコード ==== Software Design 2021年4月号掲載の「ディープラーニングではじめるソフトウェア高速化入門 第6回」のサンプルコードです。 ## 動作確認環境 - Ubuntu 18.04 LTS - CUDA Toolkit 10.0 ## ビルド方法 各サブディレクトリ中で `make` コマンドを実行することで対応するプログラムがビルドされます。 ## プログラムの説明と実行方法 ### naive - 愚直に実装されたGPU版行列積です。 - 行列サイズはコマンドライン引数として指定します。 ```shell ./matmul 2048 ``` ### blocking - レジスタブロッキングを行ったGPU版行列積です。 - 行列サイズはコマンドライン引数として指定します。 ```shell ./matmul 2048 ``` ### cublas - cuBLASを利用したGPU版行列積です。 - 行列サイズはコマンドライン引数として指定します。 ```shell ./matmul 2048 ``` ## 作者 - 平櫛 貴章 (株式会社フィックスターズ) ## ライセンス - Apache License 2.0
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace io.daniellanner.indiversity { public class LoadinScreenAnimationWait : CustomYieldInstruction { private bool _done = false; public override bool keepWaiting { get { return !_done; } } public LoadinScreenAnimationWait() { LoadingScreenAnimationDeployer.Done += Callback; } private void Callback() { _done = true; LoadingScreenAnimationDeployer.Done -= Callback; } } }
/** * For pooling objects that can be reused. * @class Pool * @constructor */ export class Pool { objects: any[]; type: any; constructor() { /** * The pooled objects * @property {Array} objects */ this.objects = []; /** * Constructor of the objects * @property {mixed} type */ this.type = Object; } /** * Release an object after use * @method release * @param {Object} obj */ release(...obj: any[]) { const Nargs = obj.length; for (let i = 0; i !== Nargs; i++) { this.objects.push(obj[i]); } return this; } /** * Get an object * @method get * @return {mixed} */ get(): any { if (this.objects.length === 0) { return this.constructObject(); } else { return this.objects.pop(); } } /** * Construct an object. Should be implmented in each subclass. * @method constructObject * @return {mixed} */ constructObject() { throw new Error('constructObject() not implemented in this Pool subclass yet!'); } /** * @method resize * @param {number} size * @return {Pool} Self, for chaining */ resize(size: number) { const objects = this.objects; while (objects.length > size) { objects.pop(); } while (objects.length < size) { objects.push(this.constructObject()); } return this; } }
module CoverMe module Results class << self def read_results(path = CoverMe.config.results.store) data = {} if File.exists?(path) data = eval(File.read(path)) || {} end return data end def merge_results!(cov_results, path = CoverMe.config.results.store) data = CoverMe::Results.read_results(path) cov_results.each do |file, results| if data.has_key?(file) results.each_with_index do |result, i| summed_value = result # default if result.nil? summed_value = data[file][i] elsif !data[file][i].nil? summed_value = data[file][i] + result end data[file][i] = summed_value end else data[file] = results end end File.open(path, 'w') do |f| f.write(data.inspect) end return data end end end # Results end # CoverMe
var express = require('express'); var assetLinks = require('../resources/assetlinks.json'); var appleSiteAssociation = require('../resources/apple-app-site-association.json'); var { makeQrCodeDataUri } = require('../utils/qrcodeUtils'); var router = express.Router(); router.get('/', function (req, res, next) { function isAndroid(userAgent) { return userAgent.toLowerCase().indexOf("android") > -1; } function isIOS(userAgent) { return userAgent.toLowerCase().indexOf("iphone") > -1; } if (req.query.redirect) { return next(); } var userAgent = req.headers['user-agent']; res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); res.header('Expires', '-1'); res.header('Pragma', 'no-cache'); if (isAndroid(userAgent)) { return res.redirect("https://play.google.com/store/apps/details?id=im.status.ethereum"); } else if (isIOS(userAgent)) { return res.redirect("https://testflight.apple.com/join/J8EuJmey"); } return res.redirect("https://status.im"); }); router.get('/health', function(req, res) { res.send('OK'); }); router.get('/.well-known/assetlinks.json', function(req, res) { res.json(assetLinks); }); router.get('/.well-known/apple-app-site-association', function(req, res) { res.json(appleSiteAssociation); }); router.get('/chat/:chatType/:chatId', function(req, res, next) { const { chatId, chatType } = req.params; res.render('index', { title: `Join the ${chatType} chat: #${chatId} in Status`, path: req.originalUrl }); }); router.get('/user/:userId', function(req, res, next) { const { userId } = req.params; const options = { title: `View user ${userId} profile in Status`, path: req.originalUrl, }; makeQrCodeDataUri(userId).then( qrCodeDataUri => res.render('index', { ...options, qrCodeDataUri }), error => res.render('index', options) ); }); router.get('/extension/:extensionEndpoint', function(req, res, next) { const { extensionEndpoint } = req.params; const options = { title: `Open extension ${extensionEndpoint} in Status`, path: req.originalUrl, }; makeQrCodeDataUri('https://get.status.im/extension/' + extensionEndpoint).then( qrCodeDataUri => res.render('index', { ...options, qrCodeDataUri }), error => res.render('index', options) ); }); router.get('/browse/:url(*)', function(req, res, next) { res.render('index', { title: `Browse to ${req.params.url} in Status`, path: req.originalUrl }); }); module.exports = router;
using System; namespace StarWing.Framework { public class GameTime { public TimeSpan SinceLastUpdate { get; } public TimeSpan TotalTime { get; } public GameTime() { SinceLastUpdate = TimeSpan.Zero; TotalTime = TimeSpan.Zero; } public GameTime(TimeSpan sinceLastUpdate, TimeSpan totalTime) { SinceLastUpdate = sinceLastUpdate; TotalTime = totalTime; } } }
package com.example.heroku.repositories; import com.example.heroku.domain.Passenger; import org.springframework.data.jpa.repository.JpaRepository; public interface PassengerRepository extends JpaRepository <Passenger, Long>{ }
import { Component, forwardRef, Input } from '@angular/core'; import { ISipMenuItem } from '../../base/i-sip-menu-item'; import { SipMenuChildren } from './sip-menu-children'; @Component({ selector: 'sip-menu', template: ` <div class="ant-dropdown-menu" [style.width]="width"> <ul nz-menu [nzMode]="mode" [nzTheme]="theme" [nzInlineCollapsed]="inlineCollapsed"> <ng-template #itemtmpl let-item="item"> <li *ngIf="showItem(item)" nz-menu-item [nzSelected]="item.selected" (click)="item.onClick && item.onClick(item)"> <i *ngIf="item.icon" [class]="item.icon"></i>{{item.title}} </li> <li *ngIf="showItemDivider(item)" nz-menu-item-divider></li> </ng-template> <ng-template ngFor let-item [ngForOf]="datas" let-i="index"> <ng-container [ngTemplateOutlet]="itemtmpl" [ngTemplateOutletContext]="{item:item}"></ng-container> <li *ngIf="showItemSub(item)" nz-submenu [nzOpen]="item.open"> <span title (click)="item.onClick && item.onClick(item)"> <i *ngIf="item.icon" [class]="item.icon"></i>{{item.title}} </span> <ul> <ng-template ngFor let-citem [ngForOf]="item.children"> <ng-container [ngTemplateOutlet]="itemtmpl" [ngTemplateOutletContext]="{item:citem}"></ng-container> </ng-template> </ul> </li> <li *ngIf="showItemGroup(item)" nz-menu-group> <span title> <i *ngIf="item.icon" class="anticon {{item.icon}}"></i>{{item.title}} </span> <ul> <ng-template ngFor let-citem [ngForOf]="item.children"> <ng-container [ngTemplateOutlet]="itemtmpl" [ngTemplateOutletContext]="{item:citem}"></ng-container> </ng-template> </ul> </li> </ng-template> </ul> </div> `, styles: [], providers: [{ provide: SipMenuChildren, useExisting: forwardRef(() => SipMenuComponent) }], }) export class SipMenuComponent implements SipMenuChildren { @Input() theme = 'light';// 主题颜色 string: light dark light @Input() mode = 'vertical';// 菜单类型,现在支持垂直、水平、和内嵌模式三种 string: vertical horizontal inline vertical @Input() inlineCollapsed = false;// 控制内嵌菜单的缩起/展开。 Boolean false @Input() width = '130px'; @Input() style: any; private _menuItem: ISipMenuItem; showItem(item: ISipMenuItem) { return !item.disabled && !item.group && !item.divider && !item.children; } showItemSub(item: ISipMenuItem) { return !item.disabled && !item.group && item.children; } showItemGroup(item: ISipMenuItem) { return !item.disabled && item.group; } showItemDivider(item: ISipMenuItem) { return !item.disabled && item.divider; } @Input() datas: ISipMenuItem[] = []; addChild(menu: ISipMenuItem) { this.datas.push(menu); } }
package io.github.jspinak.brobot.actions.methods.sikuliWrappers.mouse; import io.github.jspinak.brobot.actions.BrobotSettings; import io.github.jspinak.brobot.actions.methods.sikuliWrappers.Wait; import io.github.jspinak.brobot.reports.Report; import org.sikuli.script.Mouse; import org.springframework.stereotype.Component; /** * Wrapper class for MouseDown, works for real or mock actions. * Presses and holds a mouse button. */ @Component public class MouseDownWrapper { private ClickType clickType; private final Wait wait; public MouseDownWrapper(ClickType clickType, Wait wait) { this.clickType = clickType; this.wait = wait; } public boolean press(double pauseBeforeBegin, double totalPause, ClickType.Type type) { if (BrobotSettings.mock) { Report.print("<mouse-down>"); // this could be expanded if object clicks are given mock actions if (type != ClickType.Type.LEFT) Report.print(type.name()); Report.print(" "); return true; } wait.wait(pauseBeforeBegin); Mouse.down(clickType.getTypeToSikuliButton().get(type)); wait.wait(totalPause); return true; } }
/** * Class for config graph connections * @param editor which contains graph for config * @constructor */ var GraphConnectionConfig = function (editor) { this.editor = editor; this.graph = editor.graph; }; GraphConnectionConfig.prototype.config = function () { var graph = this.graph; graph.isCellConnectable = this.createIsCellConnectable(); graph.isValidConnection = this.createIsValidConnection(); graph.isCellDisconnectable = this.createIsCellDisconnectable(); graph.connectionHandler.cursor = 'pointer'; graph.connectionHandler.connectImage = new mxImage(app.basePath + OArchitectConstants.CONNECTOR_IMG_PATH, OArchitectConstants.ICON_SIZE, OArchitectConstants.ICON_SIZE); graph.connectionHandler.factoryMethod = this.createConnectionHandlerFactoryMethod(); graph.connectionHandler.createEdgeState = this.createConnectionHandlerCreateEdgeState(); graph.connectionHandler.isConnectableCell = this.createIsCellConnectable(); graph.connectionHandler.createLinkOnConnection = false; graph.connectionHandler.linkConnection = false; graph.connectionHandler.createEdge = this.createConnectionHandlerCreateEdge(); graph.connectionHandler.createIcons = this.createConnectionHandlerCreateIcons(); graph.connectionHandler.redrawIcons = this.createConnectionHandlerRedrawIcons(); graph.connectionHandler.connect = this.createConnectionHandlerConnect(); graph.connectionHandler.validateConnection = function (source, target) { if (source === target && this.createLinkOnConnection) return null; return mxConnectionHandler.prototype.validateConnection.apply(this, arguments); }; graph.connectionHandler.mouseUp = function (sender, me) { if (me == null || me.state == null) this.createLinkOnConnection = false; mxConnectionHandler.prototype.mouseUp.apply(this, arguments); }; this.configEvents(); }; GraphConnectionConfig.prototype.configEvents = function () { this.graph.addListener(mxEvent.CELLS_REMOVED, this.createCellRemovedBehavior()); this.graph.addListener(mxEvent.CELL_CONNECTED, this.createCellConnectedBehavior()); }; GraphConnectionConfig.prototype.createIsCellConnectable = function () { return function (cell) { var connectable = !(!app.canUpdate || cell == null); if (connectable) { connectable = cell.value instanceof OArchitectOClass || cell.value instanceof OArchitectOProperty && cell.value.canConnect(); } return connectable; }; }; GraphConnectionConfig.prototype.createIsCellDisconnectable = function () { return function () { return false; }; }; GraphConnectionConfig.prototype.isCellDeletable = function () { return function (cell) { if (cell.edge && cell.source.value instanceof OArchitectOClass && cell.target.value instanceof OArchitectOClass) return !cell.source.value.existsInDb; return mxGraph.prototype.isCellDeletable.apply(this, arguments); }; }; GraphConnectionConfig.prototype.createIsValidConnection = function () { return function (source, target) { var sourceValue = source.value; var targetValue = target.value; var valid = false; if (sourceValue instanceof OArchitectOClass && targetValue instanceof OArchitectOClass) { valid = !sourceValue.containsSuperClass(targetValue) && !targetValue.containsSuperClass(sourceValue); } else if (sourceValue instanceof OArchitectOProperty && targetValue instanceof OArchitectOClass) { valid = sourceValue.canConnect(); } return valid; }; }; GraphConnectionConfig.prototype.createConnectionHandlerFactoryMethod = function () { var config = this; function getEdgeValue(source, target) { var result = ''; if (source != null && target != null) { var sourceValue = source.value; var targetValue = target.value; if (sourceValue instanceof OArchitectOClass && targetValue instanceof OArchitectOClass) { result = sourceValue.isSuperClassExistsInDb(targetValue) ? OArchitectConstants.SAVED_INHERITANCE : OArchitectConstants.UNSAVED_INHERITANCE; } else if (sourceValue instanceof OArchitectOProperty && targetValue instanceof OArchitectOClass) { result = sourceValue.isLinkExistsInDb(targetValue) ? OArchitectConstants.SAVED_LINK : OArchitectConstants.UNSAVED_LINK; } else if (sourceValue instanceof OArchitectOProperty && targetValue instanceof OArchitectOProperty) { result = sourceValue.isLinkExistsInDb(targetValue.ownerClass) ? OArchitectConstants.SAVED_LINK : OArchitectConstants.UNSAVED_LINK; } } return result; } return function (source, target) { var edge = new mxCell(); edge.setValue(getEdgeValue(source, target)); edge.setEdge(true); edge.setStyle(config.getConnectionStyle(edge.value, source, target)); var geo = new mxGeometry(); geo.relative = true; edge.setGeometry(geo); return edge; }; }; GraphConnectionConfig.prototype.createConnectionHandlerConnect = function () { return function (source, target, evt, dropTarget) { this.currentEvent = evt; if (this.createLinkOnConnection) this.createLinkOnConnection = source.value instanceof OArchitectOClass; mxConnectionHandler.prototype.connect.apply(this, arguments); this.graph.setSelectionCells([]); }; }; GraphConnectionConfig.prototype.createConnectionHandlerCreateEdgeState = function() { return function (me) { if (me.sourceState !== null) { var cell = me.sourceState.cell; var edge = cell !== null ? this.factoryMethod(cell) : this.graph.createEdge(null, null, null, null, null, 'edgeStyle=orthogonalEdgeStyle'); return new mxCellState(this.graph.view, edge, this.graph.getCellStyle(edge)); } return mxConnectionHandler.prototype.createEdge.apply(this, arguments); }; }; GraphConnectionConfig.prototype.createConnectionHandlerCreateIcons = function () { return function (state) { var createLinkIcon = state.cell != null && state.cell.value instanceof OArchitectOClass || state.cell.value instanceof OArchitectOProperty && state.cell.value.isLink(); var icons = state.cell.value instanceof OArchitectOClass ? mxConnectionHandler.prototype.createIcons.apply(this, arguments) : []; if (createLinkIcon) { var image = new mxImage(app.basePath + OArchitectConstants.LINK_IMG_PATH, OArchitectConstants.ICON_SIZE, OArchitectConstants.ICON_SIZE); var bounds = new mxRectangle(0, 0, image.width, image.height); var icon = new mxImageShape(bounds, image.src, null, null, 0); icon.preserveImageAspect = false; icon.init(this.graph.getView().getOverlayPane()); icon.node.style.cursor = mxConstants.CURSOR_CONNECT; var getState = mxUtils.bind(this, function () { return this.currentState != null ? this.currentState : state; }); var mouseDown = mxUtils.bind(this, function (evt) { if (!mxEvent.isConsumed(evt)) { this.icon = icon; this.createLinkOnConnection = true; this.graph.fireMouseEvent(mxEvent.MOUSE_DOWN, new mxMouseEvent(evt, getState())); } }); mxEvent.redirectMouseEvents(icon.node, this.graph, getState, mouseDown); icons.push(icon); this.redrawIcons(icons, state); } return icons; }; }; GraphConnectionConfig.prototype.createConnectionHandlerRedrawIcons = function () { return function (icons, state) { if (icons != null && icons[0] != null && state != null) { var withLinkIcon = icons.length === 2; var pos = this.getIconPosition(icons[0], state); if (withLinkIcon) { initIcon(icons[0], pos.y, pos.x, OArchitectConstants.ICON_SIZE * 4); initIcon(icons[1], pos.y, pos.x, OArchitectConstants.ICON_SIZE); } else initIcon(icons[0], pos.y, pos.x, OArchitectConstants.ICON_SIZE); } function initIcon(icon, y, x, xStep) { icon.bounds.x = x + OArchitectConstants.OCLASS_WIDTH / 2 - xStep; icon.bounds.y = y; icon.redraw(); } }; }; GraphConnectionConfig.prototype.createConnectionHandlerCreateEdge = function () { return function (value, source, target) { var edge = null; if (!this.createLinkOnConnection) { edge = mxConnectionHandler.prototype.createEdge.apply(this, arguments); } else { this.createLinkOnConnection = false; this.linkConnection = true; var state = this.edgeState; var evt = new mxMouseEvent(this.currentEvent, state); this.graph.fireMouseEvent(mxEvent.MOUSE_UP, evt); app.editor.execute(OArchitectActionNames.ADD_OPROPERTY_LINK_ACTION, { "source": source, "target": target, "event": evt }); } return edge; }; }; GraphConnectionConfig.prototype.createCellConnectedBehavior = function () { return function (graph, eventObject) { if (!graph.connectionHandler.linkConnection) { var edge = eventObject.getProperty('edge'); if (edge != null && app.editor.connectionAvailable()) { var source = edge.source; var target = edge.target; if (source != null && target != null) { if (!app.editor.undoOrRedoRuns) { graph.getModel().beginUpdate(); graph.getModel().execute(new OConnectionManageCommand(source, target, false)); graph.getModel().endUpdate(); } } } } else graph.connectionHandler.linkConnection = false; } }; GraphConnectionConfig.prototype.createCellRemovedBehavior = function () { return function (graph, eventObject) { var cells = eventObject.properties.cells; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (cell.edge && app.editor.connectionAvailable()) { if (!app.editor.undoOrRedoRuns) { graph.getModel().beginUpdate(); graph.getModel().execute(new OConnectionManageCommand(cell.source, cell.target, true)); graph.getModel().endUpdate(); } } } } }; GraphConnectionConfig.prototype.getConnectionStyle = function (edgeValue, source, target) { var style = null; if (source.value instanceof OArchitectOClass) { style = this.getOClassConnectionStyle(edgeValue === OArchitectConstants.UNSAVED_INHERITANCE, source); } else if (source.value instanceof OArchitectOProperty && OArchitectOType.isLink(source.value.type)) { style = this.getOPropertyConnectionStyle(source, target); } return style; }; GraphConnectionConfig.prototype.getOClassConnectionStyle = function (createUserInheritance, source) { var style = null; if (createUserInheritance) { style = OArchitectConstants.OCLASS_CONNECTION_STYLE; } else if (source.value instanceof OArchitectOClass) { style = source.value.existsInDb ? OArchitectConstants.OCLASS_EXISTS_CONNECTION_STYLE : OArchitectConstants.OCLASS_CONNECTION_STYLE; } return style; }; GraphConnectionConfig.prototype.getOPropertyConnectionStyle = function (source, target) { var style; if (source.value.existsInDb && source.value.linkedClass !== null && source.value.linkedClass.existsInDb) { if (target.value instanceof OArchitectOClass) { style = source.value.isLinkExistsInDb(target.value) ? OArchitectConstants.OPROPERTY_EXISTS_CONNECTION_STYLE : OArchitectConstants.OPROPERTY_CONNECTION_STYLE; } else { style = source.value.isLinkExistsInDb(target.value.ownerClass) ? OArchitectConstants.OPROPERTY_EXISTS_INVERSE_CONNECTION_STYLE : OArchitectConstants.OPROPERTY_CONNECTION_STYLE; } } else if (target != null && target.value instanceof OArchitectOProperty) { style = OArchitectConstants.OPROPERTY_INVERSE_CONNECTION_STYLE; } else style = OArchitectConstants.OPROPERTY_CONNECTION_STYLE; return style; };
namespace ExCSS { internal sealed class OrientationMediaFeature : MediaFeature { private static readonly IValueConverter TheConverter = Converters.Toggle(Keywords.Portrait, Keywords.Landscape); public OrientationMediaFeature() : base(FeatureNames.Orientation) { } internal override IValueConverter Converter => TheConverter; } }
USE [Certificate_Administration] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ====================================================================== -- Author: John Merkel -- Creation date: October 1, 2021 -- Description: Checks to see if schema and object exists. -- Return: Schema and object names exactly as they appear in -- sys.schemas and sys.objects. -- @object is schema_name.object_name, each quoted. -- Requires: SA -- ====================================================================== CREATE OR ALTER PROCEDURE [Validation].[ValidateSchemaObject] @db_name SYSNAME , @schema_name SYSNAME OUTPUT , @object_name SYSNAME OUTPUT , @raiserror BIT = 1 , @debug BIT = 1 AS SET XACT_ABORT, NOCOUNT ON BEGIN TRY BEGIN TRANSACTION DECLARE @executesql NVARCHAR(350) , @sql_start NVARCHAR(200) , @sql_end NVARCHAR(200) , @sql NVARCHAR(MAX) , @params NVARCHAR(MAX) , @object NVARCHAR(517) = QUOTENAME(@schema_name) + '.' + QUOTENAME(@object_name) -- QUOTENAME() reutrns NVARCHAR(258). -- Multiply by 2 and add 1 for the '.' gives 517. -- Validate db and initialize dynamic variables EXEC [InitDynamicSQL] @db_name OUTPUT , @executesql OUTPUT , @sql_start OUTPUT , @sql_end OUTPUT SELECT @sql = @sql_start + 'SELECT @schema_name = MIN([s].[name]) , @object_name = MIN([o].[name]) FROM [sys].[objects] AS [o] JOIN [sys].[schemas] AS [s] ON [o].[schema_id] = [s].[schema_id] WHERE [o].[object_id] = OBJECT_ID(@object)' + @sql_end , @params = '@schema_name SYSNAME OUTPUT , @object_name SYSNAME OUTPUT , @object NVARCHAR(260)' IF @debug = 1 PRINT '-- Validating object: "' + @object + '"' IF @debug = 1 PRINT @sql EXEC @executesql @sql, @params , @schema_name OUTPUT , @object_name OUTPUT , @object IF @raiserror = 1 AND ( @schema_name IS NULL OR @object_name IS NULL ) RAISERROR('No object %s in database %s.', 16, 1, @object, @db_name) COMMIT TRANSACTION END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION -- In cases there is an error while we are impersonating dbo, we need -- to revert back, which must be done in the user database. IF EXISTS ( SELECT * FROM [sys].[login_token] WHERE [usage] = 'DENY ONLY' ) BEGIN IF @debug = 1 PRINT '-- Error while impersonating dbo, reverting' EXEC @executesql N'REVERT' END ; THROW END CATCH GO
#!/usr/bin/env bash if [ -z ${OTOOL+x} ]; then if which otool&>/dev/null; then OTOOL=$(which otool) elif which aarch64-apple-darwin-otool&>/dev/null; then OTOOL=$(which aarch64-apple-darwin-otool) elif which x86_64-apple-darwin-otool&>/dev/null; then OTOOL=$(which x86_64-apple-darwin-otool) else echo "Install otool" exit 1 fi fi if $(which grep) --version | grep -q GNU&>/dev/null; then GREP=grep elif $(which ggrep) --version | grep -q GNU&>/dev/null; then GREP=$(which ggrep) else echo "Install GNU grep" exit 1 fi if [ -z ${1+x} ]; then echo "Usage: $0 path/to/libs/or/bins" exit 1 fi find ${1} -type f -perm -111 -exec ${OTOOL} -L {} \; | \ ${GREP} -o -P '(?<=lib\/)(.*).*dylib(?!:)' | \ sort -u
# RimWorldModGuide My attempt at a RimWorld guide to assist models. # ([Enter the Guide Here](https://github.com/roxxploxx/RimWorldModGuide/wiki)) Finding this helpful? [Support me on Patreon](https://www.patreon.com/roxxploxx). Thanks!
/** * @author WMXPY * @namespace Neon_Card * @description Racket */ import { Classes } from "jss"; import * as React from "react"; import { ThemedComponent, ThemeProps, withConsumer } from "../#common/consumer"; import { BoxProps } from "../#common/declare"; import { mergeClasses } from "../#common/style/decorator"; import { NeonButton } from "../button/button"; import { SIZE } from "../declare/index"; import { NeonRacketStyle } from "./style/racket"; export type NeonRacketProps = { readonly text?: string; readonly image?: string; readonly size?: SIZE; readonly proportion?: number; } & ThemeProps & BoxProps; const getLeftClass = (style: Classes, size?: SIZE): string => { switch (size) { case SIZE.MEDIUM: return style.leftMedium; case SIZE.LARGE: return style.leftLarge; case SIZE.FULL: return style.leftFull; case SIZE.RELATIVE: return style.leftRelative; case SIZE.NORMAL: default: return style.leftNormal; } }; const getSizeClass = (style: Classes, size?: SIZE): string => { switch (size) { case SIZE.MEDIUM: return style.medium; case SIZE.LARGE: return style.large; case SIZE.FULL: return style.full; case SIZE.RELATIVE: return style.relative; case SIZE.NORMAL: default: return style.normal; } }; export const NeonRacketBase: React.FC<NeonRacketProps> = (props: NeonRacketProps) => { const racketStyle: Classes = NeonRacketStyle.use(); const proportion: number = props.proportion || 3; return (<NeonButton ignoreTheme className={mergeClasses( props.className, racketStyle.box, getSizeClass(racketStyle, props.size), )} size={SIZE.RELATIVE} buttonClassName={racketStyle.button} > <div className={mergeClasses( racketStyle.left, getLeftClass(racketStyle, props.size), )} > <img className={racketStyle.image} src={props.image} alt={props.text} /> </div> <div style={{ flex: proportion }}> {props.text} </div> </NeonButton>); }; export const NeonRacket: ThemedComponent<NeonRacketProps> = withConsumer<NeonRacketProps>(NeonRacketBase);
// SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org> // // SPDX-License-Identifier: Apache-2.0 package main import ( "flag" "fmt" "github.com/spf13/viper" "os" "text/template" ) const yamlAppsTemplate = "{{ printf \"#ONOS Helm Chart Releases\"}}\n\n" + "{{range $key, $value := .Entries }}" + "{{ printf \"## %s\" $key }}\n\n" + "{{range $value}}" + "{{printf \"#### Version **%s**\" .Version}}\n" + "{{printf \"> Generated %s\" .Created}}\n\n" + "{{printf \"App Version **%s**\" .AppVersion}}\n\n" + "{{range .Urls}}" + "{{printf \"[%s](%s)\" . .}}\n" + "{{end}}\n\n" + "{{end}}\n" + "{{end}}\n" type Chart struct { ApiVersion string `yaml:"apiVersion"` AppVersion string `yaml:"appVersion"` Version string `yaml:"version"` Created string `yaml:"created"` Description string `yaml:"description"` Urls []string `yaml:"urls"` } type IndexYaml struct { ApiVersion string `yaml:"apiVersion"` Entries map[string][]Chart `yaml:"entries"` Generated string `yaml:"generated"` } /** * A simple application that takes the generated index.yaml and outputs it in * a Markdown format - usually we pipe this to README.md when in the gh-pages branch */ func main() { file := flag.String("file", "index", "name of YAML file to parse (without extension or path)") flag.Parse() indexYaml, err := getIndexYaml(*file) if err != nil { fmt.Fprintf(os.Stderr, "Unable to load %s.yaml %s\n", *file, err) os.Exit(1) } var tmplAppsList, _ = template.New("yamlAppsTemplate").Parse(yamlAppsTemplate) tmplAppsList.Execute(os.Stdout, indexYaml) } func getIndexYaml(location string) (IndexYaml, error) { indexYaml := &IndexYaml{} viper.SetConfigName(location) viper.AddConfigPath(".") viper.SetConfigType("yaml") if err := viper.ReadInConfig(); err != nil { return IndexYaml{}, err } if err := viper.Unmarshal(indexYaml); err != nil { return IndexYaml{}, err } return *indexYaml, nil }
/* # Derby: start pitcher start batter start timer # PitchingAndBatting: batter active pitcher active { onPitch: deactivate } catcher: catch the ball -> activate batter/pitcher batter: hit the ball -> ball fly ball: land on field -> { show distance for 2 seconds : if timer = 0: end derby else reset batter/pitcher } ball: land out of field -> homerun Homerun:{ show homerun message for a few seconds then back to # pitching and batting : if timer = 0: end derby } */
/* * Copyright 2019 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.leakdetection.controllers import uk.gov.hmrc.leakdetection.ModelFactory._ import org.apache.commons.codec.digest.{HmacAlgorithms, HmacUtils} import org.scalatest.{Matchers, WordSpec} import play.api.libs.json.Json import uk.gov.hmrc.leakdetection.model.{DeleteBranchEvent, PayloadDetails} import scala.concurrent.ExecutionContext class WebhookRequestValidatorSpec extends WordSpec with Matchers { s"Parsing ${PayloadDetails.getClass.getName}" should { "succeed if all required fields are present and deleted field is 'false'" in { val expectedPayloadDetails = aPayloadDetails val validJson = asJson(expectedPayloadDetails) val res = Json.parse(validJson).as[PayloadDetails](PayloadDetails.reads) res shouldBe expectedPayloadDetails res.branchRef should not startWith "refs/heads/" } } s"Parsing ${DeleteBranchEvent.getClass.getName}" should { "succeed if all required fields are present and deleted field is 'true'" in { val expectedDeleteBranchEvent = aDeleteBranchEvent val validJson = asJson(expectedDeleteBranchEvent) val res = Json.parse(validJson).as[DeleteBranchEvent](DeleteBranchEvent.reads) res shouldBe expectedDeleteBranchEvent res.branchRef should not startWith "refs/heads/" } } "Validating payload signature" should { "fail if signature invalid" in new TestSetup { val secret = aString() val payload = aString() val invalidSignature = aString() val res = webhookRequestValidator.isValidSignature(payload, invalidSignature, secret) withClue("Expected a failure for invalid signature") { res shouldBe false } } "succeed if valid" in new TestSetup { val secret = aString() val payload = aString() val validSignature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secret).hmacHex(payload) val res = webhookRequestValidator.isValidSignature(payload, validSignature, secret) withClue("Expected signature validation to succeed") { res shouldBe true } } } trait TestSetup { val webhookRequestValidator = new WebhookRequestValidator()(ExecutionContext.global) } }
# permissions.py from webpie import WPApp, WPHandler, run_server, webmethod import time class H_methods(WPHandler): _Methods = ["hello"] def hello(self, request, relpath): return "Hello, World!\n" def wrong(self, request, relpath): return "This should never happen\n" class H_decorators(WPHandler): @webmethod() def hello(self, request, relpath): return "Hello, World!d\n" @webmethod() def wrong(self, request, relpath): return "This should never happen\n" class H_permissions(WPHandler): def _roles(self, request, relpath): return [relpath] @webmethod(["read","write"]) def read_write(self, request, relpath): return "Read/write access granted\n" @webmethod(["read"]) def read_only(self, request, relpath): return "Read access granted\n" class H_open(WPHandler): def hello(self, request, relpath): return "Hello, World!\n" def wrong(self, request, relpath): return "This should never happen\n" class Top(WPHandler): def __init__(self, *params): WPHandler.__init__(self, *params) self.o = H_open(req, app, path) self.m = H_methods(req, app, path) self.d = H_decorators(req, app, path) self.p = H_permissions(req, app, path) application = WPApp(Top, strict=True) application.run_server(8080)
# Worder A chrome extension for [Cambridge Learner's Dictionary](http://dictionary.cambridge.org/dictionary/learner-english/)
#include<GL/gl.h> #include<GL/glx.h> #include<X11/Xlib.h> #include<stdlib.h> #include<stdio.h> main() { Display *dpy=XOpenDisplay(NULL); int screen=DefaultScreen(dpy); int errorcode[10],eventcode[10]; printf("%d\n",glXQueryExtension(dpy,errorcode,eventcode)); printf("%s\n",glXQueryExtensionsString(dpy,screen)); int nelements; GLXFBConfig *get=glXGetFBConfigs(dpy,screen,&nelements); printf("%d\n",nelements); int attriblist[1]={GLX_WINDOW_BIT}; GLXFBConfig *choose=glXChooseFBConfig(dpy,screen,attriblist,&nelements); printf("%d\n",nelements); Window parent=RootWindow(dpy,screen); GLXWindow win=glXCreateWindow(dpy,choose[0],parent,attriblist); //GLXWindow win=glXCreateWindow(dpy,,win,); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0,1.0,1.0); glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0); glBegin(GL_POLYGON); glVertex2f(-0.5,-0.5); glVertex2f(-0.5,0.5); glVertex2f(0.5,0.5); glVertex2f(0.5,-0.5); glEnd(); glFlush(); //glXDestroyWindow(dpy,win); }
--- layout: watch title: TLP4 - 15/05/2019 - M20190515_050914_TLP_4T.jpg date: 2019-05-15 05:09:14 permalink: /2019/05/15/watch/M20190515_050914_TLP_4 capture: TLP4/2019/201905/20190514/M20190515_050914_TLP_4T.jpg ---
# frozen_string_literal: true module Devise module Sso module Controllers # Those helpers are convenience methods added to ApplicationController. module Helpers def authenticate_sso! return if sso_resource_signed_in? respond_to do |format| format.html { redirect_to sso_login_url } format.js { render js: "window.location.href='#{sso_login_url}';" } end end def sso_resource_signed_in? current_sso_resource.present? end def current_sso_resource return unless defined?(cookies) @current_sso_resource ||= Devise::Sso::Authentication.find(cookies[Devise::Sso.session_key]) end def sso_login_url Devise::Sso::UrlBuilder.new( host: ENV.fetch('SSO_HOST'), port: ENV.fetch('SSO_PORT'), path: ENV.fetch('SSO_LOGIN_PATH', 'sso/sessions/login'), query: { sso_redirect: sso_redirect_location } ).to_s end def sso_redirect_location session[:sso_redirect] || request.url end def sso_logout_url Devise::Sso::UrlBuilder.new( host: ENV.fetch('SSO_HOST'), port: ENV.fetch('SSO_PORT'), path: ENV.fetch('SSO_LOGOUT_PATH', 'sso/sessions/logout') ).to_s end end end end end
import assert from "assert"; import { extract } from "../../../src/core/scrapers.js"; describe("Scraper: StarGR", function () { it("should return URL when it's not a video", async function () { const url = new URL("https://www.star.gr/lifestyle/media"); const options = { depth: false, incognito: false }; const file = await extract(url, options); assert.strictEqual(file, url.href); }); it("should return video URL", async function () { const url = new URL("https://www.star.gr/video/lifestyle/viral/538100"); const options = { depth: false, incognito: false }; const file = await extract(url, options); assert.ok(file?.startsWith("https://cdnapisec.kaltura.com/p/713821/sp" + "/0/playManifest/entryId/1_n0gatj56/format/applehttp" + "/protocol/https/flavorParamId/0/manifest.m3u8"), `"${file}"?.startsWith(...)`); }); it("should return video URL from StarTV", async function () { const url = new URL("https://www.star.gr/tv/enimerosi" + "/kedriko-deltio-eidiseon/kedriko-deltio-eidiseon-3132021/"); const options = { depth: false, incognito: false }; const file = await extract(url, options); assert.ok(file?.startsWith("https://cdnapisec.kaltura.com/p/713821/sp" + "/0/playManifest/entryId/1_uscdf5as/format/applehttp" + "/protocol/https/flavorParamId/0/manifest.m3u8"), `"${file}"?.startsWith(...)`); }); it("should return video URL from StarTV when protocol is HTTP", async function () { const url = new URL("http://www.star.gr/tv/psychagogia" + "/sti-folia-ton-kou-kou/bolonez-garidas-932021/"); const options = { depth: false, incognito: false }; const file = await extract(url, options); assert.ok(file?.startsWith("https://cdnapisec.kaltura.com/p/713821/sp" + "/0/playManifest/entryId/1_ocn00cdc/format/applehttp" + "/protocol/https/flavorParamId/0/manifest.m3u8"), `"${file}"?.startsWith(...)`); }); it("should return video id [stargr-youtube]", async function () { const url = new URL("https://www.star.gr/tv/psychagogia" + "/ston-kosmo-tou/ston-kosmo-tou-2042019-tiflida/"); const options = { depth: false, incognito: false }; const file = await extract(url, options); assert.ok(file?.startsWith("plugin://plugin.video.youtube/play/" + "?video_id=p9DYioRLAXE&incognito=false"), `"${file}"?.startsWith(...)`); }); });
export const addCommas = (value: string): string => value.replace(/\B(?=(\d{3})+(?!\d))/g, ','); export const removeCommas = (value: string): string => value.replace(/,/g, ''); export const checkIsValidNumber = (input: string): boolean => { if (Number(input) < 0 || isNaN(Number(input))) { return false; } return true; }; /** * Remove prefix, commas and extra decimals from value */ export const cleanValue = ( value: string, allowDecimals: boolean, decimalsLimit: number, prefix?: string ): string => { const withoutPrefix = prefix ? value.replace(prefix, '') : value; const withoutCommas = removeCommas(withoutPrefix); if (withoutCommas.includes('.')) { const [int, decimals] = withoutCommas.split('.'); const includeDecimals = allowDecimals ? `.${decimalsLimit ? decimals.slice(0, decimalsLimit) : decimals}` : ''; return `${int}${includeDecimals}`; } return withoutCommas; }; /** * Format value with commas and prefix */ export const formatValue = (value: string, prefix?: string): string => { const [int, decimals] = value.split('.'); const includePrefix = prefix ? prefix : ''; const includeDecimals = value.includes('.') ? `.${decimals}` : ''; return `${includePrefix}${addCommas(int)}${includeDecimals}`; };
# ${StrFilter} * Convert string to uppercase or lowercase. * Set symbol filter. ## Syntax ${StrFilter} "[string]" "[options]" "[symbols1]" "[symbols2]" $var "[string]" ;[string] ; input string ; "[options]" ;[+|-][1|2|3|12|23|31][eng|rus] ; + : convert string to uppercase ; - : convert string to lowercase ; 1 : only Digits ; 2 : only Letters ; 3 : only Special ; 12 : only Digits + Letters ; 23 : only Letters + Special ; 31 : only Special + Digits ; eng : English symbols (default) ; rus : Russian symbols ; "[symbols1]" ;[symbols1] ; symbols include (not changeable) ; "[symbols2]" ;[symbols2] ; symbols exclude ; $var ;output (result) Note: - Error flag if syntax error - Same symbol to include & to exclude = to exclude ## Examples ### UpperCas Section ${StrFilter} "123abc 456DEF 7890|%#" "+" "" "" $R0 ; $R0="123ABC 456DEF 7890|%#" SectionEnd ### LowerCase Section ${StrFilter} "123abc 456DEF 7890|%#" "-" "ef" "" $R0 ; $R0="123abc 456dEF 7890|%#" SectionEnd ### Filter 1 Section ${StrFilter} "123abc 456DEF 7890|%#" "2" "|%" "" $R0 ; $R0="abcDEF|%" ;only Letters + |% SectionEnd ### Filter 2 Section ${StrFilter} "123abc 456DEF 7890|%#" "13" "af" "4590" $R0 ; $R0="123a 6F 78|%#" ;only Digits + Special + af - 4590 SectionEnd ### Filter 3 Section ${StrFilter} "123abc 456DEF 7890|%#" "+12" "b" "def" $R0 ; $R0="123AbC4567890" ;only Digits + Letters + b - def SectionEnd ### Filter 4 Section ${StrFilter} "123abcÀÁÂ 456DEFãäå 7890|%#" "+12rus" "ä" "ãå" $R0 ; $R0="123ÀÁÂ456ä7890" ;only Digits + Letters + ä - ãå SectionEnd ### English + Russian Letters Section ${StrFilter} "123abcÀÁÂ 456DEFãäå 7890|%#" "2rus" "" "" $R0 ; $R0="ÀÁÂãäå" ;only Russian Letters ${StrFilter} "123abcÀÁÂ 456DEFãäå 7890|%#" "2" "$R0" "" $R0 ; $R0="abcÀÁÂDEFãäå" ;only English + Russian Letters SectionEnd ### Word Capitalize Section Push "_01-PERPETUOUS_DREAMER__-__THE_SOUND_OF_GOODBYE_(ORIG._MIX).MP3_" Call Capitalize Pop $R0 ; $R0="_01-Perpetuous_Dreamer__-__The_Sound_Of_Goodbye_(Orig._Mix).mp3_" ${WordReplace} "$R0" "_" " " "+*" $R0 ; $R0=" 01-Perpetuous Dreamer - The Sound Of Goodbye (Orig. Mix).mp3 " ${WordReplace} "$R0" " " "" "{}" $R0 ; $R0="01-Perpetuous Dreamer - The Sound Of Goodbye (Orig. Mix).mp3" SectionEnd Function Capitalize Exch $R0 Push $0 Push $1 Push $2 ${StrFilter} '$R0' '-eng' '' '' $R0 ${StrFilter} '$R0' '-rus' '' '' $R0 StrCpy $0 0 loop: IntOp $0 $0 + 1 StrCpy $1 $R0 1 $0 StrCmp $1 '' end StrCmp $1 ' ' +5 StrCmp $1 '_' +4 StrCmp $1 '-' +3 StrCmp $1 '(' +2 StrCmp $1 '[' 0 loop IntOp $0 $0 + 1 StrCpy $1 $R0 1 $0 StrCmp $1 '' end ${StrFilter} '$1' '+eng' '' '' $1 ${StrFilter} '$1' '+rus' '' '' $1 StrCpy $2 $R0 $0 IntOp $0 $0 + 1 StrCpy $R0 $R0 '' $0 IntOp $0 $0 - 2 StrCpy $R0 '$2$1$R0' goto loop end: Pop $2 Pop $1 Pop $0 Exch $R0 FunctionEnd ## Credits Written by [Instructor][1] [1]: http://nsis.sourceforge.net/User:Instructor
using System; using System.Threading.Tasks; using ProcessControl.Industry; using ProcessControl.Jobs; using ProcessControl.Tools; using UnityEngine; public class ConstructionSite : MonoBehaviour, Buildable { public bool Assembled => this.enabled; [SerializeField] private Recipe constructionRecipe; public Recipe recipe => constructionRecipe; public async Task Deliver(Stack stack, float deliveryTime) { await Alerp.Delay(deliveryTime); } public async Task Build(float buildTime) { await Alerp.Delay(buildTime); enabled = true; } public async Task Disassemble(float deconstructionTime) { await Alerp.Delay(deconstructionTime); Destroy(this); } }
#!/bin/sh eval $(docker-machine env workshop-manager) docker swarm init --advertise-addr $(docker-machine ip workshop-manager) eval $(docker-machine env workshop-manager) export TOKEN=$(docker swarm join-token worker -q) eval $(docker-machine env workshop-worker1) docker swarm join --token $TOKEN $(docker-machine ip workshop-manager):2377 eval $(docker-machine env workshop-worker2) docker swarm join --token $TOKEN $(docker-machine ip workshop-manager):2377 eval $(docker-machine env workshop-manager) export NODE=$(docker node ls -q --filter "name=workshop-worker1") docker node update --label-add zone=a $NODE export NODE=$(docker node ls -q --filter "name=workshop-worker2") docker node update --label-add zone=b $NODE
package com.prateekj.snooper.formatter import com.prateekj.snooper.utils.TestUtilities.readFrom import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat import org.junit.Test class JsonResponseFormatterTest { @Test @Throws(Exception::class) fun shouldReturnFormattedJsonObject() { val formatter = JsonResponseFormatter() val formattedResponse = formatter.format(readFrom("person_details_raw_response.json")) val expectedResponse = readFrom("person_details_formatted_response.json") assertThat(formattedResponse, `is`<String>(expectedResponse)) } @Test @Throws(Exception::class) fun shouldReturnFormattedJsonArray() { val formatter = JsonResponseFormatter() val formattedResponse = formatter.format(readFrom("person_details_raw_array_response.json")) val expectedResponse = readFrom("person_details_formatted_array_response.json") assertThat(formattedResponse, `is`<String>(expectedResponse)) } @Test @Throws(Exception::class) fun shouldReturnSameResponseWhenExceptionOccurs() { val formatter = JsonResponseFormatter() val invalidJSON = "{\"value\":\"Invalid JSON\", \"value\"}" val formattedResponse = formatter.format(invalidJSON) assertThat(formattedResponse, `is`(invalidJSON)) } }
package io.gitlab.arturbosch.grovlin.parser import io.gitlab.arturbosch.grovlin.GrovlinParser import org.assertj.core.api.Assertions import org.junit.Test /** * @author Artur Bosch */ class ReturnTest { @Test fun simpleReturnStmt() { val returnStmt = "return 5".parseStatement() as GrovlinParser.ReturnStatementContext Assertions.assertThat(returnStmt.returnStmt().expression()) .isInstanceOf(GrovlinParser.IntLiteralContext::class.java) } }
//====================================================================== /*! \file IbeoSdkTrackingBoxLiveDemo.cpp * * \copydoc Copyright * \author Jan Christian Dittmer (jcd) * \date Oct 23, 2015 * * Demo project for connecting to a LUX and process the received * data blocks. *///------------------------------------------------------------------- #include <ibeosdk/trackingbox.hpp> #include <ibeosdk/IpHelper.hpp> #include <ibeosdk/datablocks/commands/CommandEcuAppBaseStatus.hpp> #include <ibeosdk/datablocks/commands/ReplyEcuAppBaseStatus.hpp> #include <ibeosdk/datablocks/commands/CommandEcuAppBaseCtrl.hpp> #include <ibeosdk/datablocks/commands/EmptyCommandReply.hpp> #include <iostream> #include <cstdlib> //====================================================================== using namespace ibeosdk; //====================================================================== const ibeosdk::Version::MajorVersion majorVersion(5); const ibeosdk::Version::MinorVersion minorVersion(2); const ibeosdk::Version::Revision revision(2); const ibeosdk::Version::PatchLevel patchLevel; const ibeosdk::Version::Build build; const std::string info = "IbeoSdkTrackingBoxLiveDemo"; ibeosdk::Version appVersion(majorVersion, minorVersion, revision, patchLevel, build, info); IbeoSDK ibeoSDK; //====================================================================== void live_demo(LogFileManager& logFileManager, std::string ip); //====================================================================== TimeConversion tc; //====================================================================== class AllTrackingBoxListener : public ibeosdk::DataListener<ScanLux>, public ibeosdk::DataListener<ObjectListLux>, public ibeosdk::DataListener<VehicleStateBasicLux>, public ibeosdk::DataListener<LogMessageError>, public ibeosdk::DataListener<LogMessageDebug>, public ibeosdk::DataListener<LogMessageNote>, public ibeosdk::DataListener<LogMessageWarning> { public: virtual ~AllTrackingBoxListener() {} public: //======================================== void onData(const ScanLux* const scan) { logInfo << "Scan received: # " << scan->getScanNumber() <<" time: " << tc.toString(scan->getStartTimestamp().toPtime(), 3) << std::endl; } //======================================== void onData(const ObjectListLux* const pObj) { logInfo << "Objects received: # " << pObj->getNumberOfObjects() << std::endl; } //======================================== void onData(const VehicleStateBasicLux* const vsb) { logInfo << "VSB for Scan #: " << vsb->getScanNumber() << " " << tc.toString(vsb->getTimestamp().toPtime()) << std::endl; } //======================================== virtual void onData(const LogMessageError* const logMsg) { logInfo << std::setw(5) << logMsg->getSerializedSize() << " Bytes " << "LogMessage (Error) received: time: " << logMsg->getTraceLevel() << ": " << logMsg->getMessage() << std::endl; } //======================================== virtual void onData(const LogMessageWarning* const logMsg) { logInfo << std::setw(5) << logMsg->getSerializedSize() << " Bytes " << "LogMessage (Warning) received: time: " << logMsg->getTraceLevel() << ": " << logMsg->getMessage() << std::endl; } //======================================== virtual void onData(const LogMessageNote* const logMsg) { logInfo << std::setw(5) << logMsg->getSerializedSize() << " Bytes " << "LogMessage (Note) received: time: " << logMsg->getTraceLevel() << ": " << logMsg->getMessage() << std::endl; } //======================================== virtual void onData(const LogMessageDebug* const logMsg) { logInfo << std::setw(5) << logMsg->getSerializedSize() << " Bytes " << "LogMessage (Debug) received: time: " << logMsg->getTraceLevel() << ": " << logMsg->getMessage() << std::endl; } }; // AllTrackingBoxListener //====================================================================== //====================================================================== //====================================================================== int checkArguments(const int argc, const char** argv, bool& hasLogFile) { const int minNbOfNeededArguments = 2; const int maxNbOfNeededArguments = 3; bool wrongNbOfArguments = false; if (argc < minNbOfNeededArguments) { std::cerr << "Missing argument" << std::endl; wrongNbOfArguments = true; } else if (argc > maxNbOfNeededArguments) { std::cerr << "Too many argument" << std::endl; wrongNbOfArguments = true; } if (wrongNbOfArguments) { std::cerr << argv[0] << " " << " IP [LOGFILE]" << std::endl; std::cerr << "\tIP is the ip address of the LUX sensor, e.g. 192.168.0.1." << std::endl; std::cerr << "\tLOGFILE name of the log file. If ommitted, the log output will be performed to stderr." << std::endl; return 1; } hasLogFile = (argc == maxNbOfNeededArguments); return 0; } //====================================================================== int main(const int argc, const char** argv) { std::cerr << argv[0] << " Version " << appVersion.toString(); std::cerr << " using IbeoSDK " << ibeoSDK.getVersion().toString() << std::endl; bool hasLogFile; const int checkResult = checkArguments(argc, argv, hasLogFile); if (checkResult != 0) exit(checkResult); int currArg = 1; std::string ip = argv[currArg++]; const off_t maxLogFileSize = 1000000; LogFileManager logFileManager; ibeosdk::LogFile::setTargetFileSize(maxLogFileSize); if (hasLogFile) { ibeosdk::LogFile::setLogFileBaseName(argv[currArg++]); } const ibeosdk::LogLevel ll = ibeosdk::logLevelFromString("Debug"); ibeosdk::LogFile::setLogLevel(ll); logFileManager.start(); if (hasLogFile) { logInfo << argv[0] << " Version " << appVersion.toString() << " using IbeoSDK " << ibeoSDK.getVersion().toString() << std::endl; } live_demo(logFileManager, ip); exit(0); } //====================================================================== void live_demo(LogFileManager& logFileManager, std::string ip) { AllTrackingBoxListener allListener; const uint16_t port = getPort(ip, 12002); IbeoTrackingBox trackingBox(ip, port); trackingBox.setLogFileManager(&logFileManager); trackingBox.registerListener(&allListener); trackingBox.getConnected(); // Just to keep the program alive while (true) { if (!trackingBox.isConnected()) return; # ifdef _WIN32 ::Sleep(1); # else // _WIN32 sleep(1); # endif // _WIN32 } } //======================================================================
class Mixlr < Cask url 'http://cdn.mixlr.com/Mixlr_beta_latest.pkg' homepage 'http://mixlr.com' version 'latest' sha256 :no_check install 'Mixlr_beta_latest.pkg' uninstall :pkgutil => 'com.mixlr.Mixlr' end
import odrive from odrive.enums import * from odrive.utils import dump_errors import time class OdriveInterface: def __init__(self): # CONSTANTS self.MIN_MOTOR_RADS = 104 # So min wheel speed is ~50 RPM self.MAX_MOTOR_RADS = 471 # So max wheel speed is ~200 RPM self.MAX_EFFORT = 20 # Encoder counts per radian the MOTOR has turned self.ENCODER_COUNTS_PER_RAD = 4000 / (2 * 3.1415926) # Encoder counts from the wheels self._encoder_counts = [0, 0] # Find the Odrive - block until received print("\033[1;31mWaiting for Odrive...\033[0m") self._odrv = odrive.find_any() print("\033[1;32m...Found Odrive\033[0m") # Do initial callibration self._odrv.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE self._odrv.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE while (self._odrv.axis0.current_state != AXIS_STATE_IDLE and self._odrv.axis1.current_state != AXIS_STATE_IDLE): time.sleep(0.1) if self._odrv.axis0.error != 0x00 or self._odrv.axis1.error != 0x00: dump_errors(self._odrv, True) raise RuntimeError("Failed to calibrate axis") # Set ourselves to the reset state self.reset(); # Ensure that we're in velocity control self._odrv.axis0.controller.config.control_mode = CTRL_MODE_VELOCITY_CONTROL self._odrv.axis1.controller.config.control_mode = CTRL_MODE_VELOCITY_CONTROL self._ctrl_modes = [CTRL_MODE_VELOCITY_CONTROL, CTRL_MODE_VELOCITY_CONTROL] # Set reset state, where motors are un-powered def reset(self): self._odrv.axis0.requested_state = AXIS_STATE_IDLE self._odrv.axis1.requested_state = AXIS_STATE_IDLE self._odrv.axis0.controller.vel_setpoint = 0 self._odrv.axis1.controller.vel_setpoint = 0 self.clear_errors() # Release the odrive from reset, powering on the motors def release_reset(self): # Prepare for new match self._odrv.axis0.encoder.shadow_count = 0 self._odrv.axis1.encoder.shadow_count = 0 self._odrv.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL self._odrv.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL # Read the wheel velocity in radians per second def get_wheel_vel(self, axis, dt): old_encoder_counts = self._encoder_counts[axis] if axis == 0: self._encoder_counts[axis] = self._odrv.axis0.encoder.shadow_count else: self._encoder_counts[axis] = self._odrv.axis1.encoder.shadow_count delta = self._encoder_counts[axis] - old_encoder_counts wheel_vel = delta / (dt * self.ENCODER_COUNTS_PER_RAD * 20) return wheel_vel # Set the wheel velocity in radians per second def set_wheel_vel(self, axis, vel): # Convert wheel velocity into motor velocity vel *= 20 if vel < self.MIN_MOTOR_RADS: vel = 0 elif vel > self.MAX_MOTOR_RADS: vel = self.MAX_MOTOR_RADS if self._ctrl_modes[axis] != CTRL_MODE_VELOCITY_CONTROL: self._ctrl_modes[axis] = CTRL_MODE_VELOCITY_CONTROL if axis == 0: self._odrv.axis0.controller.config.control_mode = CTRL_MODE_VELOCITY_CONTROL else: self._odrv.axis1.controller.config.control_mode = CTRL_MODE_VELOCITY_CONTROL if axis == 0: self._odrv.axis0.controller.vel_setpoint = vel * self.ENCODER_COUNTS_PER_RAD else: self._odrv.axis1.controller.vel_setpoint = vel * self.ENCODER_COUNTS_PER_RAD # Read the battery voltage def get_battery_voltage(self): return self._odrv.vbus_voltage # Set the effort(current) applied to the wheel def set_wheel_eff(self, axis, eff): if eff > self.MAX_EFFORT: eff = self.MAX_EFFORT elif eff < -self.MAX_EFFORT: eff = -self.MAX_EFFORT if self._ctrl_modes[axis] != CTRL_MODE_CURRENT_CONTROL: self._ctrl_modes[axis] = CTRL_MODE_CURRENT_CONTROL if axis == 0: self._odrv.axis0.controller.config.control_mode = CTRL_MODE_CURRENT_CONTROL else: self._odrv.axis1.controller.config.control_mode = CTRL_MODE_CURRENT_CONTROL if axis == 0: self._odrv.axis0.controller.current_setpoint = eff else: self._odrv.axis1.controller.current_setpoint = eff # Read the effort(current) applied to the wheel def get_wheel_eff(self, axis): B = 0 C = 0 if axis == 0: B = self._odrv.axis0.motor.current_meas_phB C = self._odrv.axis0.motor.current_meas_phC else: B = self._odrv.axis1.motor.current_meas_phB C = self._odrv.axis1.motor.current_meas_phC if abs(B) > abs(C): return B return C def check_errors(self): if self._odrv.axis0.error != 0x00: return True if self._odrv.axis1.error != 0x00: return True return False def clear_errors(self): dump_errors(self._odrv, True)
# Reloading class Main unless production? FileUtils.mkdir_p Aura.root('tmp/') FileUtils.touch Aura.root('tmp/restart.txt') use(Pistol, app_files + [Aura.root('tmp/restart.txt')]) { reset! and load(ENV['APP_FILE']) } end end
;;; -*- mode: lisp; package: jnil.lib -*- ;;; Copyright (c) 2004-2005 Tiago Maduro-Dias. All Rights Reserved. ;;; ;;; This code is free software; you can redistribute it and/or ;;; modify it under the terms of the version 2.1 of ;;; the GNU Lesser General Public License as published by ;;; the Free Software Foundation, as clarified by the preamble ;;; found in license-llgpl.txt. ;;; ;;; This code is distributed in the hope that it will be useful, ;;; but without any warranty; without even the implied warranty of ;;; merchantability or fitness for a particular purpose. See the GNU ;;; Lesser General Public License for more details. ;;; ;;; Version 2.1 of the GNU Lesser General Public License is in the file ;;; license-lgpl.txt that was distributed with this file. ;;; If it is not present, you can access it from ;;; http://www.gnu.org/copyleft/lesser.txt (until superseded by a newer ;;; version) or write to the Free Software Foundation, Inc., 59 Temple Place, ;;; Suite 330, Boston, MA 02111-1307 USA ;;; ;;; $Id: utils.lisp,v 1.1.1.1 2006/04/23 17:11:48 tdias Exp $ ;;; ;;; Description: General utility utils. Used when the switch :support-utils is active. ;;; ;;; -- start of utils.lisp -- (defpackage :jnil.lib) (in-package :jnil.lib) (defmacro >>> (form shift) `(mask-field (byte (- 32 ,shift) 0) (ash ,form (- ,shift)))) (defmacro post-incf (form) `(prog1 ,form (incf ,form))) (defmacro post-decf (form) `(prog1 ,form (decf ,form))) (defun make-initialized-instance (class &optional initializer &rest args) (let ((inst (make-instance class))) (when initializer (apply initializer inst args)) inst)) (defun make-vector-matrix (dimensions &rest args) (if (and (listp dimensions) (rest dimensions)) (make-array (first dimensions) :initial-contents (loop for i from 1 upto (first dimensions) collect (apply #'make-vector-matrix (rest dimensions) args))) (apply #'make-array dimensions args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; symbols are exported here ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval-when (:compile-toplevel :load-toplevel :execute) (export '(>>> post-incf post-decf make-initialized-instance make-vector-matrix) 'jnil.lib)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; other miscellaneous operations ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; --- end of utils.lisp --
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\HomeController; use App\Http\Controllers\PatientController; use App\Http\Controllers\UserController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ /* Route::get('/', function () { return view('index'); }); */ Route::get('/', function () { return view('connexion'); }); Route::post('check', [UserController::class, 'check'])->name('check'); Route::group(['middleware' => ['logged']], function () { Route::get('index', [UserController::class, 'index']); Route::get('/logout', [UserController::class, 'logout']); Route::get('create_patient', [PatientController::class, 'create']); Route::get('show_patient/{patient}', [PatientController::class, 'show']); Route::get('create_consultation/{patient}', [PatientController::class, 'create_consultation']); Route::post('store_patient', [PatientController::class, 'store']); Route::post('/store_consultation', [PatientController::class, 'store_consultation']); Route::get('getConsultation', [PatientController::class, 'getConsultation'])->name('getConsultation'); Route::get('edit_patient/{patient}', [PatientController::class, 'edit']); Route::put('update_patient/{patient}', [PatientController::class, 'update']); Route::get('edit_consultation/{id}', [PatientController::class, 'edit_consultation']); Route::put('update_consultation/{consultation}', [PatientController::class, 'update_consultation']); });
%%==================================================================== %% Copyright (c) 2011, David Haglund %% 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. %%==================================================================== %% @author David Haglund %% @copyright 2011, David Haglund %% @doc %% %% @end -module(breeze_generating_worker_tests). -include_lib("eunit/include/eunit.hrl"). -compile(export_all). % used by pc_tests_common -export([tested_module/0]). -export([create_mock/0]). % Exported functions tested_module() -> breeze_generating_worker. create_mock() -> Mock = generating_worker_mock, meck:new(Mock), meck:expect(Mock, init, fun(State) -> {ok, State} end), meck:expect(Mock, generate, fun(_EmitFun, State) -> {ok, State} end), meck:expect(Mock, terminate, fun(_Reason, State) -> State end), Mock. % Tests in pc_tests_common start_stop_test() -> pc_tests_common:test_start_stop(?MODULE), ok. should_return_the_state_in_stop_test() -> pc_tests_common:should_return_the_state_in_stop(?MODULE), ok. should_call_terminate_on_stop_test() -> pc_tests_common:should_call_terminate_on_stop(?MODULE), ok. behaviour_info_test() -> Expected = [{init, 1}, {generate, 2}, {terminate, 2}], pc_tests_common:test_behaviour_info(?MODULE, Expected), ok. validate_module_test() -> pc_tests_common:validate_module(?MODULE), ok. mocked_tests_test_() -> pc_tests_common:mocked_tests(?MODULE). verify_emitted_message_is_multicasted_to_all_targets_test() -> verify_emitted_message_is_sent_to_all_targets(multicast, all), ok. verify_emitted_message_is_random_casted_to_all_targets_test() -> verify_emitted_message_is_sent_to_all_targets(random_cast, random), ok. verify_emitted_message_is_keyhash_casted_to_all_targets_test() -> verify_emitted_message_is_sent_to_all_targets(keyhash_cast, keyhash), ok. verify_emitted_message_is_dynamically_casted_to_all_targets_test() -> verify_emitted_message_is_sent_to_all_targets(dynamic_cast, dynamic), ok. verify_emitted_message_is_sent_to_all_targets(EpcEmitFunc, DistributionKey) -> Msg = {foo, bar}, EmitTriggerFun = fun(_Pid) -> noop end, EmitTriggerMock = make_emitting_generate_mock(Msg), pc_tests_common:verify_emitted_message_is_sent_to_all_targets( ?MODULE, EmitTriggerMock, EmitTriggerFun, Msg, EpcEmitFunc, DistributionKey). % Local tests should_set_the_timer_after_every_message_test_() -> {foreach, fun setup_timer_tests/0, fun teardown_timer_tests/1, [{with, [T]} || T <- [ fun ?MODULE:should_have_timeout_after_init_/1, fun ?MODULE:should_have_timeout_after_timeout_/1, fun ?MODULE:should_have_timeout_after_sync_/1, fun ?MODULE:should_have_timeout_after_handle_call_/1, fun ?MODULE:should_have_timeout_after_handle_cast_/1, fun ?MODULE:should_have_timeout_after_handle_info_/1 ] ]}. should_have_timeout_after_init_([_Pid, Target, Msg | _]) -> verify_continuous_timeouts(Target, Msg), ok. should_have_timeout_after_timeout_([Pid, Target, Msg | _]) -> breeze_generating_worker:sync(Pid), PreCount = meck:num_calls(breeze_worker_controller, multicast, [Target, Msg]), timer:sleep(1), % enough time to make a number of calls % The counter must increase with more then one, since increase % with only one indicate no timeout after handling timeout. ?assert((PreCount + 1) < meck:num_calls( breeze_worker_controller, multicast, [Target, Msg])). should_have_timeout_after_sync_([Pid, Target, Msg | _]) -> breeze_generating_worker:sync(Pid), verify_continuous_timeouts(Target, Msg), ok. should_have_timeout_after_handle_call_([Pid, Target, Msg | _]) -> gen_server:call(Pid, random_data()), verify_continuous_timeouts(Target, Msg), ok. should_have_timeout_after_handle_cast_([Pid, Target, Msg | _]) -> gen_server:cast(Pid, random_data()), verify_continuous_timeouts(Target, Msg), ok. should_have_timeout_after_handle_info_([Pid, Target, Msg | _]) -> Pid ! random_data(), verify_continuous_timeouts(Target, Msg), ok. % Helper to the timeout tests verify_continuous_timeouts(Target, Msg) -> PreCount = meck:num_calls(breeze_worker_controller, multicast, [Target, Msg]), timer:sleep(1), % enough time to make a number of calls ?assert(PreCount < meck:num_calls(breeze_worker_controller, multicast, [Target, Msg])). %% Internal functions make_emitting_generate_mock(Msg) -> fun(Mock) -> meck:expect(Mock, generate, fun(EmitFun, State) -> EmitFun(Msg), {ok, State} end) end. setup_timer_tests() -> Mock = create_mock(), Msg = {foo, bar}, EmitTriggerMock = make_emitting_generate_mock(Msg), EmitTriggerMock(Mock), Target = pc_tests_common:create_pid(), Targets = [{Target, all}], meck:new(breeze_worker_controller), meck:expect(breeze_worker_controller, multicast, 2, ok), {ok, Pid} = breeze_generating_worker:start_link( Mock, [], [{targets, Targets}]), [Pid, Target, Msg, Mock]. teardown_timer_tests([Pid, _Target, _Msg, Mock]) -> breeze_generating_worker:stop(Pid), pc_tests_common:delete_mock(breeze_worker_controller), pc_tests_common:delete_mock(Mock), ok. random_data() -> {foo, make_ref(), self(), [1]}.
--- template: ModelPage title: Connor featuredImage: >- https://ucarecdn.com/5c9fe007-b326-4717-a3a0-978910b2e6aa/-/crop/2048x1011/0,191/-/preview/ imageThumbnail: 'https://ucarecdn.com/e088a995-1444-432b-bde5-234e118da1e1/' firstName: Connor collection: Men height: 179cm measurementType: chest bust: 96cm waist: 79cm hips: 99cm size: 'Shirt: M Pants: 32' shoeSize: 10.5 US hair: Brown eyes: Blue imagePortfolio: - image: 'https://ucarecdn.com/de77a743-cc07-4ce2-b95d-6c65bc167fa3/' - image: 'https://ucarecdn.com/989867c4-ee82-4616-a8ea-4d15f23901da/' - image: 'https://ucarecdn.com/75ea71ff-9dbe-4d5a-b542-4690d396e0c1/' - image: 'https://ucarecdn.com/c7b25f70-02bb-474e-b7f1-07c1e1e70bd5/' - image: 'https://ucarecdn.com/dd5934c1-fbce-48ea-84ec-78ce7b139f74/' - image: 'https://ucarecdn.com/0dc41d10-af69-4388-b052-086bd635b986/' - image: 'https://ucarecdn.com/d2038864-4c2c-4b87-a0a0-1b1a1843a1bc/' - image: 'https://ucarecdn.com/7e10b7d6-7eca-47c9-80a1-6582b5918abb/' - image: 'https://ucarecdn.com/072ddbe3-bea4-4368-aaa7-7c9d852760fe/' - image: 'https://ucarecdn.com/e7807d5d-d786-4732-b174-8a56395e109b/' - image: 'https://ucarecdn.com/f3251ef7-96c1-494e-a24a-b92e5c1f7508/' - image: 'https://ucarecdn.com/9a789e8b-649b-4db0-9d99-5c870dec3ef7/' ---
package com.hoc081098.datastoresample.domain.usecase import com.hoc081098.datastoresample.domain.repo.UserPreferencesRepository class EnableSortByDeadline( private val userPreferencesRepository: UserPreferencesRepository, ) { suspend operator fun invoke(enabled: Boolean) = userPreferencesRepository.enableSortByDeadline(enabled) }
// // MenuDefine.cs // ProductName Ling // // Created by toshiki sakamoto on 2021.04.11 // namespace Ling.Common.Scene.Menu { /// <summary> /// 定数 /// </summary> public class MenuDefine { /// <summary> /// メニューグループ /// </summary> public enum Group { Menu, Shop, } /// <summary> /// 各要素のカテゴリ /// </summary> public enum Category { Bag, // 持ち物(今はアイテムのみとする) Equip, // 装備一覧 Shop, // ショップ:買う Other, // その他 } } public static class MenuDefineExtensions { public static string GetCategoryName(this MenuDefine.Category self) { switch (self) { case MenuDefine.Category.Bag: return "もちもの"; case MenuDefine.Category.Equip: return "装備"; case MenuDefine.Category.Shop: return "ショップ"; case MenuDefine.Category.Other: return "その他"; default: return "None"; } } } }
#include <iostream> using std::cout; class Foo { int value_ = 0; public: Foo (){} Foo (int x) : value_(x) {} int value () const { return value_; } int value (int x) { return value_ = x; } Foo& operator++ (); Foo operator++ (int); Foo& operator-- (); Foo operator-- (int); }; Foo& Foo::operator++ () { cout << "pre-incrementing\t"; value_ += 1; return *this; } Foo Foo::operator++ (int) { cout << "post-incrementing\t"; Foo tmp(*this); // or Foo tmp = *this; operator++(); // sometimes you see: ++(*this); return tmp; } Foo& Foo::operator-- () { cout << "pre-decrementing\t"; value_ -= 1; return *this; } Foo Foo::operator-- (int) { cout << "post-decrementing\t"; Foo tmp = *this; operator--(); // sometimes you see: --(*this); return tmp; } int main() { Foo n(13); cout << "n is " << (++n).value() << '\n'; cout << "n is " << (n++).value() << '\n'; cout << "n is " << (--n).value() << '\n'; cout << "n is " << (n--).value() << '\n'; cout << "n is " << n.value() << '\n'; ++n; ++n; cout << "n is " << n.value() << '\n'; return 0; }
using FluentAssertions; using ksqlDB.RestApi.Client.Infrastructure.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ksqlDB.Api.Client.Tests.Infrastructure.Extensions { [TestClass] public class EnumerableExtensionsTests { [TestMethod] public void IsOneOfFollowing() { //Arrange //Act var isOneOf = 1.IsOneOfFollowing(1, 2, 3); //Assert isOneOf.Should().BeTrue(); } [TestMethod] public void IsOneOfFollowing_ReturnsFalse() { //Arrange //Act var isOneOf = 4.IsOneOfFollowing(1, 2, 3); //Assert isOneOf.Should().BeFalse(); } [TestMethod] public void IsNotOneOfFollowing() { //Arrange //Act var isNotOneOf = 4.IsNotOneOfFollowing(1, 2, 3); //Assert isNotOneOf.Should().BeTrue(); } [TestMethod] public void IsNotOneOfFollowing_ReturnsFalse() { //Arrange //Act var isNotOneOf = 1.IsNotOneOfFollowing(1, 2, 3); //Assert isNotOneOf.Should().BeFalse(); } } }
--- макет : название слайда : " Добро пожаловать на наш второй слайд! " --- Ваш текст awwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww Используйте левую стрелку, чтобы вернуться!
# Description Runs Get-IISAppPool and returns app pool names and their status. # Author Bryan Mason
//! Encoding, where 8 trits are stored in two bytes. //! //! Advantages: //! * Better memory-efficiency than T3B1, and same as T4B1. //! * If the `hi` part is stored in byte 1, and the `lo` part in byte 2 at the same //! relative position, then this form of vectorization allows high-level SIMD, //! and therefore for the best ternary processing performance. //! Disadvantages: //! * There are still encodings with better memory efficiency (see T5B1 and T9B2).
package com.github.saboteur.ticketbookingsystem.ticketbookingservice.mapper.dto import com.github.saboteur.ticketbookingsystem.ticketbookingservice.dto.TicketDto import com.github.saboteur.ticketbookingsystem.ticketbookingservice.mapper.Mapper import com.github.saboteur.ticketbookingsystem.ticketbookingservice.mapper.common.LocalDateTimeToStringMapper import com.github.saboteur.ticketbookingsystem.ticketbookingservice.model.Ticket object TicketToTicketDtoMapper : Mapper<Ticket, TicketDto> { override fun get(from: Ticket): TicketDto = TicketDto( price = from.price, discountPrice = from.discountPrice, movie = from.movie, date = LocalDateTimeToStringMapper[from.date], seat = from.seat ) }
import type { Encodings } from "$lib/types/encodings"; import { sendAxisDimension } from "$lib/util/requests"; import type { Writable } from "svelte/store"; import { writable } from "svelte/store"; import { interestingDimensions } from "./interesting-dimensions"; export const activeViewEncodings: Writable<Encodings> = writable({ x: null, y: null, color: null }); activeViewEncodings.subscribe((newEncodings) => { if (newEncodings.x !== null) { sendAxisDimension("x", newEncodings.x); interestingDimensions.update((dims) => { dims[newEncodings.x] = true; return dims; }); } if (newEncodings.y !== null) { sendAxisDimension("y", newEncodings.y); interestingDimensions.update((dims) => { dims[newEncodings.y] = true; return dims; }); } });
// Type definitions for itty-router-extras 0.4 // Project: https://github.com/kwhitley/itty-router-extras // Definitions by: David Roizenman <https://github.com/hmnd> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Router, Request as IttyRequest } from 'itty-router'; export { Router as ThrowableRouter }; /** * Throw to respond with provided status code and message. */ export class StatusError extends Error { constructor(status: number, message: string); } /** * Middleware to safely parse and embed content request bodies (eg.text/json) as `request.content`. */ export function withContent(request: IttyRequest): void; /** * Middleware to embed cookies into request as `request.cookies` (object). */ export function withCookies(request: IttyRequest): void; /** * Middleware to embed route params directly into request as a convenience. * * NOTE: withParams cannot be applied globally upstream, as it will have seen no route params at this stage (to spread into the request). */ export function withParams(request: IttyRequest): void; export interface ErrorBody { error: string; status: number; } /** * Create JSON-formatted {@link Response}, with {@link ErrorBody} or custom payload as body. * * @param status Response status code * @param payload Error message or custom payload */ export function error(status: number, payload?: string | object): Response; /** * Create JSON-formatted {@link Response Response}. * * @param content Payload * @param options Response options */ export function json(content: object, options?: ResponseInit): Response; /** * Create JSON-formatted {@link Response}, with status code 404, and message as {@link ErrorBody} or custom payload. * * @param payload Error message or custom payload */ export function missing(payload?: string | object): Response; export interface StatusBody { message: string; status: number; } /** * Create JSON-formatted {@link Response}, with provided status code and message as {@link StatusBody body} or custom payload. * * @param status Response status code * @param message Message or custom payload */ export function status(status: number, payload?: string | object): Response; /** * Create plaintext-formatted {@link Response} with provided options. * * @param content Response text * @param options Response options */ export function text(content: string, options?: ResponseInit): Response;
# frozen_string_literal: true $LOAD_PATH.push File.expand_path('lib', __dir__) require 'clepsydra/version' Gem::Specification.new do |spec| spec.name = 'clepsydra' spec.version = Clepsydra::Version::VALUE spec.authors = ['Abhimanyu Singh'] spec.email = ['abhisinghabhimanyu@gmail.com'] spec.homepage = 'https://github.com/avmnu-sng/clepsydra' spec.summary = 'Instrument events for elapsed time' spec.description = <<-DESCRIPTION.strip.gsub(/\s+/, ' ') Clepsydra is an instrumentation tool allowing instrumenting events. You can subscribe to events to receive instrument notifications once done. DESCRIPTION spec.license = 'MIT' spec.metadata['homepage_uri'] = spec.homepage spec.metadata['source_code_uri'] = "https://github.com/avmnu-sng/clepsydra/tree/v#{spec.version}" spec.metadata['changelog_uri'] = 'https://github.com/avmnu-sng/clepsydra/blob/main/CHANGELOG.md' spec.metadata['bug_tracker_uri'] = 'https://github.com/avmnu-sng/clepsydra/issues' spec.required_ruby_version = '>= 2.5.0' spec.add_dependency 'concurrent-ruby', '~> 1.0', '>= 1.0.0' spec.files = `git ls-files -- lib/*`.chomp.split("\n") spec.files += %w[CHANGELOG.md README.md LICENSE] spec.require_paths = ['lib'] end
require 'spec_helper' require 'cleanroom/rspec' describe 'RSpec matchers' do let(:klass) do Class.new do include Cleanroom def method_1; end expose :method_1 def method_2; end end end let(:instance) { klass.new } describe '#be_an_exposed_method_on' do context 'when given a class' do it 'is true when the method is exposed' do expect(:method_1).to be_an_exposed_method_on(klass) end it 'is false when the method exists, but is not exposed' do expect(:method_2).to_not be_an_exposed_method_on(klass) end it 'is false when the method is not exposed' do expect(:method_3).to_not be_an_exposed_method_on(klass) end end context 'when given an instance' do it 'is true when the method is exposed' do expect(:method_1).to be_an_exposed_method_on(instance) end it 'is false when the method exists, but is not exposed' do expect(:method_2).to_not be_an_exposed_method_on(instance) end it 'is false when the method is not exposed' do expect(:method_3).to_not be_an_exposed_method_on(instance) end end end describe '#have_exposed_method' do context 'when given a class' do it 'is true when the method is exposed' do expect(klass).to have_exposed_method(:method_1) end it 'is false when the method exists, but is not exposed' do expect(klass).to_not have_exposed_method(:method_2) end it 'is false when the method is not exposed' do expect(klass).to_not have_exposed_method(:method_3) end end context 'when given an instance' do it 'is true when the method is exposed' do expect(instance).to have_exposed_method(:method_1) end it 'is false when the method exists, but is not exposed' do expect(instance).to_not have_exposed_method(:method_2) end it 'is false when the method is not exposed' do expect(instance).to_not have_exposed_method(:method_3) end end end end
if [[ -n $CUBES ]]; then CUBES="$CUBES orders" else CUBES="orders" fi
/* Copyright 2020 The Crossplane Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package persona import ( "context" "fmt" "time" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/crossplane/crossplane-runtime/pkg/logging" "github.com/crossplane/crossplane-runtime/pkg/meta" "github.com/crossplane/crossplane/pkg/stacks" ) const ( managedRolesLabel = "rbac.crossplane.io/managed-roles" managedRolesEnabled = "true" reconcileTimeout = 1 * time.Minute loggerName = "stacks/namespace-personas" adminPersona = "admin" editPersona = "edit" viewPersona = "view" errFailedToCreateClusterRole = "failed to create clusterrole" errFailedToDeleteClusterRoles = "failed to delete clusterroles" errFailedToGetNamespace = "failed to get namespace" logFailedToCreateDuringSync = "failed to create during sync" logFailedToDeleteDuringSync = "failed to delete during sync" ) var ( personas = []string{adminPersona, editPersona, viewPersona} resultRequeue = reconcile.Result{Requeue: true} ) // Reconciler reconciles Namespaces type Reconciler struct { kube client.Client log logging.Logger factory } // Setup adds a controller that reconciles Namespaces. func Setup(mgr ctrl.Manager, l logging.Logger) error { r := &Reconciler{ kube: mgr.GetClient(), factory: &nsPersonaHandlerFactory{}, log: l.WithValues("controller", loggerName), } // TODO(displague) Should we own the ClusterRole and watch the Namespace? // Not doing so means that changes to the ClusterRole won't be addressed by // this controller. OTOH, Permitting such changes keeps this controller // simple and gives users the flexibility to modify the clusterrole return ctrl.NewControllerManagedBy(mgr). Named(loggerName). For(&corev1.Namespace{}). Complete(r) } // Reconcile changes on Namespaces that may or may not have Stacks managed RBAC // labels. // // Reconcile gets the Namespace with the requested namespace name with the // management enabling label. When the label is found, we create matching // clusterroles. When the label is not found, possibly removed, the // namespace-persona clusterroles are deleted. // // When a namespace is deleted, the clusterroles will be removed through // garbage-collection using OwnerReferences. func (r *Reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) { r.log.Debug("Reconciling", "request", req) ctx, cancel := context.WithTimeout(context.Background(), reconcileTimeout) defer cancel() ns := &corev1.Namespace{} if err := r.kube.Get(ctx, req.NamespacedName, ns); err != nil { if kerrors.IsNotFound(err) { return reconcile.Result{}, nil } r.log.Debug(errFailedToGetNamespace, "request", req, "error", err) return reconcile.Result{}, err } handler := r.factory.newHandler(r.log, ns, r.kube) return handler.sync(ctx) } type handler interface { sync(context.Context) (reconcile.Result, error) create(context.Context) error delete(context.Context) error } type nsPersonaHandler struct { kube client.Client ns *corev1.Namespace log logging.Logger } type factory interface { newHandler(logging.Logger, *corev1.Namespace, client.Client) handler } type nsPersonaHandlerFactory struct{} func (f *nsPersonaHandlerFactory) newHandler(log logging.Logger, ns *corev1.Namespace, kube client.Client) handler { return &nsPersonaHandler{ kube: kube, ns: ns, log: log, } } // sync compares the namespace being handled to the desired labels // Matches warrant Clusterrole creation // Non-matches warrant Clusterrole deletion func (h *nsPersonaHandler) sync(ctx context.Context) (reconcile.Result, error) { if nsHasPersonaManagement(h.ns) && !meta.WasDeleted(h.ns) { if err := h.create(ctx); err != nil { h.log.Debug(logFailedToCreateDuringSync, "namespace", h.ns.GetName(), "error", err) return resultRequeue, err } } else { if err := h.delete(ctx); err != nil { h.log.Debug(logFailedToDeleteDuringSync, "namespace", h.ns.GetName(), "error", err) return resultRequeue, err } } return reconcile.Result{}, nil } // generateNamespaceClusterRoles generates roles for a given namespace // These clusterroles are named crossplane:ns:{nsName}:{persona} func generateNamespaceClusterRoles(ns *corev1.Namespace) (roles []*rbacv1.ClusterRole) { nsName := ns.GetName() for _, persona := range personas { name := fmt.Sprintf(stacks.NamespaceClusterRoleNameFmt, nsName, persona) labels := map[string]string{ fmt.Sprintf(stacks.LabelNamespaceFmt, nsName): "true", stacks.LabelScope: stacks.NamespaceScoped, } if persona == adminPersona { labels[fmt.Sprintf(stacks.LabelAggregateFmt, "crossplane", persona)] = "true" } // By specifying MatchLabels, ClusterRole Aggregation will pass // along the rules from other ClusterRoles with the desired labels. // This is why we don't define any Rules here. role := &rbacv1.ClusterRole{ AggregationRule: &rbacv1.AggregationRule{ ClusterRoleSelectors: []metav1.LabelSelector{ { MatchLabels: map[string]string{ fmt.Sprintf(stacks.LabelAggregateFmt, stacks.NamespaceScoped, persona): "true", fmt.Sprintf(stacks.LabelNamespaceFmt, nsName): "true", }, }, { MatchLabels: map[string]string{ fmt.Sprintf(stacks.LabelAggregateFmt, "namespace-default", persona): "true", }, }, }, }, ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: labels, }, } // Parent labels enable more precise DeleteAllOf calls than matching // on clusterrole name meta.AddLabels(role, stacks.ParentLabels(ns)) roles = append(roles, role) } return roles } func nsHasPersonaManagement(ns *corev1.Namespace) bool { v, ok := ns.GetLabels()[managedRolesLabel] return ok && v == managedRolesEnabled } // create ClusterRoles for namespace personas // example: crossplane:ns:{name}:{persona} func (h *nsPersonaHandler) create(ctx context.Context) error { roles := generateNamespaceClusterRoles(h.ns) for _, role := range roles { // When the namespace is deleted, clusterroles are no longer needed. // Set the owner to the Namespace for garbage collection. role.SetOwnerReferences([]metav1.OwnerReference{ meta.AsOwner(meta.ReferenceTo(h.ns, corev1.SchemeGroupVersion.WithKind("Namespace"))), }) // Creating the clusterroles. Rules in these clusterroles are populated // through aggregation from the stacks installed in the namespaces, we // won't need to update them. // // We are not patching existing clusterroles. This permits user // modification. h.log.Debug("Creating ClusterRole", "name", role.GetName()) if err := h.kube.Create(ctx, role); err != nil && !kerrors.IsAlreadyExists(err) { return errors.Wrapf(err, errFailedToCreateClusterRole) } } return nil } // delete ClusterRoles for namespace personas func (h *nsPersonaHandler) delete(ctx context.Context) error { // Logging that clusterroles are attempting to be deleted would // either be noisy (logged on unmanaged namespaces) or cost a // lookup for existing clusterroles labels := stacks.ParentLabels(h.ns) if err := h.kube.DeleteAllOf(ctx, &rbacv1.ClusterRole{}, client.MatchingLabels(labels)); err != nil { return errors.Wrapf(err, errFailedToDeleteClusterRoles) } return nil }
--- title: Number sequences in Microsoft Dynamics AX TOCTitle: Number sequences ms:assetid: 7e3b5fa7-6761-42ef-a296-620558a08172 ms:mtpsurl: https://technet.microsoft.com/library/Hh209291(v=AX.60) ms:contentKeyID: 36058317 author: Khairunj ms.date: 04/18/2014 mtps_version: v=AX.60 audience: Application User ms.search.region: Global --- # Number sequences in Microsoft Dynamics AX [!INCLUDE[archive-banner](includes/archive-banner.md)] _**Applies To:** Microsoft Dynamics AX 2012 R3, Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012_ This section provides information about number sequences. The following topics are included: [Number sequence overview](number-sequence-overview.md) [Set up number sequences](set-up-number-sequences.md)
package lab2 import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi @JsonClass(generateAdapter = true) data class SomeObj( val hidden: Boolean, val names: List<String> ) fun main() { val json = """ { "hidden": true, "names": ["a", "b"] } """.trimIndent() val moshi: Moshi = Moshi.Builder().build() val adapter = moshi.adapter(SomeObj::class.java) println(adapter.fromJson(json)) }
# frozen_string_literal: true module Rockstart::Development class GeneratorOverridesGenerator < Rails::Generators::Base include Rails::Generators::AppName source_root File.expand_path("templates", __dir__) def add_custom_resource_routes_generator template "resource_route_generator.rb", "lib/generators/rails/#{app_name}_resource_route_generator.rb" end # rubocop:disable Metrics/MethodLength def override_generator_defaults application do <<~DEFAULTS config.generators do |g| g.assets false g.helper false g.javascripts false g.scaffold_stylesheet false g.stylesheets false g.resource_route :#{app_name}_resource_route end DEFAULTS end end # rubocop:enable Metrics/MethodLength end end
using System; using Android.Media; namespace PictureInPicture { public class MovieViewMediaPlayerOnCompletionListener : Java.Lang.Object, MediaPlayer.IOnCompletionListener { MovieView self; public MovieViewMediaPlayerOnCompletionListener(MovieView self) { this.self = self; } public void OnCompletion(MediaPlayer player) { self.AdjustToggleState(); self.KeepScreenOn = false; if (self.MVMovieListener != null) { self.MVMovieListener.OnMovieStopped(); } } } }
# Convert To UTF-8-BOM ![](https://imgtp.apqiang.com/2022/03/30/SnUa1qbP.png) 这是一个嗯缝了以下两个开源项目而得到的产物,感谢这些项目的开发者们。 软件主体框架 https://github.com/hontsev/ShiftJISDecoder 文件编码识别 https://github.com/CharsetDetector/UTF-unknown
#!/bin/bash TMP_PATH=`mktemp -d -t gstringer` IFS=' ' SAMPLE_NUM=1; SAMPLE_LIST=""; if [ "$(which ffmpeg)" == "" ]; then echo "no ffmpeg installed :("; exit -1 fi while read LINE; do QUOTED_LINE=`python -c "import urllib, sys; print urllib.quote(sys.stdin.read().replace('\n',''))" <<EOF $LINE EOF` if [ "$QUOTED_LINE" == "" ]; then continue fi SAMPLE_URL="https://translate.google.com/translate_tts?ie=UTF-8&&tl=pt&total=100&idx=1&textlen=50000&client=t&q=${QUOTED_LINE}" SAMPLE_PATH="${TMP_PATH}/${SAMPLE_NUM}.mp3" echo "Fetching \"${LINE}\"" echo -e "\t=> \"${SAMPLE_PATH}\""; curl -A "Mozilla/5.0" --stderr /dev/null "${SAMPLE_URL}" >"${SAMPLE_PATH}" SAMPLE_NUM=$(($SAMPLE_NUM+1)) SAMPLE_LIST="${SAMPLE_LIST} file '${SAMPLE_PATH}'" done; [ -f "output.mp3" ] && rm output.mp3 ffmpeg -f concat -i - -c copy output.mp3 <<EOF ${SAMPLE_LIST} EOF