text
stringlengths
27
775k
๏ปฟ#region Using directives using System; #endregion namespace Blazorise.Markdown { /// <summary> /// Supplies the information about the markdown button click event. /// </summary> public class MarkdownButtonEventArgs : EventArgs { /// <summary> /// A default <see cref="MarkdownButtonEventArgs"/> constructor. /// </summary> /// <param name="name">Button action name.</param> /// <param name="value">Button value.</param> public MarkdownButtonEventArgs( string name, object value ) { Name = name; Value = value; } /// <summary> /// Gets the button action name. /// </summary> public string Name { get; } /// <summary> /// Gets the button action value. /// </summary> public object Value { get; } } }
package com.malliina.boat.graph import com.malliina.boat.Coord sealed trait GraphError case class UnresolvedFrom(from: Coord) extends GraphError case class UnresolvedTo(to: Coord) extends GraphError case class NoRoute(from: Coord, to: Coord) extends GraphError case object EmptyGraph extends GraphError
import { TOTP } from '@otplib/core'; import { testClassPropertiesEqual } from '@tests/utils'; import { testSuiteTOTP } from '@tests/suite/totp'; import { TOTPAsync } from './totp'; testClassPropertiesEqual<TOTP, TOTPAsync>( TOTP.name, new TOTP(), TOTPAsync.name, new TOTPAsync() ); testSuiteTOTP<TOTPAsync>('totp-async', TOTPAsync);
package services import java.util.UUID trait HashAppender { def append(str: String): String } class HashAppenderImpl extends HashAppender { override def append(str: String): String = UUID.randomUUID.toString.take(9) + str }
# conversion methods for DataArrays and DataFrames function rcopy{T,S<:VectorSxp}(::Type{DataArray{T}}, s::Ptr{S}) DataArray(rcopy(Array{T},s), isna(s)) end function rcopy{S<:VectorSxp}(::Type{DataArray}, s::Ptr{S}) DataArray(rcopy(Array,s), isna(s)) end function rcopy(::Type{DataArray}, s::Ptr{IntSxp}) isFactor(s) && error("$s is a R factor") DataArray(rcopy(Array,s), isna(s)) end function rcopy(::Type{PooledDataArray}, s::Ptr{IntSxp}) isFactor(s) || error("$s is not a R factor") refs = DataArrays.RefArray([isna(x) ? zero(Int32) : x for x in s]) compact(PooledDataArray(refs,rcopy(getattrib(s,Const.LevelsSymbol)))) end function rcopy(::Type{DataFrame}, s::Ptr{VecSxp}) isFrame(s) || error("s is not a R data frame") DataFrame(Any[isFactor(c)? rcopy(PooledDataArray, c) : rcopy(DataArray, c) for c in s], rcopy(Array{Symbol},getnames(s))) end ## DataArray to sexp conversion. function sexp(v::DataArray) rv = protect(sexp(v.data)) try for (i,isna) = enumerate(v.na) if isna rv[i] = naeltype(eltype(rv)) end end finally unprotect(1) end rv end ## PooledDataArray to sexp conversion. function sexp{T<:Compat.String,R<:Integer}(v::PooledDataArray{T,R}) rv = sexp(v.refs) setattrib!(rv, Const.LevelsSymbol, sexp(v.pool)) setattrib!(rv, Const.ClassSymbol, sexp("factor")) rv end ## DataFrame to sexp conversion. function sexp(d::DataFrame) nr,nc = size(d) rd = protect(allocArray(VecSxp, nc)) try for i in 1:nc rd[i] = sexp(d[d.colindex.names[i]]) end setattrib!(rd,Const.NamesSymbol, sexp([string(n) for n in d.colindex.names])) setattrib!(rd,Const.ClassSymbol, sexp("data.frame")) setattrib!(rd,Const.RowNamesSymbol, sexp(1:nr)) finally unprotect(1) end rd end # R formula objects function sexp(f::Formula) s = protect(rlang_p(:~,rlang_formula(f.lhs),rlang_formula(f.rhs))) try setattrib!(s,Const.ClassSymbol,sexp("formula")) setattrib!(s,".Environment",Const.GlobalEnv) finally unprotect(1) end s end function rlang_formula(e::Expr) e.head == :call || error("invalid formula object") op = e.args[1] if op == :& op = :(:) end if length(e.args) > 3 && op in (:+,:*,:(:)) rlang_p(op, rlang_formula(Expr(e.head,e.args[1:end-1]...)), rlang_formula(e.args[end])) else rlang_p(op,map(rlang_formula,e.args[2:end])...) end end rlang_formula(e::Symbol) = e rlang_formula(n::Number) = n
๏ปฟnamespace DSerfozo.RpcBindings.CefGlue.Common { public static class Messages { public const string RpcResponseMessage = "RpcResponseMessage"; public const string RpcRequestMessage = "RpcRequestMessage"; } }
<?php /** * YYF - A simple, secure, and efficient PHP RESTful Framework. * * @link https://github.com/YunYinORG/YYF/ * * @license Apache2.0 * @copyright 2015-2017 NewFuture@yunyin.org */ namespace tests\library; use \Db as Db; use \Orm as Orm; use \Test\YafCase as TestCase; class DbTest extends TestCase { /** * @dataProvider configProvider * * @param mixed $config */ public function testConnect($config) { $connection = Db::connect($config); $this->assertNotNull($connection); $this->assertInstanceOf('\PDO', $connection); } /** * @dataProvider configProvider * * @param mixed $config */ public function testSet($config) { $connection = Db::set('x', $config); $this->assertSame($connection, Db::get('x')); Db::set('xx', $connection); $this->assertSame($connection, Db::get('xx')); } public function testGet() { $connection = Db::current(); $this->assertSame($connection, Db::get('xxxxx')); } /** * @dataProvider configProvider * @depends testGet * * @param mixed $config */ public function testCurrent($config) { $connection = Db::connect($config); Db::current($connection); $this->assertSame($connection, Db::current()); } /** * @dataProvider configProvider * @depends testConnect * * @param mixed $config */ public function testQuery($config) { Db::set('_read', $config); $this->assertCount(2, Db::query('SELECT * FROM user')); $dataset = array( array( 'id' => '1', 'account' => 'newfuture', 'name' => 'New Future', ) ); $user = Db::query('SELECT id,account,name FROM user WHERE id=?', array(1)); $this->assertEquals($dataset, $user); //ๅ•ๆกๆŸฅ่ฏข $user = Db::query('SELECT id,account,name FROM user WHERE id=?', array(1), false); $this->assertEquals($dataset[0], $user); } /** * @dataProvider configProvider * @depends testConnect * * @param mixed $config */ public function testColumn($config) { Db::set('_read', $config); $name = 'ๆต‹่ฏ•'; $this->assertSame($name, Db::column('SELECT name FROM user WHERE id=2')); $this->assertSame($name, Db::column('SELECT name FROM user WHERE id=?', array(2))); $this->assertSame($name, Db::column('SELECT name FROM user WHERE id=:id', array('id' => 2))); $this->assertSame($name, Db::column('SELECT name FROM user WHERE id=:id', array(':id' => 2))); } /** * @dataProvider configProvider * @depends testQuery * * @param mixed $config */ public function testExec($config) { Db::set('_read', $config); Db::set('_write', $config); $data = array( 'id' => 3, 'account' => 'dbtester', 'name' => 'Db Test', 'created_at' => date('Y-m-d h:i:s'), ); $insert = 'INSERT INTO`user`(`id`,`name`,`account`,`created_at`)VALUES(:id,:name,:account,:created_at)'; $this->assertSame(1, Db::exec($insert, $data)); $this->assertEquals(3, Db::column('SELECT COUNT(*) FROM user')); $user = Db::query('SELECT id,account,name,created_at FROM user WHERE id=?', array($data['id']), false); $this->assertEquals($data, $user); $update = 'UPDATE`user`SET`name`= ? WHERE(`id`= ?)'; $UPDATE_NAME = 'UPDATE_TEST DB'; $this->assertSame(1, Db::execute($update, array($UPDATE_NAME, 3))); $data['name'] = $UPDATE_NAME; $user = Db::query('SELECT id,account,name,created_at FROM user WHERE id=?', array($data['id']), false); $this->assertEquals($data, $user); $delete = 'DELETE FROM`user`WHERE(`id`= :id)'; $this->assertSame(1, Db::exec($delete, array(':id' => $data['id']))); $this->assertEquals(2, Db::column('SELECT COUNT(*) FROM user')); } /** * @dataProvider tableProvider * * @param mixed $name * @param string $pk * @param null|mixed $prefix */ public function testTable($name, $pk = 'id', $prefix = null) { $orm = call_user_func_array(array('Db', 'table'), func_get_args()); $this->assertInstanceOf('Orm', $orm); $this->assertAttributeEquals($pk, '_pk', $orm); if (func_num_args() > 2) { $this->assertAttributeEquals($prefix, '_pre', $orm); } } /** *ๆต‹่ฏ•ๆ•ฐๆฎๅบ“ */ public function configProvider() { return array( 'default' => array('_'), 'test' => array('test'), 'mysql' => array( array( 'dsn' => getenv('MYSQL_DSN') ?: 'mysql:host=localhost;port=3306;dbname=yyf;charset=utf8', 'username' => getenv('DB_USER') ?: 'root', 'password' => getenv('DB_PWD'), ), ), 'sqlite' => array( array( 'dsn' => getenv('SQLITE_DSN') ?: 'sqlite:'.APP_PATH.'/runtime/yyf.db', ), ), ); } /** *ๆต‹่ฏ•ๆ•ฐๆฎๅบ“ */ public function tableProvider() { return array( 'only name' => array('user'), 'name with pk' => array('article','aid'), 'name pk with prefix' => array('user','uid','yyf_'), ); } }
use serde::Deserialize; use serde_json::value::RawValue; use crate::domain::*; use crate::util::*; /// Setting is a json, include the following properties: /// each you defined dimensions will be output as `Instance.para` #[derive(Serialize, Deserialize)] struct Setting { /// default is "/" #[serde(skip_serializing_if = "is_default_para_separator")] #[serde(default = "default_para_separator")] pub dimension_separator: String, } /// each item in the table which will be scattered #[derive(Serialize, Deserialize, Clone)] struct Item<'a> { /// include all dimension, separator is defined in Setting key: &'a str, /// each split dimension will copy this value. #[serde(borrow)] value: &'a RawValue, } #[derive(Clone)] struct MiddleResult<'a>(&'a str, Vec<Item<'a>>); /// Suggestion: /// - use-upstream-id to avoid result scatter pub fn scatter(para: &ConverterParameter) -> ConverterReturned { // check setting let cfg = if para.cfg.eq("") { "{}" } else { &para.cfg }; let set = serde_json::from_str::<Setting>(cfg); if let Err(e) = set { let msg = format!("setting error : {:?}", e.to_string()); return ConverterReturned::LogicalError { msg: msg }; } let set = set.unwrap(); // check input content let input = serde_json::from_str::<Vec<Item>>(&para.from.content); if let Err(e) = input { let msg = format!("instance content error : {:?}", e.to_string()); return ConverterReturned::LogicalError { msg: msg }; } // process split let mut rtn: Vec<Instance> = vec![]; let input = input.unwrap(); let need_replace = !set.dimension_separator.eq(&*SEPARATOR_INS_PARA); for one in input { let mut ins = Instance::default(); if need_replace { ins.path.para = one.key.replace(&set.dimension_separator, &*SEPARATOR_INS_PARA); } else { ins.path.para = one.key.to_string(); } ins.content = one.value.to_string(); rtn.push(ins); } // return result ConverterReturned::Instances { ins: rtn } } #[cfg(test)] mod test { use super::*; #[test] fn scatter_test() { let mut content: Vec<KV> = vec![]; content.push(KV::new("class5|name1|subject1", 92)); content.push(KV::new("class5|name1|subject2", 85)); content.push(KV::new("class5|name1|subject3", 99)); let mut input_instance = Instance::default(); input_instance.content = serde_json::to_string(&content).unwrap(); let setting = Setting { dimension_separator: "|".to_string(), }; let para = ConverterParameter { from: input_instance, last_state: None, task_id: 0, master: None, cfg: serde_json::to_string(&setting).unwrap(), }; let rtn = scatter(&para); if let ConverterReturned::Instances { ins } = rtn { assert_eq!(ins.len(), 3); let one = &ins[0]; assert_eq!(one.path.para, "class5/name1/subject1"); assert_eq!(one.content, "92"); }; } #[test] fn setting_default() { let set = Setting { dimension_separator: "/".to_string(), }; let json = serde_json::to_string(&set).unwrap(); let cmp = r#"{}"#; assert_eq!(json, cmp); let set = serde_json::from_str::<Setting>(&json).unwrap(); assert_eq!(set.dimension_separator, "/") } #[derive(Serialize)] struct KV { pub key: String, pub value: i32, } impl KV { pub fn new(key: &str, value: i32) -> Self { KV { key: key.to_string(), value, } } } }
#Sumi Bae Git Blog --- ๐Ÿ“ŒContact - โœ‰๏ธ <a href="mailto:ssum0222@gmail.com?Subject=\[blog\]Hello">ssum0222@gmail.com</a>
import 'package:ex04_using_generics/assembly.dart'; void operation(car) { print('Operate ${car}'); } void main() { // final passengerCarAssembly = AssemblyLine<Car>(); final passengerCarAssembly = AssemblyLine<PassengerCar>(); passengerCarAssembly.add(PassengerCar()); // passengerCarAssembly.add(Truck()); passengerCarAssembly.make(operation); // Paint operation for passenger car final paint = Operation<PassengerCar>('paint'); final paintTruck = Operation<Truck>('paint'); passengerCarAssembly.add(PassengerCar()); passengerCarAssembly.make(paint); passengerCarAssembly.make(paintTruck); }
import React, { Component } from 'react' import api from '../api' import ErrorMessage from '../ui/ErrorMessage' import List from '../ui/List' import Loader from '../ui/Loader' import PollCard from './PollCard' export default class Home extends Component { state = { polls: null, isLoading: false, errors: { fetching: null } } fetchPolls = () => { this.setState(prevState => ({ isLoading: true })) api .getAll('polls')() .then(({ data }) => { this.setState(prevState => ({ isLoading: false, polls: Object.values(data) })) }) .catch(e => this.setState(prevState => ({ isLoading: false, error: { fetching: 'An error occured while fetching polls' } })) ) } componentDidMount = () => { this.fetchPolls() } render() { const { isLoading, errors, polls } = this.state return ( <List> {isLoading && <Loader />} {polls && polls.map(p => ( <PollCard fetchPolls={this.fetchPolls} {...p} key={p._id} /> ))} <ErrorMessage errors={errors} type="fetching" /> </List> ) } }
module Chapter11Huttons where data Expr = Lit Integer | Add Expr Expr eval :: Expr -> Integer eval (Lit i) = i eval (Add expr1 expr2) = eval expr1 + eval expr2 printExpr :: Expr -> String printExpr (Lit i) = show i printExpr (Add expr1 expr2) = printExpr expr1 ++ " + " ++ printExpr expr2
-- Team: Cody Malick and Jacob Broderick module Tree where -- -- * Part 2: Binary trees -- -- | Integer-labeled binary trees. data Tree = Node Int Tree Tree -- ^ Internal nodes | Leaf Int -- ^ Leaf nodes deriving (Eq,Show) -- | An example binary tree, which will be used in tests. t1 :: Tree t1 = Node 1 (Node 2 (Node 3 (Leaf 4) (Leaf 5)) (Leaf 6)) (Node 7 (Leaf 8) (Leaf 9)) -- | Another example binary tree, used in tests. t2 :: Tree t2 = Node 6 (Node 2 (Leaf 1) (Node 4 (Leaf 3) (Leaf 5))) (Node 8 (Leaf 7) (Leaf 9)) -- | The integer at the left-most node of a binary tree. -- -- >>> leftmost (Leaf 3) -- 3 -- -- >>> leftmost (Node 5 (Leaf 6) (Leaf 7)) -- 6 -- -- >>> leftmost t1 -- 4 -- -- >>> leftmost t2 -- 1 -- leftmost :: Tree -> Int leftmost (Leaf i) = i leftmost (Node _ l _) = leftmost l -- | The integer at the right-most node of a binary tree. -- -- >>> rightmost (Leaf 3) -- 3 -- -- >>> rightmost (Node 5 (Leaf 6) (Leaf 7)) -- 7 -- -- >>> rightmost t1 -- 9 -- -- >>> rightmost t2 -- 9 -- rightmost :: Tree -> Int rightmost (Leaf i) = i rightmost (Node _ _ r) = rightmost r -- | Get the maximum integer from a binary tree. -- -- >>> maxInt (Leaf 3) -- 3 -- -- >>> maxInt (Node 5 (Leaf 4) (Leaf 2)) -- 5 -- -- >>> maxInt (Node 5 (Leaf 7) (Leaf 2)) -- 7 -- -- >>> maxInt t1 -- 9 -- -- >>> maxInt t2 -- 9 -- maxInt :: Tree -> Int maxInt (Leaf i) = i maxInt (Node val left right) = max val (max (maxInt left) (maxInt right)) -- | Get the minimum integer from a binary tree. -- -- >>> minInt (Leaf 3) -- 3 -- -- >>> minInt (Node 2 (Leaf 5) (Leaf 4)) -- 2 -- -- >>> minInt (Node 5 (Leaf 4) (Leaf 7)) -- 4 -- -- >>> minInt t1 -- 1 -- -- >>> minInt t2 -- 1 -- minInt :: Tree -> Int minInt (Leaf i) = i minInt (Node val left right) = min val (min (minInt left) (minInt right)) -- | Get the sum of the integers in a binary tree. -- -- >>> sumInts (Leaf 3) -- 3 -- -- >>> sumInts (Node 2 (Leaf 5) (Leaf 4)) -- 11 -- -- >>> sumInts t1 -- 45 -- -- >>> sumInts (Node 10 t1 t2) -- 100 -- sumInts :: Tree -> Int sumInts (Leaf i) = i sumInts (Node val left right) = (+) val ((+) (sumInts left) (sumInts right)) -- | The list of integers encountered by a pre-order traversal of the tree. -- -- >>> preorder (Leaf 3) -- [3] -- -- >>> preorder (Node 5 (Leaf 6) (Leaf 7)) -- [5,6,7] -- -- >>> preorder t1 -- [1,2,3,4,5,6,7,8,9] -- -- >>> preorder t2 -- [6,2,1,4,3,5,8,7,9] -- preorder :: Tree -> [Int] preorder (Leaf i) = [i] preorder (Node val left right) = [val] ++ preorder left ++ preorder right -- | The list of integers encountered by an in-order traversal of the tree. -- -- >>> inorder (Leaf 3) -- [3] -- -- >>> inorder (Node 5 (Leaf 6) (Leaf 7)) -- [6,5,7] -- -- >>> inorder t1 -- [4,3,5,2,6,1,8,7,9] -- -- >>> inorder t2 -- [1,2,3,4,5,6,7,8,9] -- inorder :: Tree -> [Int] inorder (Leaf i) = [i] inorder (Node val left right) = inorder left ++ [val] ++ inorder right -- | Check whether a binary tree is a binary search tree. -- -- >>> isBST (Leaf 3) -- True -- -- >>> isBST (Node 5 (Leaf 6) (Leaf 7)) -- False -- -- >>> isBST t1 -- False -- -- >>> isBST t2 -- True -- -- Get node value, needed for isBST and inBST nodeValue :: Tree -> Int nodeValue (Leaf i) = i nodeValue (Node val _ _) = val isBST :: Tree -> Bool isBST (Leaf i) = True isBST (Node val left right) = -- If the binary tree structure holds for this node and all children val >= nodeValue left && val < nodeValue right && isBST left && isBST right -- | Check whether a number is contained in a binary search tree. -- (You may assume that the given tree is a binary search tree.) -- -- >>> inBST 2 (Node 5 (Leaf 2) (Leaf 7)) -- True -- -- >>> inBST 3 (Node 5 (Leaf 2) (Leaf 7)) -- False -- -- >>> inBST 4 t2 -- True -- -- >>> inBST 10 t2 -- False -- inBST :: Int -> Tree -> Bool inBST sVal (Leaf i) = sVal == i inBST sVal (Node val left right) = val == sVal || inBST sVal left || inBST sVal right
package com.salmoukas.cerberus.ui import android.app.Application import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner class ViewModelFactory<T>(val creator: () -> T) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return creator() as T } } inline fun <reified T : ViewModel> ViewModelStoreOwner.createViewModel(noinline creator: (() -> T)? = null): T { return ViewModelProvider( this, if (creator == null) ( if (this is Context) ViewModelProvider.AndroidViewModelFactory((this as Context).applicationContext as Application) else ViewModelProvider.NewInstanceFactory() ) else ViewModelFactory(creator) ).get(T::class.java) }
--- layout: post title: 195. Tenth Line subtitle: Easy author: Bin Li tags: [Coding, LeetCode, Easy, Bash] image: comments: true published: true --- ## Description Given a text file `file.txt`, print just the 10th line of the file. **Example:** Assume that `file.txt` has the following content: ``` Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 ``` Your script should output the tenth line, which is: ``` Line 10 ``` **Note:** \1. If the file contains less than 10 lines, what should you output? \2. There's at least three different solutions. Try to explore all possibilities. ## Solutions ### 1. Awk ```bash # awk awk 'FNR == 10 {print }' file.txt # or awk 'NR==10' file.txt # 7/7 cases passed (0 ms) # Your runtime beats 100 % of bash submissions # Your memory usage beats 85.71 % of bash submissions (3.7 MB) ``` ### 2. Sed ```bash sed -n '10p' file.txt # 7/7 cases passed (4 ms) # Your runtime beats 73.92 % of bash submissions # Your memory usage beats 100 % of bash submissions (3.6 MB) ``` ### 3. Script ```bash cnt=0 while read line && [ $cnt -le 10 ]; do let 'cnt = cnt + 1' if [ $cnt -eq 10 ]; then echo $line exit 0 fi done < file.txt # 7/7 cases passed (4 ms) # Your runtime beats 73.92 % of bash submissions # Your memory usage beats 100 % of bash submissions (3.6 MB) ``` ### 4. Tail ```bash tail -n+10 file.txt|head -1 # 7/7 cases passed (4 ms) # Your runtime beats 73.92 % of bash submissions # Your memory usage beats 52.38 % of bash submissions (3.7 MB) ``` ## References 1. [195. Tenth Line](https://leetcode.com/problems/tenth-line/)
<?php class Vehiculo { //Atributos protected $owner; /******Constructores***********/ public function __construct($owner) { $this->owner = $owner; echo 'construct <br>'; } //getters y setters public function getOwner(){ return $this->owner; } public function setOwner($Name){ $this->owner = $Name; } //Metodos public function move() { echo 'moving <br>'; } } class Car extends Vehiculo { public function move() { echo 'Car: moving<br>'; } } /** * */ class Truck extends Vehiculo { private $type; public function __construct($ownerName,$type) { // parent::__construct($ownerName); $this->owner = $ownerName; $this->type=$type; } public function move() { echo 'Truck-'.$this->type.': moving<br>'; } } echo 'CLASS Car <br>'; $car = new Car('Mercedes'); $car->move(); echo 'Owner car: '.$car->getOwner().'<br>'; echo '<br>CLASS Truck <br>'; $Truck = new Truck('Silvia','Pickup'); $Truck->move(); echo 'Owner truck: '.$Truck->getOwner().'<br>'; ?>
๏ปฟusing System; using UnityEngine; namespace ET { public static class GameObjectHelper { public static GameObject Instantiate(GameObject prefab , Transform parent,bool worldPositionStays) { return UnityEngine.Object.Instantiate(prefab, parent, worldPositionStays); } } }
module Scoreboard class Team attr_reader :name, :score attr_writer :name, :score def initialize @score = 0 @name = "NA" end def field_goal @score += 3 end def touchdown @score += 7 end def to_s "Team name: #{@name} - Score: #{@score}" end def inspect to_s end end end
CREATE TABLE `user` ( `ID` int(10) DEFAULT NULL, `AGE` tinyint(3) DEFAULT NULL, `NAME` varchar(50) DEFAULT NULL, `WEIGHT` float(3,0) DEFAULT NULL, `SEX` bit(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
import React from 'react' import takeSamples from './take_samples' import {paramSignatures} from './model' const ResultLine = ({points}) => <polyline style={{fill:'none', stroke:'blue', strokeWidth: '0.5%'}} points={ points.map(({t,v}) => [t,1 - v].join(' ')).join(' ') }/> const Circle = ({point}) => <circle r="1%" cx={point.t} cy={1 - (point.v || 0)} style={{fill: 'red'}}/> const Segment = ({segment, remove, change}) => { return ( <li> <form onChange={ e => { let method = e.currentTarget.method.value change( _.merge( {method: method}, paramSignatures[method] .map(label => ({[label]: +_.get(e.currentTarget, [label, 'value'], 0)})) .reduce(_.merge) ) )}}> <button onClick={remove}>X</button> <label>method <select value={segment.method} name='method' onChange={ _ => {} }> {_.keys(paramSignatures).map(method => <option key={method}>{method}</option>)} </select> </label> {paramSignatures[segment.method].map( (label) => <label key={label}>{label} <input type='range' name={label} min='0' max='1' step='0.01' value={segment[label]} onChange={ _ => {} }/> </label>) } </form> </li> ) } export default ({model, store}) => { const addPoint = e => { const {left: l, top: t, height: h, width: w} = e.currentTarget.getClientRects()[0], {clientX: x, clientY: y} = e store.dispatch({type: 'ADD_SEGMENT', v: 1 - (y - t) / h , t: (x - l) / w}) takeSamples(store) }, removeSegment = i => { return (e) => { e.preventDefault() store.dispatch({type: 'REMOVE_SEGMENT', index: i}) takeSamples(store) } }, changeSegment = i => { return (e) => { store.dispatch(_.merge(e, {type: 'CHANGE_SEGMENT', index: i})) takeSamples(store) } } return ( <article> <svg width={model.get('width')} onClick={addPoint} viewBox="0 0 1 1" style={{borderStyle: 'solid'}}> <g> <ResultLine points={model.get('points')}/> {model.get('segments').map( (s,i) => <Circle key={i} point={s.toJS()}/>)} </g> </svg> <ul style={{float: 'right'}} > {model.get('segments').map( (s,i) => <Segment key={i} segment={s.toJS()} remove={removeSegment(i)} change={changeSegment(i)} />)} </ul> </article> ) }
<?php /** * This file is part of Helix package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Helix\Container; use Helix\Container\Definition\DefinitionInterface; use Helix\Container\Definition\DefinitionRegistrarInterface; use Helix\Container\Definition\FactoryDefinition; use Helix\Container\Definition\InstanceDefinition; use Helix\Container\Definition\SingletonDefinition; use Helix\Container\Definition\WeakSingletonDefinition; use Helix\Container\Exception\ServiceNotFoundException; use Helix\Container\ParamResolver\ContainerServiceResolver; use Helix\Container\ParamResolver\ValueResolverInterface; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; /** * @template-implements \IteratorAggregate<non-empty-string, DefinitionInterface> */ final class Container implements ContainerInterface, RegistrarInterface, DispatcherInterface, InstantiatorInterface { /** * @var Registry */ private readonly Registry $definitions; /** * @var ParamResolverInterface */ private readonly ParamResolverInterface $resolver; /** * @var InstantiatorInterface */ private readonly InstantiatorInterface $instantiator; /** * @var DispatcherInterface */ private readonly DispatcherInterface $dispatcher; /** * @param ContainerInterface|null $parent */ public function __construct( private readonly ?ContainerInterface $parent = null, ) { $this->resolver = new ParamResolver([ new ContainerServiceResolver($this), ]); $this->definitions = new Registry(); $this->instantiator = new Instantiator($this->definitions, $this->resolver); $this->dispatcher = new Dispatcher($this, $this->resolver); $this->registerSelf(); } /** * @template TIdentifier as object * * @param non-empty-string|class-string<TIdentifier> $id * @param \Closure():TIdentifier|null $registrar * @return DefinitionRegistrarInterface */ public function singleton(string $id, \Closure $registrar = null): DefinitionRegistrarInterface { return $this->define($id, new SingletonDefinition( $this->detach($registrar ?? fn () => $this->make($id)) )); } /** * @template TIdentifier as object * * @param non-empty-string|class-string<TIdentifier> $id * @param \Closure():TIdentifier|null $registrar * @return DefinitionRegistrarInterface */ public function weak(string $id, \Closure $registrar = null): DefinitionRegistrarInterface { return $this->define($id, new WeakSingletonDefinition( $this->detach($registrar ?? fn () => $this->make($id)) )); } /** * @template TIdentifier as object * * @param non-empty-string|class-string<TIdentifier> $id * @param \Closure():TIdentifier|null $registrar * @return DefinitionRegistrarInterface */ public function factory(string $id, \Closure $registrar = null): DefinitionRegistrarInterface { return $this->define($id, new FactoryDefinition( $this->detach($registrar ?? fn () => $this->make($id)) )); } /** * @param object $id * @return DefinitionRegistrarInterface */ public function instance(object $id): DefinitionRegistrarInterface { return $this->define($id::class, new InstanceDefinition($id)); } /** * {@inheritDoc} */ public function define(string $id, DefinitionInterface $service): DefinitionRegistrarInterface { return $this->definitions->define($id, $service); } /** * {@inheritDoc} */ public function alias(string $id, string $alias): void { $this->definitions->alias($id, $alias); } /** * @template T of object * * @param non-empty-string|class-string<T>|interface-string<T> $id * @param iterable<ValueResolverInterface> $resolvers * @return T * @throws ServiceNotFoundException * @throws ContainerExceptionInterface */ public function get(string $id, iterable $resolvers = []): object { if ($this->parent?->has($id)) { return $this->parent->get($id); } if ($this->definitions->has($id)) { $definition = $this->definitions->get($id); return $definition->resolve(); } return $this->make($id, $resolvers); } /** * @param non-empty-string $id * @return bool */ public function has(string $id): bool { return $this->parent?->has($id) || $this->definitions->has($id); } /** * {@inheritDoc} */ public function call(callable|string $fn, iterable $resolvers = []): mixed { return $this->dispatcher->call($fn, $resolvers); } /** * @param callable|string $fn * @param iterable<ValueResolverInterface> $resolvers * @return \Closure():mixed */ public function detach(callable|string $fn, iterable $resolvers = []): \Closure { return function () use ($fn, $resolvers): mixed { return $this->call($fn, $resolvers); }; } /** * {@inheritDoc} */ public function make(string $id, iterable $resolvers = []): object { return $this->instantiator->make($id, $resolvers); } /** * @return void */ private function registerSelf(): void { $this->instance($this) ->withInterfaces(); } }
%macro mapFloor 2 mov si, word freeX[0] mov ax, %1 mov bx, %2 mov center[si], ax mov center[si+1], bx inc si mov freeX[0], si %endmacro %macro createEntity 3 mov ax, %1 mov bx, %2 mov cx, %3 mov si, word freeX[1] mov entities[si], si inc si mov entities[si], ax inc si mov entities[si], bx inc si mov entities[si], cx inc si mov freeX[1], si %endmacro %macro findEnt 1 saveLocal mov bx, %1 mov ax, 4 imul bx push ax loadLocal %endmacro %macro findCenter 1 saveLocal mov bx, %1 mov ax, 2 imul bx push ax loadLocal %endmacro %macro createGround 3 mov ax, %1 mov bx, %2 mov cx, %3 mov si, word freeX[2] mov ground[si], ax inc si mov ground[si], bx inc si mov ground[3], cx inc si mov freeX[2], si %endmacro %macro createCenter 2 mov ax, %1 mov bx, %2 mov si, word freeX[3] mov center[si], ax inc si mov center[si], bx inc si mov freeX[3], si %endmacro %macro drag 2 findEnt %1 pop si ;ent X inc si mov ax, word entities[si] ;ent Y inc si mov bx, word entities[si] ;center X findCenter %2 pop si mov cx, word center[si] ;center Y inc si mov dx, word center[si] %%tesnex: nout ax cmp ax, cx jb %%toRight jg %%toLeft cmp bx, dx jb %%down jg %%rise %%toRight: inc ax jmp %%tesnex %%toLeft: dec ax jmp %%tesnex %%down: inc bx jmp %%tesnex %%rise: dec bx jmp %%tesnex findEnt %1 pop si ;ent X inc si mov entities[si], ax ;ent Y inc si mov entities[si], bx %endmacro
๏ปฟusing Newtonsoft.Json; namespace Hateoas.Controllers.DataTransferObjects { public class CommentResponseBody : CommentRequestBody { // <remarks> // Id should not be returned to client, but is needed internally for the HAL link // templates. // </remarks> [JsonIgnore] public int Id { get; set; } // <remarks> // Id should not be returned to client, but is needed internally for the HAL link // templates. // </remarks> [JsonIgnore] public override int? AuthorId { get; set; } // <remarks> // Id should not be returned to client, but is needed internally for the HAL link // templates. // </remarks> [JsonIgnore] public override int? ArticleId { get; set; } } }
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { DeletionResponse, MutationCreateTaxRateArgs, MutationDeleteTaxRateArgs, MutationUpdateTaxRateArgs, Permission, QueryTaxRateArgs, QueryTaxRatesArgs, } from '@vendure/common/lib/generated-types'; import { PaginatedList } from '@vendure/common/lib/shared-types'; import { TaxRate } from '../../../entity/tax-rate/tax-rate.entity'; import { TaxRateService } from '../../../service/services/tax-rate.service'; import { RequestContext } from '../../common/request-context'; import { Allow } from '../../decorators/allow.decorator'; import { Ctx } from '../../decorators/request-context.decorator'; import { Transaction } from '../../decorators/transaction.decorator'; @Resolver('TaxRate') export class TaxRateResolver { constructor(private taxRateService: TaxRateService) {} @Query() @Allow(Permission.ReadSettings, Permission.ReadCatalog, Permission.ReadTaxRate) taxRates(@Ctx() ctx: RequestContext, @Args() args: QueryTaxRatesArgs): Promise<PaginatedList<TaxRate>> { return this.taxRateService.findAll(ctx, args.options || undefined); } @Query() @Allow(Permission.ReadSettings, Permission.ReadCatalog, Permission.ReadTaxRate) async taxRate(@Ctx() ctx: RequestContext, @Args() args: QueryTaxRateArgs): Promise<TaxRate | undefined> { return this.taxRateService.findOne(ctx, args.id); } @Transaction() @Mutation() @Allow(Permission.CreateSettings, Permission.CreateTaxRate) async createTaxRate( @Ctx() ctx: RequestContext, @Args() args: MutationCreateTaxRateArgs, ): Promise<TaxRate> { return this.taxRateService.create(ctx, args.input); } @Transaction() @Mutation() @Allow(Permission.UpdateSettings, Permission.UpdateTaxRate) async updateTaxRate( @Ctx() ctx: RequestContext, @Args() args: MutationUpdateTaxRateArgs, ): Promise<TaxRate> { return this.taxRateService.update(ctx, args.input); } @Transaction() @Mutation() @Allow(Permission.DeleteSettings, Permission.DeleteTaxRate) async deleteTaxRate( @Ctx() ctx: RequestContext, @Args() args: MutationDeleteTaxRateArgs, ): Promise<DeletionResponse> { return this.taxRateService.delete(ctx, args.id); } }
package com.github.naz013.compassapp.view import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.view.Gravity import com.github.naz013.compassapp.theming.Palette class AngleLabelPainter(private val paint: Paint) { private var secondaryColor: Int = Color.BLUE private var secondarySolidColor: Int = Color.BLUE private val topRect = Rect() private val bottomRect = Rect() private val textBounds = Rect() var textSizeDegree = 25f var textSize = 15f var bounds: Rect = Rect() var degree: Float = 0f fun updateBounds() { if (bounds.width() == 0 || bounds.height() == 0) return val topHeight = (bounds.height().toFloat() * TOP_HALF_SIZE).toInt() topRect.left = bounds.left topRect.top = bounds.top topRect.right = bounds.right topRect.bottom = bounds.top + topHeight bottomRect.left = bounds.left bottomRect.top = bounds.top + topHeight bottomRect.right = bounds.right bottomRect.bottom = bounds.bottom } fun draw(canvas: Canvas) { paint.color = secondaryColor paint.textSize = textSizeDegree drawText(canvas, degree.toInt().toString() + "ยฐ", paint, Gravity.BOTTOM, topRect) paint.color = secondarySolidColor paint.textSize = textSize drawText(canvas, findSub(degree), paint, Gravity.TOP, bottomRect) } fun setPalette(palette: Palette) { secondaryColor = palette.colorSecondary secondarySolidColor = palette.colorSecondarySolid } private fun drawText(canvas: Canvas, text: String, paint: Paint, vGravity: Int, rect: Rect) { paint.getTextBounds(text, 0, text.length, textBounds) if (vGravity == Gravity.TOP) { canvas.drawText(text, rect.centerX().toFloat(), rect.top.toFloat() + textBounds.height(), paint) } else { canvas.drawText(text, rect.centerX().toFloat(), rect.bottom.toFloat() - textBounds.height() / 2, paint) } } private fun findSub(degree: Float): String { RANGES.forEach { if (it.range.contains(degree)) { return it.label } } return "N" } data class Angle(var range: ClosedFloatingPointRange<Float>, val label: String) companion object { private const val TOP_HALF_SIZE = 0.59f private val RANGES = listOf( Angle(22.5f..67.5f, "NE"), Angle(67.5f..112.5f, "E"), Angle(112.5f..157.5f, "SE"), Angle(157.5f..202.5f, "S"), Angle(202.5f..247.5f, "SW"), Angle(247.5f..292.5f, "W"), Angle(292.5f..337.5f, "NW") ) } }
ts() { tmux kill-session -t k8s tmux new-session -d -s k8s } tc() { tmux select-window -t $1 tmux send-keys 'source k8s-kc-helper.sh' C-m tmux send-keys 'kc' C-m } export -f tc tw() { tc "k8s:0" tmux send-keys 'wk svc,ep,deploy,po,no' C-m } te() { tmux new-window -t k8s:1 tc "k8s:1" tmux send-keys 'vim' C-m } tr() { tmux new-window -t k8s:2 tc "k8s:2" tmux send-keys 'k run --help' } tx() { tmux new-window -t k8s:3 tc "k8s:3" tmux send-keys 'k explain --help' } tk() { ts;tw;te;tr;tx tmux select-window -t k8s:0 tmux attach-session -t k8s } export -f tk
-- This is a test file. CREATE TABLE TABLE1 ( NAME VARCHAR(255), `FIRST_NAME` VARCHAR(255), PROFESSION VARCHAR(50) NOT NULL, CONSTRAINT TABLE1_PK PRIMARY KEY (NAME, FIRST_NAME), FOREIGN KEY (PROFESSION) REFERENCES TABLE2 (PROFESSION) ); CREATE TABLE TABLE2 ( PROFESSION VARCHAR(255), RECOGNITION VARCHAR(255), [COMMENTS] TEXT, PRIMARY KEY (PROFESSION), );
import csv import numpy as np import torch import parameter_calculator as calculator import cardiGAN import hyper_parameters as parameters GEN_PATH = 'saved_models/sample_generator_net.pt' RESULT_PATH = 'data/generated_result.csv' num_samples = 10000 # The number of generated samples. # Load the trained generator model generator = cardiGAN.Generator() generator.load_state_dict(torch.load(GEN_PATH)) generator.eval() # Set the csv writer. out = open(RESULT_PATH, 'w', newline='') csv_write = csv.writer(out, dialect='excel') print("start generating novel CCA compositions...") # Create a Gaussian noise and use the trained generator to generate CCA candidates. g_noise = torch.tensor(np.random.randn(num_samples, parameters.num_latent)).float() cca_candidates = generator(g_noise) + 1e-6 while torch.isnan(torch.sum(cca_candidates)): cca_candidates = generator(g_noise) # Write the headers for the generated dataset. csv_write.writerow(['Element', 'Molar_ratio'] + parameters.empirical_params) # Normalize the compositions and calculate the empirical parameters of the generated candidates. normalized_compositions = cca_candidates / torch.sum(cca_candidates, dim=1).reshape((cca_candidates.shape[0], -1)) calc_result = calculator.calculate_all_parameters(normalized_compositions).detach().numpy() normalized_compositions = normalized_compositions.detach().numpy() # Write the element compositions and empirical parameters of the generated candidates. for i in range(normalized_compositions.shape[0]): element_strings = '' mol_ratio_strings = '' for m in range(parameters.num_elements): if normalized_compositions[i][m] > 0.01: element_strings += (parameters.element_list[m] + '-') mol_ratio_strings += ("{0:.2f}".format(normalized_compositions[i][m]) + '-') csv_write.writerow([element_strings, mol_ratio_strings] + list(calc_result[i])) print("finish generation of " + str(num_samples) + " novel CCA samples.")
package Video::Delay; use strict; use warnings; our $VERSION = 0.08; 1; __END__ =pod =encoding utf8 =head1 NAME Video::Delay - Perl classes for delays between frames generation. =head1 SEE ALSO =over =item L<Video::Delay::Array> Video::Delay class for predefined list of delays. =item L<Video::Delay::Const> Video::Delay class for constant delay. =item L<Video::Delay::Func> Video::Delay class for delays defined by math function. =back =head1 REPOSITORY L<https://github.com/michal-josef-spacek/Video-Delay> =head1 AUTHOR Michal Josef ล paฤek L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT ยฉ 2012-2020 Michal Josef ล paฤek BSD 2-Clause License =head1 VERSION 0.02 =cut
package net.nemerosa.ontrack.extension.general import net.nemerosa.ontrack.extension.api.BuildDisplayNameExtension import net.nemerosa.ontrack.extension.support.AbstractExtension import net.nemerosa.ontrack.model.structure.Build import net.nemerosa.ontrack.model.structure.PropertyService import org.springframework.stereotype.Component @Component class LabelBuildDisplayNameExtension( extensionFeature: GeneralExtensionFeature, private val propertyService: PropertyService ) : AbstractExtension(extensionFeature), BuildDisplayNameExtension { override fun getBuildDisplayName(build: Build): String? { val displayProperty: BuildLinkDisplayProperty? = propertyService.getProperty(build.project, BuildLinkDisplayPropertyType::class.java).value val labelProperty: ReleaseProperty? = propertyService.getProperty(build, ReleasePropertyType::class.java).value return displayProperty.getLabel(build, labelProperty) } }
export type FormResult = { [key: string]: string | number | string[] | number[] | undefined; }; export enum ValidationError { Required = 'required', Invalid = 'invalid', } export enum FieldTypeError { isMultipleAndRadio = 'isMultipleAndRadio', } export type Entry<T> = [string, T]; export type OnFieldChange = (name: string, isDirty: boolean) => void; export interface ValidationErrors { [key: string]: any; }
module Intermed where import Environment getTypeFromIVar :: IVar -> ChType getTypeFromIVar (VarInfo (_, (_, ty, _))) = ty getTypeFromIVar _ = ChVoid type FpAddr = Int type GpAddr = Int data Address = Fp Int | Gp Int -- | Reg Int deriving (Eq) instance Show Address where show (Fp n) = show n ++ "($fp)" show (Gp n) = show n ++ "($gp)" type IVarAddr = Address type IProgram = [IExDecl] data IVar = VarInfo Info | VarAddr IVarAddr deriving (Eq) instance Show IVar where show (VarInfo info) = fst info show (VarAddr addr) = show addr data IExDecl = IDecl [IVar] | IFuncDef IVar [IVar] IStmt deriving (Show) data IStmt = IEmptyStmt | ILetStmt IVar IExpr | IWriteStmt IVar IVar | IReadStmt IVar IVar | IIfStmt IVar [IStmt] [IStmt] | IWhileStmt IVar [IStmt] | ICallStmt IVar Info [IVar] | IReturnStmt IVar | IPrintStmt IVar | ICompoundStmt [IVar] [IStmt] deriving (Show) data IExpr = IVarExpr IVar | IIntExpr Integer | IAopExpr String IVar IVar --op arithmetic | IRelopExpr String IVar IVar --op compare | IAddrExpr IVar deriving (Show)
/* LICENSE Copyright (c) 2013-2016, Jesse Hostetler (jessehostetler@gmail.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * */ package edu.oregonstate.eecs.mcplan.domains.cosmic; import edu.oregonstate.eecs.mcplan.LoggerManager; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntProcedure; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.Map; import ch.qos.logback.classic.Logger; import com.mathworks.toolbox.javabuilder.MWCellArray; import com.mathworks.toolbox.javabuilder.MWNumericArray; import com.mathworks.toolbox.javabuilder.MWStructArray; /** * @author jhostetler * */ public final class CosmicParameters implements AutoCloseable { public final double delta_t = 1.0; public final CosmicMatlabInterface cosmic; public final MWStructArray C; public final MWStructArray index; public final double T; public final int Nbus; public final int Nbranch; public final int Ngenerator; public final int Nmachine; public final int Nexciter; public final int Ngovernor; public final int Nshunt; public final LinkedHashMap<String, Integer> bu_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> br_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> ge_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> ma_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> ex_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> go_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> sh_col_names = new LinkedHashMap<>(); public final LinkedHashMap<String, Integer> ev_col_names = new LinkedHashMap<>(); public final int ev_cols; public final int ev_time; public final int ev_type; public final int ev_trip_branch; public final int ev_branch_loc; public final int ev_trip_bus; public final int ev_bus_loc; public final int ev_shed_load; public final int ev_shunt_loc; public final int ev_trip_shunt; public final int ev_change_by; public final int ev_quantity; public static final int ev_change_by_amount = 0; public static final int ev_change_by_percent = 1; public final Map<Integer, Integer> bus_id_to_matlab_index = new LinkedHashMap<>(); public final TIntIntMap bus_matlab_index_to_id = new TIntIntHashMap(); private final TIntObjectMap<TIntList> bus_to_shunts = new TIntObjectHashMap<>(); public final int Nzones; /** * Map from zone ID to IDs of buses in that zone. */ private final TIntObjectMap<TIntList> zone_to_buses = new TIntObjectHashMap<>(); private final TIntObjectMap<TIntList> zone_to_shunts = new TIntObjectHashMap<>(); /** * Maps a zone ID to the IDs of the branches that need to be cut in order * to isolate that zone from the rest of the grid. */ private final TIntObjectMap<TIntSet> zone_cutsets = new TIntObjectHashMap<>(); public static enum Version { take_action, take_action_iter, take_action2 } private Version version = Version.take_action2; public Version getCosmicVersion() { return version; } public void setCosmicVersion( final Version version ) { this.version = version; } /** * @param cosmic * @param C Owned by CosmicParameters * @param ps NOT owned by CosmicParameters * @param nx * @param ny */ public CosmicParameters( final CosmicMatlabInterface cosmic, final CosmicMatlabInterface.Case cosmic_case, final MWStructArray C, final MWStructArray ps, final MWStructArray index, final double T ) { this.cosmic = cosmic; this.C = C; this.index = index; this.T = T; final Logger log = LoggerManager.getLogger( "log.domain" ); MWStructArray ev = null; try { ev = (MWStructArray) C.getField( "ev", 1 ); ev_cols = (int) ((double[][]) ev.get( "cols", 1 ))[0][0]; // ev_cols = ((MWNumericArray) ev.getField( "cols", 1 )).getInt(); ev_time = (int) ((double[][]) ev.get( "time", 1 ))[0][0]; // ev_time = ((MWNumericArray) ev.getField( "time", 1 )).getInt(); ev_type = (int) ((double[][]) ev.get( "type", 1 ))[0][0]; // ev_type = ((MWNumericArray) ev.getField( "type", 1 )).getInt(); ev_trip_branch = (int) ((double[][]) ev.get( "trip_branch", 1 ))[0][0]; // ev_trip_branch = ((MWNumericArray) ev.getField( "trip_branch", 1 )).getInt(); ev_branch_loc = (int) ((double[][]) ev.get( "branch_loc", 1 ))[0][0]; // ev_branch_loc = ((MWNumericArray) ev.getField( "branch_loc", 1 )).getInt(); ev_trip_bus = (int) ((double[][]) ev.get( "trip_bus", 1 ))[0][0]; // ev_trip_bus = ((MWNumericArray) ev.getField( "trip_bus", 1 )).getInt(); ev_bus_loc = (int) ((double[][]) ev.get( "bus_loc", 1 ))[0][0]; // ev_bus_loc = ((MWNumericArray) ev.getField( "bus_loc", 1 )).getInt(); ev_shed_load = (int) ((double[][]) ev.get( "shed_load", 1 ))[0][0]; // ev_shed_load = ((MWNumericArray) ev.getField( "shed_load", 1 )).getInt(); ev_shunt_loc = (int) ((double[][]) ev.get( "shunt_loc", 1 ))[0][0]; // ev_shunt_loc = ((MWNumericArray) ev.getField( "shunt_loc", 1 )).getInt(); ev_trip_shunt = (int) ((double[][]) ev.get( "trip_shunt", 1 ))[0][0]; // ev_trip_shunt = ((MWNumericArray) ev.getField( "trip_shunt", 1 )).getInt(); ev_change_by = (int) ((double[][]) ev.get( "change_by", 1 ))[0][0]; // ev_change_by = ((MWNumericArray) ev.getField( "change_by", 1 )).getInt(); ev_quantity = (int) ((double[][]) ev.get( "quantity", 1 ))[0][0]; // ev_quantity = ((MWNumericArray) ev.getField( "quantity", 1 )).getInt(); } finally { ev.dispose(); } fillColumnNames( bu_col_names, "bu" ); fillColumnNames( br_col_names, "br" ); fillColumnNames( ge_col_names, "ge" ); fillColumnNames( ma_col_names, "ma" ); fillColumnNames( ex_col_names, "ex" ); fillColumnNames( go_col_names, "go" ); fillColumnNames( sh_col_names, "sh" ); fillColumnNames( ev_col_names, "ev" ); Nbus = M.field_getDimensions( ps, "bus", 1 )[0]; // Nbus = ps.getField( "bus", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "bus", 1 )[1] != bu_col_names.size() ) { // if( ps.getField( "bus", 1 ).getDimensions()[1] != bu_col_names.size() ) { throw new IllegalArgumentException( "ps.bus dimension != col_names" ); } Nbranch = M.field_getDimensions( ps, "branch", 1 )[0]; // Nbranch = ps.getField( "branch", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "branch", 1 )[1] != br_col_names.size() ) { // if( ps.getField( "branch", 1 ).getDimensions()[1] != br_col_names.size() ) { throw new IllegalArgumentException( "ps.branch dimension != col_names" ); } Ngenerator = M.field_getDimensions( ps, "gen", 1 )[0]; // Ngenerator = ps.getField( "gen", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "gen", 1 )[1] < ge_col_names.size() ) { // if( ps.getField( "gen", 1 ).getDimensions()[1] < ge_col_names.size() ) { throw new IllegalArgumentException( "ps.gen dimension != col_names" ); } else if( ps.getField( "gen", 1 ).getDimensions()[1] > ge_col_names.size() ) { log.warn( "ps.gen dimension {} > col_names.size() {}", ps.getField( "gen", 1 ).getDimensions()[1], ge_col_names.size() ); } Nmachine = M.field_getDimensions( ps, "mac", 1 )[0]; // Nmachine = ps.getField( "mac", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "mac", 1 )[1] != ma_col_names.size() ) { // if( ps.getField( "mac", 1 ).getDimensions()[1] != ma_col_names.size() ) { throw new IllegalArgumentException( "ps.mac dimension != col_names" ); } Nexciter = M.field_getDimensions( ps, "exc", 1 )[0]; // Nexciter = ps.getField( "exc", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "exc", 1 )[1] != ex_col_names.size() ) { // if( ps.getField( "exc", 1 ).getDimensions()[1] != ex_col_names.size() ) { throw new IllegalArgumentException( "ps.exc dimension != col_names" ); } Ngovernor = M.field_getDimensions( ps, "gov", 1 )[0]; // Ngovernor = ps.getField( "gov", 1 ).getDimensions()[0]; if( M.field_getDimensions( ps, "gov", 1 )[1] != go_col_names.size() ) { // if( ps.getField( "gov", 1 ).getDimensions()[1] != go_col_names.size() ) { throw new IllegalArgumentException( "ps.gov dimension != col_names" ); } Nshunt = M.field_getDimensions( ps, "shunt", 1 )[0]; // Nshunt = ps.getField( "shunt", 1 ).getDimensions()[0]; // if( M.field_getDimensions( ps, "bus", 1 )[1] != bu_col_names.size() ) { // FIXME: This error check is desirable, but the current Cosmic // code violates it and will need to be fixed first. // if( ps.getField( "shunt", 1 ).getDimensions()[1] != sh_col_names.size() ) { // throw new IllegalArgumentException( "ps.shunt dimension != col_names" ); // } // Initialize bus id to array index map MWNumericArray mbuses = null; try { mbuses = (MWNumericArray) ps.getField( "bus", 1 ); for( int mi = 1; mi <= Nbus; ++mi ) { final int bus_id = mbuses.getInt( new int[] { mi, bu_col_names.get( "id" ) } ); bus_id_to_matlab_index.put( bus_id, mi ); bus_matlab_index_to_id.put( mi, bus_id ); } } finally { mbuses.dispose(); } // Initialize bus_to_shunts map for( final Map.Entry<Integer, Integer> e : bus_id_to_matlab_index.entrySet() ) { bus_to_shunts.put( e.getKey(), new TIntArrayList() ); } // bus_matlab_index.forEachKey( new TIntProcedure() { // @Override // public boolean execute( final int id ) // { // bus_to_shunts.put( id, new TIntArrayList() ); // return true; // } // } ); MWNumericArray mshunts = null; try { mshunts = (MWNumericArray) ps.getField( "shunt", 1 ); for( int mi = 1; mi <= Nshunt; ++mi ) { final int shunt_id = mshunts.getInt( new int[] { mi, sh_col_names.get( "id" ) } ); final int bus_id = mshunts.getInt( new int[] { mi, sh_col_names.get( "bus" ) } ); bus_to_shunts.get( bus_id ).add( shunt_id ); } } finally { mshunts.dispose(); } // FIXME: The code below here must come *after* the calls to fillColumnNames() // above. This is because Bus, etc. depend on fields of CosmicParameters. // Thus we are calling code that depends on CosmicParameters being initialized // *during execution of CosmicParameters's constructor*, which is bad! // Initialize zone_to_buses map // for( int mi = 1; mi <= Nbus; ++mi ) { for( final int id : bus_id_to_matlab_index.keySet() ) { // final Bus bus = new Bus( mi, this, ps ); final Bus bus = new Bus( id, this, ps ); final int zone = bus.zone(); TIntList zone_buses = zone_to_buses.get( zone ); if( zone_buses == null ) { zone_buses = new TIntArrayList(); zone_to_buses.put( zone, zone_buses ); } zone_buses.add( bus.id() ); } Nzones = zone_to_buses.size(); // Initialize zone_to_shunts map for( final int zone : zone_to_buses.keys() ) { final TIntList zone_shunts = new TIntArrayList(); final TIntList buses = zone_to_buses.get( zone ); final TIntIterator bus_itr = buses.iterator(); while( bus_itr.hasNext() ) { final TIntList bus_shunts = bus_to_shunts.get( bus_itr.next() ); final TIntIterator sh_itr = bus_shunts.iterator(); while( sh_itr.hasNext() ) { zone_shunts.add( sh_itr.next() ); } } zone_to_shunts.put( zone, zone_shunts ); } // Initialize zone_cutsets map zone_to_buses.forEachKey( new TIntProcedure() { @Override public boolean execute( final int id ) { zone_cutsets.put( id, new TIntHashSet() ); return true; } } ); // for( int mi = 1; mi <= Nzones; ++mi ) { // zone_cutsets.put( mi, new TIntHashSet() ); // } for( int mi = 1; mi <= Nbranch; ++mi ) { final Branch br = new Branch( mi, this, ps ); final int from = br.from(); final int to = br.to(); final int from_zone = new Bus( from, this, ps ).zone(); final int to_zone = new Bus( to, this, ps ).zone(); if( from_zone != to_zone ) { zone_cutsets.get( from_zone ).add( br.id() ); zone_cutsets.get( to_zone ).add( br.id() ); } } if( log.isInfoEnabled() ) { for( int mi = 1; mi <= Nzones; ++mi ) { final TIntSet cutset = zone_cutsets.get( mi ); log.info( "Zone " + mi + ": cutset " + cutset ); } } } private void fillColumnNames( final LinkedHashMap<String, Integer> names, final String category ) { MWStructArray cat = null; MWCellArray col_names = null; try { cat = (MWStructArray) C.getField( category, 1 ); col_names = (MWCellArray) cat.getField( "col_names", 1 ); for( int i = 1; i <= col_names.numberOfElements(); ++i ) { names.put( new String( (char[]) col_names.getCell( i ).getData() ), i ); } } finally { cat.dispose(); col_names.dispose(); } } public int matlabIndex( final Bus bus ) { return bus_id_to_matlab_index.get( bus.id() ); } public int bus_id_at( final int mi ) { return bus_matlab_index_to_id.get( mi ); } public TIntIterator shuntsForBus( final int bus_id ) { return bus_to_shunts.get( bus_id ).iterator(); } public TIntList shuntsForZone( final int zone ) { return zone_to_shunts.get( zone ); } public TIntSet zoneCutset( final int zone_id ) { return zone_cutsets.get( zone_id ); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); try { for( final Field f : CosmicParameters.class.getFields() ) { sb.append( f.getName() ).append( ": " ).append( f.get( this ) ).append( "\n" ); } } catch( IllegalArgumentException | IllegalAccessException ex ) { throw new RuntimeException( ex ); } return sb.toString(); } @Override public void close() { C.dispose(); } }
# -*- coding: utf-8 -*- """ walle-web :copyright: ยฉ 2015-2017 walle-web.io :created time: 2017-03-25 11:15:01 :author: wushuiyong@walle-web.io """ from flask import request from walle.api.api import SecurityResource from walle.model.menu import MenuModel from walle.model.role import RoleModel class AccessAPI(SecurityResource): controller = 'access' """ ๆƒ้™ๆ˜ฏไปฅresource + methodไฝœไธบไธ€ไธชaccess """ def get(self, access_id=None): """ fetch access list or one access :return: """ super(AccessAPI, self).get() return self.item(access_id) if access_id else self.list() def list(self): """ fetch access list /access/ :return: """ access_model = MenuModel() access_list = access_model.list() return self.render_json(data=access_list) def item(self, access_id): """ /access/<int:access_id> :param access_id: :return: """ access_info = RoleModel().list(size=1000) data = MenuModel.query.all() list = [p.to_json() for p in data] return self.render_json(data=list) def post(self): """ ๆ–ฐๅขž่ง’่‰ฒ /access/ :return: """ super(AccessAPI, self).post() access_name = request.form.get('access_name', None) access_permissions_ids = request.form.get('access_ids', '') access_model = RoleModel() access_id = access_model.add(name=access_name, access_ids=access_permissions_ids) if not access_id: self.render_json(code=-1) return self.render_json(data=access_model.item()) def put(self, access_id): """ ไฟฎๆ”น่ง’่‰ฒ /access/<int:access_id> :param access_id: :return: """ super(AccessAPI, self).put() access_name = request.form.get('access_name', None) access_ids = request.form.get('access_ids', '') if not access_name: return self.render_json(code=-1, message='access_name can not be empty') access_model = RoleModel(id=access_id) ret = access_model.update(name=access_name, access_ids=access_ids) return self.render_json(data=access_model.item()) def delete(self, access_id): """ ๅˆ ้™คไธ€ไธช่ง’่‰ฒ /access/<int:access_id> :return: """ super(AccessAPI, self).delete() access_model = RoleModel(id=access_id) ret = access_model.remove() return self.render_json(code=0)
import os import sys import time from logging import LogRecord, getLogger, basicConfig, getLevelName, INFO, WARNING, Formatter, makeLogRecord from logging.handlers import BufferingHandler from threading import Thread, Event from six.moves.queue import Queue from ...backend_api.services import events from ...backend_api.session.session import MaxRequestSizeError from ...config import config buffer_capacity = config.get('log.task_log_buffer_capacity', 100) class TaskHandler(BufferingHandler): __flush_max_history_seconds = 30. __wait_for_flush_timeout = 10. __max_event_size = 1024*1024 __once = False @property def task_id(self): return self._task_id @task_id.setter def task_id(self, value): self._task_id = value def __init__(self, session, task_id, capacity=buffer_capacity): super(TaskHandler, self).__init__(capacity) self.task_id = task_id self.session = session self.last_timestamp = 0 self.counter = 1 self._last_event = None self._exit_event = None self._queue = None self._thread = None self._pending = 0 def shouldFlush(self, record): """ Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. """ if self._task_id is None: return False # if we need to add handlers to the base_logger, # it will not automatically create stream one when first used, so we must manually configure it. if not TaskHandler.__once: base_logger = getLogger() if len(base_logger.handlers) == 1 and isinstance(base_logger.handlers[0], TaskHandler): if record.name != 'console' and not record.name.startswith('trains.'): base_logger.removeHandler(self) basicConfig() base_logger.addHandler(self) TaskHandler.__once = True else: TaskHandler.__once = True # if we passed the max buffer if len(self.buffer) >= self.capacity: return True # if the first entry in the log was too long ago. try: if len(self.buffer) and (time.time() - self.buffer[0].created) > self.__flush_max_history_seconds: return True except: pass return False def _record_to_event(self, record): # type: (LogRecord) -> events.TaskLogEvent if self._task_id is None: return None timestamp = int(record.created * 1000) if timestamp == self.last_timestamp: timestamp += self.counter self.counter += 1 else: self.last_timestamp = timestamp self.counter = 1 # ignore backspaces (they are often used) full_msg = record.getMessage().replace('\x08', '') return_events = [] while full_msg: msg = full_msg[:self.__max_event_size] full_msg = full_msg[self.__max_event_size:] # unite all records in a single second if self._last_event and timestamp - self._last_event.timestamp < 1000 and \ len(self._last_event.msg) + len(msg) < self.__max_event_size and \ record.levelname.lower() == str(self._last_event.level): # ignore backspaces (they are often used) self._last_event.msg += '\n' + msg continue # if we have a previous event and it timed out, return it. new_event = events.TaskLogEvent( task=self.task_id, timestamp=timestamp, level=record.levelname.lower(), worker=self.session.worker, msg=msg ) if self._last_event: return_events.append(self._last_event) self._last_event = new_event return return_events def flush(self): if self._task_id is None: return if not self.buffer: return self.acquire() if self.buffer: buffer = self.buffer self.buffer = [] self.release() if not buffer: return try: record_events = [r for record in buffer for r in self._record_to_event(record)] + [self._last_event] self._last_event = None batch_requests = events.AddBatchRequest(requests=[events.AddRequest(e) for e in record_events if e]) except Exception: self.__log_stderr("WARNING: trains.log - Failed logging task to backend ({:d} lines)".format(len(buffer))) batch_requests = None if batch_requests: self._pending += 1 self._add_to_queue(batch_requests) def _create_thread_queue(self): if self._queue: return self._queue = Queue() self._exit_event = Event() self._exit_event.clear() # multiple workers could be supported as well self._thread = Thread(target=self._daemon) self._thread.daemon = True self._thread.start() def _add_to_queue(self, request): self._create_thread_queue() self._queue.put(request) def close(self, wait=False): # self.__log_stderr('Closing {} wait={}'.format(os.getpid(), wait)) # flush pending logs if not self._task_id: return # avoid deadlocks just skip the lock, we are shutting down anyway self.lock = None self.flush() # shut down the TaskHandler, from this point onwards. No events will be logged _thread = self._thread self._thread = None if self._queue: self._exit_event.set() self._queue.put(None) self._task_id = None if wait and _thread: try: timeout = 1. if self._queue.empty() else self.__wait_for_flush_timeout _thread.join(timeout=timeout) if not self._queue.empty(): self.__log_stderr('Flush timeout {}s exceeded, dropping last {} lines'.format( timeout, self._queue.qsize())) # self.__log_stderr('Closing {} wait done'.format(os.getpid())) except: pass # call super and remove the handler super(TaskHandler, self).close() def _send_events(self, a_request): try: # if self._thread is None: # self.__log_stderr('Task.close() flushing remaining logs ({})'.format(self._pending)) self._pending -= 1 res = self.session.send(a_request) if not res.ok(): self.__log_stderr("failed logging task to backend ({:d} lines, {})".format( len(a_request.requests), str(res.meta)), level=WARNING) except MaxRequestSizeError: self.__log_stderr("failed logging task to backend ({:d} lines) log size exceeded limit".format( len(a_request.requests)), level=WARNING) except Exception as ex: self.__log_stderr("Retrying, failed logging task to backend ({:d} lines): {}".format( len(a_request.requests), ex)) # we should push ourselves back into the thread pool if self._queue: self._pending += 1 self._queue.put(a_request) def _daemon(self): # multiple daemons are supported leave = self._exit_event.wait(0) request = True while not leave or request: # pull from queue request = None if self._queue: try: request = self._queue.get(block=not leave) except: pass if request: self._send_events(request) leave = self._exit_event.wait(0) # self.__log_stderr('leaving {}'.format(os.getpid())) @staticmethod def __log_stderr(msg, level=INFO): # output directly to stderr, make sure we do not catch it. write = sys.stderr._original_write if hasattr(sys.stderr, '_original_write') else sys.stderr.write write('{asctime} - {name} - {levelname} - {message}\n'.format( asctime=Formatter().formatTime(makeLogRecord({})), name='trains.log', levelname=getLevelName(level), message=msg))
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Traits\CheckTraits; use Illuminate\Support\Facades\File; use App\Jobs\AuditJob; use Illuminate\Support\Facades\Storage; use Exception; class AuditController extends Controller { use CheckTraits; public function fetchAudit() { $shopName = $this->shopName(); $isAudit = (shopSetting($this->shopId(), 'is_audit', 'no') == 'no') ? false : true; $isAuditScan = (shopSetting($this->shopId(), 'is_audit_scan', 'no') == 'no') ? false : true; $fileContent=[]; $fileContent += ['isAudit' => $isAudit, 'isScan' => $isAuditScan]; if (file_exists(public_path("page/report.{$shopName}.html"))){ $fileContent +=['page' => "page/report.{$shopName}.html"] ; } return response()->json($fileContent); } public function scanAudit() { try{ if (!file_exists(public_path("page"))){ File::makeDirectory(public_path("page")); } shopSetting($this->shopId(), ['is_audit_scan' => 'yes']); $shopName = $this->shopName(); $id = $this->shopId(); $lr = env('LIGHTHOUSE'); AuditJob::dispatch($shopName, $id, $lr)->onQueue('Audit'); }catch (Exception $e){ logger("{$this->shopName()}: Audit job fail at {$e->getMessage()}, {$e->getTraceAsString()}"); } } }
package com.tooppoo import org.scalatest.funspec.AnyFunSpec import org.scalatest.prop.TableDrivenPropertyChecks /** * [ ] ็•ฐใชใ‚‹ๅบงๆจ™ใ‚’ๆŒใค๏ผ’ใคใฎๆ ผๅญ็‚นใ‚’ๅซใ‚€ๆ ผๅญ็‚น้›†ๅˆ(grid points)ใ‚’ๅฐŽๅ…ฅใ—ใพใ™ใ€‚ * [x] GridPointSetๅฎš็พฉ * [x] GridPointSetใฏ๏ผ’ใคใฎๆ ผๅญ็‚นใ‚’ๆŒใค * [x] 2ใคใฎๆ ผๅญ็‚นใŒ็•ฐใชใ‚‹ๅบงๆจ™ใ‚’ๆŒใค * [x] 2ใคใฎๆ ผๅญ็‚นใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค * [x] ๆ ผๅญ็‚น้›†ๅˆใŒใ€ๆŒ‡ๅฎšใ—ใŸๆ ผๅญ็‚นใ‚’ๅซใ‚€(contains)ใ‹ใ‚’ๅˆคๅฎšใ—ใฆใใ ใ•ใ„ * [x] ๆ ผๅญ็‚นAใจไธ€่‡ด : true * [x] ๆ ผๅญ็‚นBใจไธ€่‡ด : true * [x] ๆ ผๅญ็‚นA/Bไธกๆ–นใจไธไธ€่‡ด : false * [x] ๆ ผๅญ็‚น้›†ๅˆใŒ้€ฃ็ตใ—ใฆใ„ใ‚‹(connected)ใ‹ใ‚’ๅˆคๅฎšใ—ใฆใใ ใ•ใ„ * (่ฃœ่ถณ) ๆ ผๅญ็‚น้›†ๅˆใซๅซใพใ‚Œใ‚‹๏ผ’ใคใฎๆ ผๅญ็‚นใŒ้šฃใ‚Šๅˆใฃใฆใ„ใ‚‹ๅ ดๅˆใซ้™ใ‚Šใ€ใใฎๆ ผๅญ็‚น้›†ๅˆใŒ้€ฃ็ตใ—ใฆใ„ใ‚‹ใ‚‚ใฎใจใ—ใพใ™ * [x] AใŒBใฎๅทฆ * [x] AใŒBใฎๅทฆไธŠ * [x] AใŒBใฎไธŠ * [x] AใŒBใฎๅณไธŠ * [x] AใŒBใฎๅณ * [x] AใŒBใฎๅณไธ‹ * [x] AใŒBใฎไธ‹ * [x] AใŒBใฎๅทฆไธ‹ * [x] ๆ ผๅญ็‚น้›†ๅˆใ‚’ใ€็•ฐใชใ‚‹๏ผ’ใคใพใŸใฏ๏ผ“ใคใฎๆ ผๅญ็‚นใ‚’ๅซใ‚€ใ“ใจใŒๅ‡บๆฅใ‚‹ใ‚ˆใ†ใซๆ‹กๅผตใ—ใฆใใ ใ•ใ„ * [x] 3ใคใฎๆ ผๅญ็‚นใ‚’ๅ—ใ‘ๅ–ใ‚Œใ‚‹ใ‚ˆใ†ใซใ™ใ‚‹ * [x] ๅ…จใฆใฎๆ ผๅญ็‚นใฎๅบงๆจ™ใŒ็•ฐใชใ‚‹: OK * [x] 2ใคใฎๆ ผๅญ็‚นใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] AใƒปBใƒปCใฎใ†ใกใ€AใƒปBใŒไธ€่‡ด * [x] AใƒปBใƒปCใฎใ†ใกใ€BใƒปCใŒไธ€่‡ด * [x] AใƒปBใƒปCใฎใ†ใกใ€CใƒปAใŒไธ€่‡ด * [x] ๅ…จใฆใฎๆ ผๅญ็‚นใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] ๆ ผๅญ็‚นใ‚’ๅซใ‚€ใ‹ * [x] Aใซไธ€่‡ด * [x] Bใซไธ€่‡ด * [x] Cใซไธ€่‡ด * [x] ๅ…จใฆใซไธ€่‡ดใ—ใชใ„ * [x] ๆ ผๅญ็‚น้›†ๅˆใซๅซใพใ‚Œใ‚‹ไปปๆ„ใฎๆ ผๅญ็‚นใซใคใ„ใฆ * ใใฎๆ ผๅญ็‚นใ‹ใ‚‰้šฃใ‚Šๅˆใฃใฆใ„ใ‚‹ๆ ผๅญ็‚นใฎใฟใ‚’็ตŒ็”ฑใ—ใฆ * ใใฎไป–ๅ…จใฆใฎๆ ผๅญ็‚นใธๅˆฐ้”ใงใใ‚‹ๅ ดๅˆใซ้™ใ‚Š * ใใฎๆ ผๅญ็‚น้›†ๅˆใŒ้€ฃ็ตใ—ใฆใ„ใ‚‹ใ‚‚ใฎใจใ—ใพใ™ * [x] A-B A-CใŒ้€ฃ็ต ( |_ ๏ผ‰: true * [x] B-A B-CใŒ้€ฃ็ต ( |_ ๏ผ‰: true * [x] C-A C-BใŒ้€ฃ็ต ( |_ ๏ผ‰: true * [x] A-B B-CใŒ้€ฃ็ต๏ผˆ -- ) : true * [x] A-C C-BใŒ้€ฃ็ต๏ผˆ -- ) : true * [x] B-A A-CใŒ้€ฃ็ต๏ผˆ -- ) : true * [x] A-B ้€ฃ็ต ๏ผˆ | . ) : false * [x] B-C ้€ฃ็ต ๏ผˆ | . ) : false * [x] A-C ้€ฃ็ต ๏ผˆ | . ) : false * [x] ้€ฃ็ต็„กใ— ๏ผˆ . . . ) : false * [x] ๆ ผๅญ็‚น้›†ๅˆใ‹ใ‚‰ใ€ๆ ผๅญ็‚น้›†ๅˆใซๅซใพใ‚Œใฆใ„ใ‚‹ๆ ผๅญ็‚นใฎๆ•ฐ(count)ใ‚’ๅ–ๅพ—ใ—ใฆใใ ใ•ใ„ * [x] ๆ ผๅญ็‚น้›†ๅˆใ‚’ใ€็•ฐใชใ‚‹๏ผ’ใ€œ๏ผ”ใคใฎๆ ผๅญ็‚นใ‚’ๅซใ‚€ใ“ใจใŒๅ‡บๆฅใ‚‹ใ‚ˆใ†ใซๆ‹กๅผตใ—ใฆใใ ใ•ใ„ * [x] 4ใคใฎๆ ผๅญ็‚นใ‚’ๅ—ใ‘ๅ–ใ‚Œใ‚‹ใ‚ˆใ†ใซใ™ใ‚‹ * [x] ๅ…จใฆใฎๆ ผๅญ็‚นใฎๅบงๆจ™ใŒ็•ฐใชใ‚‹: OK * [x] AใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] BใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] CใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] AใƒปBใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] AใƒปCใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] BใƒปCใƒปDใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] ๅ…จใฆใฎๆ ผๅญ็‚นใฎๅบงๆจ™ใŒๅŒใ˜ : NG * [x] ้€ฃ็ต * [x] --- : true * [x] _|_ : true * [x] _ | : false * [x] . | . : false * [x] ๆ ผๅญ็‚น้›†ๅˆใŒไธ€็ญ†ๆ›ธใใงใใ‚‹ใ‹(traversable)ใ‚’ๅˆคๅฎšใ—ใฆใใ ใ•ใ„ * (่ฃœ่ถณ) ๆ ผๅญ็‚น้›†ๅˆใซๅซใพใ‚Œใ‚‹ใ‚ใ‚‹ๆ ผๅญ็‚นใซใคใ„ใฆ * ใใฎๆ ผๅญ็‚นใ‹ใ‚‰้šฃใ‚Šๅˆใฃใฆใ„ใ‚‹ๆ ผๅญ็‚นใฎใฟใ‚’็ตŒ็”ฑใ—ใฆ * ๆœ€็ต‚็š„ใซๅ…จใฆใฎๆ ผๅญ็‚นใ‚’ใกใ‚‡ใ†ใฉไธ€ๅบฆใšใค็ตŒ็”ฑใ™ใ‚‹็ต„ใฟๅˆใ‚ใ›ใŒใ‚ใ‚‹ๅ ดๅˆใซ้™ใ‚Š * ใใฎๆ ผๅญ็‚น้›†ๅˆใŒไธ€็ญ†ๆ›ธใใงใใ‚‹ใ‚‚ใฎใจใ—ใพใ™ * [x] 2็‚น * [x] ้šฃๆŽฅใ—ใฆใ„ใ‚‹ : true * [x] ้šฃๆŽฅใ—ใฆใ„ใชใ„: false * [x] 3็‚น * [x] ้€ฃ็ตใ—ใฆใ„ใ‚‹ : true * [x] ้€ฃ็ตใ—ใฆใ„ใชใ„ : false * [x] 4็‚น * [x] --- ใง้€ฃ็ต : true * [x] ๅ…ˆ้ ญใฎ็‚น = ไธ€็•ช็›ฎใฎ็‚น : true * [x] ๅ…ˆ้ ญใฎ็‚น = ไบŒ็•ช็›ฎใฎ็‚น : true * [x] _|_ ใง้€ฃ็ต : false * [x] ๆ ผๅญ็‚น้›†ๅˆใ‚’ใ€็•ฐใชใ‚‹Nๅ€‹ใฎๆ ผๅญ็‚น(Nใฏ2ไปฅไธŠใฎๆ•ดๆ•ฐ)ใŒๆ‰ฑใˆใ‚‹ใ‚ˆใ†ใซๆ‹กๅผต * [ ] ๆ ผๅญ็‚นๅŠใณๆ ผๅญ็‚น้›†ๅˆใ‚’ใ€๏ผ“ๆฌกๅ…ƒๅบงๆจ™ไธŠใงๆ‰ฑใˆใ‚‹ใ‚ˆใ†ใซๆ‹กๅผตใ—ใฆใใ ใ•ใ„ * ๏ผ’ๆฌกๅ…ƒๅบงๆจ™ไธŠใฎๆ ผๅญ็‚น๏ผๆ ผๅญ็‚น้›†ๅˆใจ * ๏ผ“ๆฌกๅ…ƒๅบงๆจ™ไธŠใฎๆ ผๅญ็‚น๏ผๆ ผๅญ็‚น้›†ๅˆใ‚’ * ๅŒๆ™‚ใซๆ‰ฑใˆใ‚‹ๅฟ…่ฆใฏใ‚ใ‚Šใพใ›ใ‚“ */ class TwoDimensionTwoDimensionGridPointSetSpec extends AnyFunSpec with TableDrivenPropertyChecks { describe("ๆ ผๅญ็‚น้›†ๅˆใฎ็”Ÿๆˆ") { describe("็”Ÿๆˆใงใใ‚‹") { val cases = Table( ("case name", "create set"), ( "2ใคใฎๆ ผๅญ็‚นใŒ็•ฐใชใ‚‹ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(3, 6)) ), ( "3ใคใฎๆ ผๅญ็‚นใŒ็•ฐใชใ‚‹ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(3, 6), GridPoint(2, 4)) ), ( "4ใคใฎๆ ผๅญ็‚นใŒ็•ฐใชใ‚‹ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(3, 6), GridPoint(2, 4), GridPoint(1, 2)) ) ) forAll(cases) { (caseName, create) => it(caseName) { create() succeed // ไพ‹ๅค–ใŒ่ตทใใชใ‘ใ‚ŒใฐOK } } } describe("็”Ÿๆˆใงใใชใ„") { describe("ๆ ผๅญ็‚นใŒ2ใค") { val cases = Table( ("case name", "create set"), ("2ใคใฎๆ ผๅญ็‚นใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(4, 7))) ) forAll(cases) { (caseName, create) => it(caseName) { assertThrows[IllegalArgumentException] { create() } } } } describe("ๆ ผๅญ็‚นใŒ3ใค[A, B, C]") { val cases = Table( ("case name", "create set"), ("AใƒปBใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(4, 7), GridPoint(3, 2))), ("BใƒปCใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(3, 2), GridPoint(4, 7), GridPoint(4, 7))), ("CใƒปAใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(3, 2), GridPoint(4, 7))), ("ๅ…จใฆๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(4, 7), GridPoint(4, 7))), ) forAll(cases) { (caseName, create) => it(caseName) { assertThrows[IllegalArgumentException] { create() } } } } describe("ๆ ผๅญ็‚นใŒ4ใค[A, B, C, D]") { val cases = Table( ("case name", "create set"), ("AใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(3, 7), GridPoint(2, 7), GridPoint(4, 7))), ("BใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(3, 7), GridPoint(4, 7), GridPoint(2, 7), GridPoint(4, 7))), ("CใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(3, 7), GridPoint(2, 7), GridPoint(4, 7), GridPoint(4, 7))), ("AใƒปBใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(4, 7), GridPoint(2, 7), GridPoint(4, 7))), ("AใƒปCใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(2, 7), GridPoint(4, 7), GridPoint(4, 7))), ("BใƒปCใƒปDใŒๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(2, 7), GridPoint(4, 7), GridPoint(4, 7), GridPoint(4, 7))), ("ๅ…จใฆๅŒใ˜ๅบงๆจ™ใ‚’ๆŒใค", () => GridPointSet(GridPoint(4, 7), GridPoint(4, 7), GridPoint(4, 7), GridPoint(4, 7))), ) forAll(cases) { (caseName, create) => it(caseName) { assertThrows[IllegalArgumentException] { create() } } } } } } describe("ๆ–‡ๅญ—ๅˆ—่กจ่จ˜") { describe("[4,6], [4,7]") { val a = GridPoint(4, 6) val b = GridPoint(4, 7) val set = GridPointSet(a, b) it("[(4,6),(4,7)]") { assert(set.notation == "[(4,6),(4,7)]") } } } describe("ๆ ผๅญ็‚น้›†ๅˆ[A, B]ใŒใ€ๆŒ‡ๅฎšใ—ใŸๆ ผๅญ็‚นใ‚’ๅซใ‚€(contains)ใ‹") { describe("A: (4,7), B: (2, 5)") { val a = GridPoint(4, 7) val b = GridPoint(2, 5) val set = GridPointSet(a, b) val grids = Table( ("case name", "grid", "expected"), ("Aใจไธ€่‡ด", GridPoint(4, 7), true), ("Bใจไธ€่‡ด", GridPoint(2, 5), true), ("A/Bไธกๆ–นใจไธไธ€่‡ด", GridPoint(3, 6), false), ) forAll(grids) { (caseName, grid, expected) => describe(caseName) { describe(s"${grid.notation}") { assert((set contains grid) == expected) } } } } describe("A: (4,7), B: (2, 5), C: (3, 6)") { val a = GridPoint(4, 7) val b = GridPoint(2, 5) val c = GridPoint(3, 6) val set = GridPointSet(a, b, c) val grids = Table( ("case name", "grid", "expected"), ("Aใจไธ€่‡ด", GridPoint(4, 7), true), ("Bใจไธ€่‡ด", GridPoint(2, 5), true), ("Cใจไธ€่‡ด", GridPoint(3, 6), true), ("A/B/Cๅ…จใฆใจไธไธ€่‡ด", GridPoint(1, 2), false), ) forAll(grids) { (caseName, grid, expected) => describe(caseName) { it(s"${grid.notation}") { assert((set contains grid) == expected) } } } } } describe("ๆ ผๅญ็‚น้›†ๅˆใŒ้€ฃ็ตใ—ใฆใ„ใ‚‹(connected)ใ‹") { describe("ๆ ผๅญ็‚นใŒA,Bใฎ2ใค") { val set = Table( ("case name", "gird a", "grid b", "expected"), ("AใŒBใฎๅทฆ้šฃ", GridPoint(4, 7), GridPoint(5, 7), true), ("AใŒBใฎๅทฆไธŠ", GridPoint(4, 8), GridPoint(5, 7), false), ("AใŒBใฎไธŠ", GridPoint(5, 8), GridPoint(5, 7), true), ("AใŒBใฎๅณไธŠ", GridPoint(6, 8), GridPoint(5, 7), false), ("AใŒBใฎๅณ", GridPoint(6, 7), GridPoint(5, 7), true), ("AใŒBใฎๅณไธ‹", GridPoint(6, 6), GridPoint(5, 7), false), ("AใŒBใฎไธ‹", GridPoint(5, 6), GridPoint(5, 7), true), ("AใŒBใฎๅทฆไธ‹", GridPoint(4, 6), GridPoint(5, 7), false), ) forAll(set) { (caseName, gridA, gridB, expected) => describe(caseName) { describe(s"A: ${gridA.notation} B: ${gridB.notation}") { it(s"$expected") { val set = GridPointSet(gridA, gridB) assert(set.isConnected == expected) } } } } } describe("ๆ ผๅญ็‚นใŒA,B,Cใฎ3ใค") { val set = Table( ("case name", "gird a", "grid b", "grid c", "expected"), ("A-B, A-C ้€ฃ็ต |_", GridPoint(4, 4), GridPoint(4, 5), GridPoint(5, 4), true), ("B-A, B-C ้€ฃ็ต |_", GridPoint(4, 5), GridPoint(4, 4), GridPoint(5, 4), true), ("C-A, C-B ้€ฃ็ต |_", GridPoint(4, 5), GridPoint(5, 4), GridPoint(4, 4), true), ("A-B, B-CใŒ้€ฃ็ต --", GridPoint(4, 4), GridPoint(5, 4), GridPoint(6, 4), true), ("A-C, C-BใŒ้€ฃ็ต --", GridPoint(4, 4), GridPoint(6, 4), GridPoint(5, 4), true), ("B-A, A-CใŒ้€ฃ็ต --", GridPoint(5, 4), GridPoint(4, 4), GridPoint(6, 4), true), ("A-BใŒ้€ฃ็ต | .", GridPoint(4, 4), GridPoint(5, 4), GridPoint(6, 5), false), ("B-CใŒ้€ฃ็ต | .", GridPoint(6, 5), GridPoint(4, 4), GridPoint(5, 4), false), ("A-CใŒ้€ฃ็ต | .", GridPoint(4, 4), GridPoint(6, 5), GridPoint(5, 4), false), ("้€ฃ็ต็„กใ—", GridPoint(4, 4), GridPoint(6, 5), GridPoint(5, 3), false), ) forAll(set) { (caseName, gridA, gridB, gridC, expected) => describe(caseName) { describe( s"A: ${gridA.notation} B: ${gridB.notation} C: ${gridC.notation}" ) { it(s"$expected") { val set = GridPointSet(gridA, gridB, gridC) assert(set.isConnected == expected) } } } } } describe("ๆ ผๅญ็‚นใŒA,B,C,Dใฎ4ใค") { val set = Table( ( "case name", "gird a", "grid b", "grid c", "grid d", "expected" ), ( "A-B, B-C, C-D ้€ฃ็ต: ---", GridPoint(4, 4), GridPoint(5, 4), GridPoint(6, 4), GridPoint(7, 4), true ), ( "A-B, B-C, B-D ้€ฃ็ต: _|_", GridPoint(4, 4), GridPoint(5, 4), GridPoint(6, 4), GridPoint(5, 5), true ), ( "B-D, C-D, D-A ้€ฃ็ต: _|_", GridPoint(4, 4), GridPoint(6, 4), GridPoint(5, 5), GridPoint(5, 4), true ), ( "้€ฃ็ตใ—ใฆใ„ใชใ„: |_ .", GridPoint(4, 4), GridPoint(4, 5), GridPoint(6, 5), GridPoint(5, 4), false ), ) forAll(set) { (caseName, gridA, gridB, gridC, gridD, expected) => describe(caseName) { describe( s"A: ${gridA.notation} B: ${gridB.notation} C: ${gridC.notation} D: ${gridD.notation}" ) { it(s"$expected") { val set = GridPointSet(gridA, gridB, gridC, gridD) assert(set.isConnected == expected) } } } } } } describe("ๆ ผๅญ็‚น้›†ๅˆใ‹ใ‚‰ใ€ๆ ผๅญ็‚น้›†ๅˆใซๅซใพใ‚Œใฆใ„ใ‚‹ๆ ผๅญ็‚นใฎๆ•ฐ(count)ใ‚’ๅ–ๅพ—") { describe("้›†ๅˆ[A, B]") { it("2") { val set = GridPointSet(GridPoint(3, 4), GridPoint(4, 5)) assert(set.count == 2) } } } describe("ๆ ผๅญ็‚น้›†ๅˆใŒไธ€็ญ†ๆ›ธใใงใใ‚‹ใ‹(traversable)") { describe("2็‚น") { val set = Table( ("case name", "set", "expected"), ("้šฃๆŽฅใ—ใฆใ„ใ‚‹", GridPointSet(GridPoint(4, 6), GridPoint(4, 7)), true), ("้šฃๆŽฅใ—ใฆใ„ใชใ„", GridPointSet(GridPoint(4, 6), GridPoint(3, 7)), false), ) forAll(set) { (caseName, set, expected) => describe(caseName) { describe(set.notation) { it(s"$expected") { assert(set.isTraversable == expected) } } } } } describe("3็‚น") { val set = Table( ("case name", "set", "expected"), ("้€ฃ็ตใ—ใฆใ„ใ‚‹: |_", GridPointSet(GridPoint(4, 4), GridPoint(4, 3), GridPoint(5, 3)), true), ("้€ฃ็ตใ—ใฆใ„ใ‚‹: --", GridPointSet(GridPoint(4, 4), GridPoint(5, 4), GridPoint(6, 4)), true), ("้€ฃ็ตใ—ใฆใ„ใชใ„: | .", GridPointSet(GridPoint(4, 4), GridPoint(4, 3), GridPoint(6, 3)), false), ("้€ฃ็ตใ—ใฆใ„ใชใ„: . . .", GridPointSet(GridPoint(4, 4), GridPoint(5, 5), GridPoint(6, 6)), false), ) forAll(set) { (caseName, set, expected) => describe(caseName) { describe(set.notation) { it(s"$expected") { assert(set.isTraversable == expected) } } } } } describe("4็‚น") { val set = Table( ( "case name", "set", "expected" ), ( "ๅ…ˆ้ ญใฎ็‚นใ‹ใ‚‰ไธ€็ญ†ๆ›ธใใงใใ‚‹: |_|", GridPointSet(GridPoint(4, 4), GridPoint(4, 3), GridPoint(5, 3), GridPoint(5, 4)), true ), ( "ไบŒ็•ช็›ฎใฎ็‚นใ‹ใ‚‰ไธ€็ญ†ๆ›ธใใงใใ‚‹: |_|", GridPointSet(GridPoint(4, 4), GridPoint(4, 5), GridPoint(5, 3), GridPoint(5, 4)), true ), ( "ไธ€็ญ†ๆ›ธใใงใใชใ„: | _", GridPointSet(GridPoint(4, 4), GridPoint(4, 3), GridPoint(6, 3), GridPoint(7, 3)), false ), ( "ไธ€็ญ†ๆ›ธใใงใใชใ„: _|_", GridPointSet(GridPoint(4, 4), GridPoint(3, 4), GridPoint(5, 4), GridPoint(4, 5)), false ), ) forAll(set) { (caseName, set, expected) => describe(caseName) { describe(set.notation) { it(s"$expected") { assert(set.isTraversable == expected) } } } } } } }
<?php function splitStringToArray($string, $separator) { $array = []; if (str_contains($string, $separator)) { $array = explode(',', $string); } else { $array[] = $string; } return $array; } function isValidTimeStamp($timestamp) { return ((string) (int) $timestamp === $timestamp) && ($timestamp <= PHP_INT_MAX) && ($timestamp >= ~PHP_INT_MAX); } function setResponseLocale($locale) { app()->setLocale($locale); }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package acm import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" ) type ExportCertificateInput struct { _ struct{} `type:"structure"` // An Amazon Resource Name (ARN) of the issued certificate. This must be of // the form: // // arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 // // CertificateArn is a required field CertificateArn *string `min:"20" type:"string" required:"true"` // Passphrase to associate with the encrypted exported private key. If you want // to later decrypt the private key, you must have the passphrase. You can use // the following OpenSSL command to decrypt a private key: // // openssl rsa -in encrypted_key.pem -out decrypted_key.pem // // Passphrase is automatically base64 encoded/decoded by the SDK. // // Passphrase is a required field Passphrase []byte `min:"4" type:"blob" required:"true" sensitive:"true"` } // String returns the string representation func (s ExportCertificateInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *ExportCertificateInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "ExportCertificateInput"} if s.CertificateArn == nil { invalidParams.Add(aws.NewErrParamRequired("CertificateArn")) } if s.CertificateArn != nil && len(*s.CertificateArn) < 20 { invalidParams.Add(aws.NewErrParamMinLen("CertificateArn", 20)) } if s.Passphrase == nil { invalidParams.Add(aws.NewErrParamRequired("Passphrase")) } if s.Passphrase != nil && len(s.Passphrase) < 4 { invalidParams.Add(aws.NewErrParamMinLen("Passphrase", 4)) } if invalidParams.Len() > 0 { return invalidParams } return nil } type ExportCertificateOutput struct { _ struct{} `type:"structure"` // The base64 PEM-encoded certificate. Certificate *string `min:"1" type:"string"` // The base64 PEM-encoded certificate chain. This does not include the certificate // that you are exporting. CertificateChain *string `min:"1" type:"string"` // The encrypted private key associated with the public key in the certificate. // The key is output in PKCS #8 format and is base64 PEM-encoded. PrivateKey *string `min:"1" type:"string" sensitive:"true"` } // String returns the string representation func (s ExportCertificateOutput) String() string { return awsutil.Prettify(s) } const opExportCertificate = "ExportCertificate" // ExportCertificateRequest returns a request value for making API operation for // AWS Certificate Manager. // // Exports a private certificate issued by a private certificate authority (CA) // for use anywhere. You can export the certificate, the certificate chain, // and the encrypted private key associated with the public key embedded in // the certificate. You must store the private key securely. The private key // is a 2048 bit RSA key. You must provide a passphrase for the private key // when exporting it. You can use the following OpenSSL command to decrypt it // later. Provide the passphrase when prompted. // // openssl rsa -in encrypted_key.pem -out decrypted_key.pem // // // Example sending a request using ExportCertificateRequest. // req := client.ExportCertificateRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificate func (c *Client) ExportCertificateRequest(input *ExportCertificateInput) ExportCertificateRequest { op := &aws.Operation{ Name: opExportCertificate, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { input = &ExportCertificateInput{} } req := c.newRequest(op, input, &ExportCertificateOutput{}) return ExportCertificateRequest{Request: req, Input: input, Copy: c.ExportCertificateRequest} } // ExportCertificateRequest is the request type for the // ExportCertificate API operation. type ExportCertificateRequest struct { *aws.Request Input *ExportCertificateInput Copy func(*ExportCertificateInput) ExportCertificateRequest } // Send marshals and sends the ExportCertificate API request. func (r ExportCertificateRequest) Send(ctx context.Context) (*ExportCertificateResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &ExportCertificateResponse{ ExportCertificateOutput: r.Request.Data.(*ExportCertificateOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // ExportCertificateResponse is the response type for the // ExportCertificate API operation. type ExportCertificateResponse struct { *ExportCertificateOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // ExportCertificate request. func (r *ExportCertificateResponse) SDKResponseMetdata() *aws.Response { return r.response }
import numpy as np import numpy.matlib import os from sklearn.externals import joblib class mSDA(object): ''' Implement mSDA. To read more about the SDA, check the following paper: Chen M , Xu Z , Weinberger K , et al. Marginalized Denoising Autoencoders for Domain Adaptation[J]. Computer Science, 2012. This implementation of mSDA is based on both the sample code the authors provided as well as the equations in the paper. The code is modified according to https://github.com/douxu896/mSDA ''' def __init__(self, p=None, l=5, act=np.tanh, Ws=None, bias=True): ''' :param p: corruption probability :param l: number of layers :param act: what nonlinearity to use? if None, not to use nonlinearity. :param Ws: model parameters. Can optionally pass in precomputed Ws to use to transform X. (e.g. if transforming test X with Ws learned from training X) :param bias: Whether to use bias? ''' self.p = p self.l = l self.act = act self.Ws = Ws self.bias = bias def mDA(self, X, W=None): ''' One layer Marginalized Denoising Autoencoder. Learn a representation h of X by reconstructing "corrupted" input but marginalizing out corruption :param X: input features, shape:(num_samples,num_features) :param W: model parameters. Can optionally pass in precomputed W to use to transform X. (e.g. if transforming test X with W learned from training X) :return: model parameters, reconstructed representation. ''' if self.bias: X=np.hstack((X, np.ones((X.shape[0], 1)))) if W is None: W = self._compute_reconstruction_W(X) h = np.dot(X, W) # no nonlinearity if self.act is not None: h = self.act(h) # inject nonlinearity return W, h def _compute_reconstruction_W(self, X): ''' Learn reconstruction parameters. :param X: input features, shape:(num_samples,num_features) :return: model parameters. ''' # typecast to correct Xtype X.dtype = "float64" d = X.shape[1] # Represents the probability that a given feature will be corrupted if self.bias: q = np.ones( (d-1, 1)) * (1 - self.p) # add bias probability q=np.vstack((q,1)) else: q = np.ones( (d, 1)) * (1 - self.p) S = np.dot(X.transpose(), X) Q = S * (np.dot(q, q.transpose())) Q[np.diag_indices_from(Q)] = q[:,0] * np.diag(S) P = S * numpy.matlib.repmat(q, 1, d) # solve equation of the form W = BA^-1 A = Q + 10**-5 * np.eye(d) B = P[:-1,:] W = np.linalg.solve(A.transpose(), B.transpose()) return W def fit(self, X): ''' Stack mDA layers on top of each other, using previous layer as input for the next :param X: input features, shape:(num_samples,num_features) :return: None ''' Ws = list() hs = list() hs.append(X) for layer in range(0, self.l): W, h = self.mDA(hs[-1]) Ws.append(W) hs.append(h) self.Ws = Ws def transform(self, X): ''' Should be called after fit! Stack mDA layers on top of each other, using previous layer as input for the next :param X: input features, shape:(num_samples,num_features) :return: reconstructed representation of the last layer. ''' if self.Ws is None: raise ValueError('Please fit on some data first.') hs = list() hs.append(X) for layer in range(0, self.l): _, h = self.mDA(hs[-1], self.Ws[layer]) hs.append(h) return hs[-1] def fit_transform(self, X): ''' Stack mDA layers on top of each other, using previous layer as input for the next :param X: input features, shape:(num_samples,num_features) :return: reconstructed representation of the last layer. ''' Ws = list() hs = list() hs.append(X) for layer in range(0, self.l): W, h = self.mDA(hs[-1]) Ws.append(W) hs.append(h) self.Ws = Ws return hs[-1] # test implementation if __name__ == "__main__": basepath = "../data/processed_acl" # load dataset1 [Xs_train, Ys_train, Xs_test, Ys_test, Xs_unlabeled]=joblib.load( os.path.join(basepath, 'K-D.pkl')) # load dataset2 [Xt_train, Xt_train_label, Xt_test, Xt_test_label, Xt_unlabeled]=joblib.load( os.path.join(basepath, 'D-K.pkl')) from sklearn import svm clf = svm.SVC().fit(Xs_train, Ys_train) preds_Xs = clf.predict(Xs_test) acc = np.mean(preds_Xs == Ys_test) print("Xs acc on regular X: ", acc) preds_Xt = clf.predict(Xt_test) acc = np.mean(preds_Xt == Xt_test_label) print("Xt acc on regular X: ", acc) # set corruption probability, number of layers and bias. pp = 0.3 ll = 5 bias = True train_X=np.concatenate((Xs_train,Xs_unlabeled,Xt_train,Xt_unlabeled),axis=0) msda=mSDA(p=pp, l=ll,act=np.tanh, Ws=None, bias=True) msda.fit(train_X) Xs_reps = msda.transform(Xs_train) print("Shape of mSDA Xs_reps h: ", Xs_reps.shape) Xs_test_reps = msda.transform(Xs_test) print("Shape of mSDA Xs_test_reps h: ", Xs_test_reps.shape) Xt_reps = msda.transform(Xt_test) print("Shape of mSDA Xt_test_reps h: ", Xt_reps.shape) clf = svm.SVC().fit(Xs_reps, Ys_train) preds_Xs=clf.predict(Xs_test_reps) acc=np.mean(preds_Xs == Ys_test) print("Xs acc with linear SVM on mSDA features: ", acc) preds_Xt = clf.predict(Xt_reps) acc = np.mean(preds_Xt == Xt_test_label) print("Xt acc with linear SVM on mSDA features: ", acc)
<?php namespace App\Radan\Config\Storage; use Illuminate\Database\Eloquent\Model; class Elequent implements StorageInterface { /** * @var Base Elequent Model connection */ protected $connection = ''; /** * @var Base Elequent Model connection */ protected $model = ''; /** * constructor * * @param BasePdo $pdo instance of pdo to execute the queries against * @param string $tableName the table name to reference * @param array $sqlQueries custom queries */ public function __construct(Model $model,$connection = null) { $this->model = $model; $this->connection = $connection; if ($this->connection) { $this->model->setConnection($this->connection); } } /** * @inheritdoc */ public function save($key, $value) { // Check value is array, save config such // key.0 => $value[0],key.1 => $value[1],.. if (is_array($value)) { foreach ($value as $i => $arrValue) { $this->model->updateOrCreate(['key' => $key.'.'.$i ],[ 'value' => $arrValue]); } return; } // Save config key => value $str=$this->model->updateOrCreate(['key' => $key],['value' => $value]); } /** * @inheritdoc */ public function load() { $results = []; $configs = $this->model->all(); foreach ($configs as $config) { $results[$config->key] = $config->value; }; return $results; } /** * @inheritdoc */ public function clear() { $this->model->truncate(); } }
๏ปฟusing System.Collections.Generic; using UnityEngine; public class BeatAnalyse : MonoBehaviour { float[] spectrum; public static List<int> beatStarts = new List<int>(); [SerializeField] int windowTrigger; [SerializeField] float drawWidth; [SerializeField] float limit, waitSamples; [SerializeField] AudioClip wave; [SerializeField] AudioSource sourceWave; bool beat; private float timeSample; void Start() { int amount = wave.samples; spectrum = new float[amount]; wave.GetData(spectrum, 0); for (int i = 0; i < spectrum.Length; i++) { spectrum[i] = Mathf.Abs(spectrum[i]); } for (int i = 1; i < spectrum.Length -1; i++) { if (spectrum[i] > limit) { if(spectrum[i] <= spectrum[i-1] && spectrum[i] >= spectrum[i+1]) { beatStarts.Add(i); i += (int)waitSamples; } } } } private void Update() { if (IsOnBeat(1000) && beat == false) { beat = true; ScoreTracker.instance.totalBeats++; } else if (!IsOnBeat(1000)) { beat = false; } } public bool IsOnBeat(int preStart) { timeSample = sourceWave.timeSamples - preStart; for (int i = 0; i < BeatAnalyse.beatStarts.Count; i++) { if (timeSample >= (BeatAnalyse.beatStarts[i] - windowTrigger) && timeSample <= (BeatAnalyse.beatStarts[i] + windowTrigger)) { return true; } } return false; } private void OnDrawGizmos() { if(spectrum == null) { return; } if (PlayerController.show) { Vector3 displacement = Camera.main.ScreenToWorldPoint(new Vector3(100, 100, 5)); float heightMulti = 1; float widthMulti = 0.000005f; Gizmos.color = new Color(0.5f, 0, 0.5f, 1); for (int i = 0; i < spectrum.Length; i += 100) { Gizmos.DrawLine(displacement + new Vector3(i * widthMulti, 0, 0), displacement + new Vector3(i * widthMulti, heightMulti * spectrum[i], 0)); } } } }
require 'spec_helper' require_relative '../support/bag_of_words' require_relative '../support/request' describe 'the impact of the bag of words' do include_context "bag_of_words" include_context "request" before do empty_bag_of_words end context "when the user is not logged in" do it "should ignore the request" do response = get("/words") expect(response['code']).to eq(403) end end context "when the user is logged in" do let(:session_id) {login_user} context "when the bag is empty" do it "should ignore the crawl requests" do response = get("/search") expect(response['response']).to be_false end end context "when the bag contains one word" do it "should detect the news containing it" do put("/words", body: {word: "word"}, headers:{'Session-Id' => session_id, 'Auth-User' => test_user.user}) response = get("/search") expect(response['response']).to be_true end context "when the word is deleted" do it "should stop accepting requests again" do delete("/words", body: {word: "word"}, headers:{'Session-Id' => session_id, 'Auth-User' => test_user.user}) response = get("/search") expect(response['response']).to be_false end end end end end
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using WindowsPhone.Recipes.Push.Server.Models; namespace WindowsPhone.Recipes.Push.Server.Services { /// <summary> /// Server info event arguments. /// </summary> internal class ServerInfoEventArgs : EventArgs { /// <summary> /// Gets or sets the server info. /// </summary> public ServerInfo ServerInfo { get; set; } } }
--- title: Datadog-Mesos Integration integration_title: Mesos kind: integration doclevel: basic --- Connects Mesos to Datadog in order to: * Visualize your Mesos cluster performance * Correlate the performance of Mesos with the rest of your applications
#!/usr/bin/perl # WARNING: this file is generated, do not edit # generated on Wed May 27 03:01:20 2020 # 01: Apache-Test/lib/Apache/TestConfig.pm:1007 # 02: Apache-Test/lib/Apache/TestConfig.pm:1099 # 03: Apache-Test/lib/Apache/TestMM.pm:142 # 04: ./Makefile.PL:50 # 05: /usr/share/perl/5.22/ExtUtils/MakeMaker.pm:241 # 06: /usr/share/perl/5.22/ExtUtils/MakeMaker.pm:228 # 07: /usr/share/perl/5.22/ExtUtils/MakeMaker.pm:228 # 08: /usr/share/perl/5.22/ExtUtils/MakeMaker.pm:728 # 09: /usr/share/perl/5.22/ExtUtils/MakeMaker.pm:67 # 10: Makefile.PL:55 BEGIN { eval { require blib && blib->import; } } #!perl -wT use strict; use CGI; use CGI::Cookie; my %cookies = CGI::Cookie->fetch; my $name = 'ApacheTest'; my $c = ! exists $cookies{$name} ? CGI::Cookie->new(-name=>$name, -value=>time) : ''; print "Set-Cookie: $c\n" if $c; print "Content-Type: text/plain\n\n"; print ($c ? 'new' : 'exists'), "\n";
/* * Copyright (c) 2017 Intel Corporation * * 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 com.intel.icecp.rpc; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import com.intel.icecp.core.Message; /** * Represent a response to a {@link Command} invocation * * @see CommandRegistry */ public class CommandResponse implements Message { private static final int TIMEOUT_FUTURE_RESULT = 2000; public boolean err; public Object out; public CommandResponse(){ } private CommandResponse(Object out, boolean err) { this.out = out; this.err = err; } /** * This method returns a CommandResponse with out object being the simple class name of the exception * concatenated with error message if it is not null * @param error invocation exception information * @return CommandResponse command response from future call. e */ public static CommandResponse fromError(Throwable error) { String errMsg = error.getMessage(); String errForOut = errMsg != null ? error.getClass().getSimpleName() + " : " + errMsg : error.getClass().getSimpleName(); return new CommandResponse(errForOut, true); } /** * This method get the target exception inside the InvocationTargetException and returns the corresponding * CommandRequest. * @param error invocation exception information * @return CommandResponse command response from future call. */ public static CommandResponse fromError(InvocationTargetException error) { return fromError(error.getTargetException()); } /** * @param response object from remote method call */ public static CommandResponse fromValid(Object response) { return new CommandResponse(response, false); } /** * @param response object from remote method call * @param timeout timeout for this to wait on the future object * @param timeunit unit for timeout * @return CommandResponse command response from future call. */ public static CommandResponse fromValidFuture(Future<?> response, long timeout, TimeUnit timeunit) { try { return new CommandResponse(response.get(timeout, timeunit), false); } catch (InterruptedException | ExecutionException | TimeoutException e) { return fromError(e); } } }
# Copyright 2015 gRPC 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. require_relative '../grpc' # GRPC contains the General RPC module. module GRPC module Core # TimeConsts is a module from the C extension. # # Here it's re-opened to add a utility func. module TimeConsts # Converts a time delta to an absolute deadline. # # Assumes timeish is a relative time, and converts its to an absolute, # with following exceptions: # # * if timish is one of the TimeConsts.TimeSpec constants the value is # preserved. # * timish < 0 => TimeConsts.INFINITE_FUTURE # * timish == 0 => TimeConsts.ZERO # # @param timeish [Number|TimeSpec] # @return [Number|TimeSpec] def from_relative_time(timeish) if timeish.is_a? TimeSpec timeish elsif timeish.nil? TimeConsts::ZERO elsif !timeish.is_a? Numeric fail(TypeError, "Cannot make an absolute deadline from #{timeish.inspect}") elsif timeish < 0 TimeConsts::INFINITE_FUTURE elsif timeish.zero? TimeConsts::ZERO else Time.now + timeish end end module_function :from_relative_time end end end
๏ปฟCREATE PROCEDURE [api].[ReportDefinitions__Save] @Entities [dbo].[ReportDefinitionList] READONLY, @Parameters [dbo].[ReportDefinitionParameterList] READONLY, @Select [dbo].[ReportDefinitionSelectList] READONLY, @Rows [dbo].[ReportDefinitionDimensionList] READONLY, @RowsAttributes [dbo].[ReportDefinitionDimensionAttributeList] READONLY, @Columns [dbo].[ReportDefinitionDimensionList] READONLY, @ColumnsAttributes [dbo].[ReportDefinitionDimensionAttributeList] READONLY, @Measures [dbo].[ReportDefinitionMeasureList] READONLY, @Roles [dbo].[ReportDefinitionRoleList] READONLY, @ReturnIds BIT = 0, @ValidateOnly BIT = 0, @Top INT = 200, @UserId INT, @Culture NVARCHAR(50) = N'en', @NeutralCulture NVARCHAR(50) = N'en' AS BEGIN SET NOCOUNT ON; EXEC [dbo].[SetSessionCulture] @Culture = @Culture, @NeutralCulture = @NeutralCulture; -- (1) Validate DECLARE @IsError BIT; EXEC [bll].[ReportDefinitions_Validate__Save] @Entities = @Entities, @Parameters = @Parameters, @Select = @Select, @Rows = @Rows, @RowsAttributes = @RowsAttributes, @Columns = @Columns, @ColumnsAttributes = @ColumnsAttributes, @Measures = @Measures, @Roles = @Roles, @Top = @Top, @IsError = @IsError OUTPUT; -- If there are validation errors don't proceed IF @IsError = 1 OR @ValidateOnly = 1 RETURN; -- (2) Execute EXEC [dal].[ReportDefinitions__Save] @Entities = @Entities, @Parameters = @Parameters, @Select = @Select, @Rows = @Rows, @RowsAttributes = @RowsAttributes, @Columns = @Columns, @ColumnsAttributes = @ColumnsAttributes, @Measures = @Measures, @Roles = @Roles, @ReturnIds = @ReturnIds, @UserId = @UserId; END;
import setuptools import os with open("README.md", "r") as fh: long_description = fh.read() def get_version(): with open(os.path.join('src', 'view', 'constants.py')) as f: for line in f: if line.strip().startswith('VERSION'): return eval(line.split('=')[-1]) setuptools.setup( name="sql_editor", version=get_version(), author="Vijay", author_email="certifyexam0@gmail.com", description="A graphic SQLite Editor in Python", long_description=long_description, long_description_content_type="text/markdown", keywords=['sqlite', 'gui', 'wxpython', 'sql'], url="https://github.com/struts2spring/sql-editor", packages=setuptools.find_packages(), install_requires=[ 'pypubsub==4.0.0', 'six==1.11.0', 'wxpython==4.0.6', 'sqlparse' ], python_requires='>=3', entry_points={ 'console_scripts': [ 'eclipse = src.TheEclipse:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Education', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering :: Information Analysis', ], package_data={'src.images': ['*.png'], 'src.view.util.styles':['*.ess'], 'src.bin':['*.dll', '*.exe']}, include_package_data=True, zip_safe=False, )
import Toast from '../components/Toast'; import socket from '../socket'; export default function fetch<T = any>( event: string, data: any = {}, { toast = true } = {}, ): Promise<[string | null, T | null]> { return new Promise((resolve) => { socket.emit(event, data, (res: any) => { if (typeof res === 'string') { if (toast) { Toast.danger(res); } resolve([res, null]); } else { resolve([null, res]); } }); }); }
import axios from "axios"; // const BASEURL = "https://api.nytimes.com/svc/search/v2/articlesearch.json?"; // const APIKEY = "apikey=c0b4d2e16a014795bbdce9d7e4df8a95"; // const QUERY = "&q=obama"; // export default { // search: function(query) { // return axios.get(BASEURL + APIKEY + QUERY); // } // }; // const axios = require("axios"); const url = "https://api.nytimes.com/svc/search/v2/articlesearch.json?apikey=c0b4d2e16a014795bbdce9d7e4df8a95&q=obama"; const API = props => { axios .get(url) .then(response => { console.log( `City: ${response.data.results[0].web_url} -`, `Latitude: ${response.data.results[0].snippet} -`, `Longitude: ${response.data.results[0].date_pub} -`, `All: ${response.data.results[0]}` ); }) .catch(error => { console.log(error); }); // const BASEURL = "https://api.nytimes.com/svc/search/v2/articlesearch.json?" ; // const APIKEY = "api-key=c0b4d2e16a014795bbdce9d7e4df8a95"; // const KEY = "c0b4d2e16a014795bbdce9d7e4df8a95"; // const urlQuery = "&q=obama" // var queryURLBase = "https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=" + // KEY + "&q=obama"; // var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json"; // url += "" + // 'api-key': "c0b4d2e16a014795bbdce9d7e4df8a95", // 'q': "obama", // 'begin_date': "20180101", // 'end_date': "20180131" // }); // const API = props => // console.log(BASEURL + urlQuery + APIKEY); // return axios.get(BASEURL + urlQuery + APIKEY); // console.log(queryURLBase); // axios.get(queryURLBase) // .then(function(arr){ // return { // results: arr[0].data, // } // }) } export default API;
๏ปฟusing System.Collections.Generic; using System.Collections.ObjectModel; using XivApi.Character.Raw; namespace XivApi.Character { public class CharacterClassJobs { public readonly struct ClassJobLevel { public IClassJob ClassJob { get; } public int? Level { get; } public bool? Specialist { get; } public bool? IsMaxed { get; } public ClassJobLevel(IClassJob classJob, int? level, bool? specialist, bool? isMaxed) { ClassJob = classJob; Level = level; Specialist = specialist; IsMaxed = isMaxed; } } private class JobLevelCollection : KeyedCollection<IClassJob, ClassJobLevel> { protected override IClassJob GetKeyForItem(ClassJobLevel item) => item.ClassJob; } private readonly JobLevelCollection _jobLevels = new JobLevelCollection(); public CharacterClassJobs(IEnumerable<ClassJobInfo> classJobInfos) { foreach (ClassJobInfo info in classJobInfos) { IClassJob classJob = ClassJobs.ById[info.UnlockedState.ID ?? info.Class.ID]!; int? lvl = null; if (info.Level != 0) lvl = info.Level; bool? specialist = null; if (classJob is HandClass) specialist = info.IsSpecialised; bool? isMaxed = null; isMaxed = (bool?) (info.ExpLevelMax == 0 && info.Level != 0); _jobLevels.Add(new ClassJobLevel(classJob, lvl, specialist, isMaxed)); } } public bool TryGetLevel(IClassJob classJob, out ClassJobLevel level) { if (_jobLevels.TryGetValue(classJob, out level)) return true; if (classJob is CombatJob job && job.Class != null) { return _jobLevels.TryGetValue(job.Class, out level); } return false; } public ClassJobLevel? this[int id] => this[ClassJobs.ById[id]]; public ClassJobLevel? this[IClassJob classJob] { get { if (!TryGetLevel(classJob, out ClassJobLevel level)) return null; return level; } } } }
package me.jonathing.minecraft.foragecraft.common.capability; import me.jonathing.minecraft.foragecraft.common.capability.base.IForageChunk; import me.jonathing.minecraft.foragecraft.common.registry.ForageCapabilities; import net.minecraft.nbt.CompoundTag; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import javax.annotation.Nonnull; /** * The forage chunk capability adds to each chunk the number of times its been foraged from. This way, a limit can be * set on each chunk to incentivise exploration. * * @author Jonathing * @see ForageCapabilities#CHUNK * @since 2.2.2 */ public class ForageChunk implements IForageChunk { @CapabilityInject(IForageChunk.class) public static Capability<IForageChunk> INSTANCE = null; @Override public Capability<IForageChunk> getDefaultInstance() { return INSTANCE; } private int timesForaged = 0; @Override public void forage() { this.timesForaged++; } @Override public int getTimesForaged() { return this.timesForaged; } @Override public void setTimesForaged(int timesForaged) { this.timesForaged = timesForaged; } @Override @Nonnull public CompoundTag writeAdditional(CompoundTag nbt) { nbt.putInt("timesForaged", this.timesForaged); return nbt; } @Override public void read(@Nonnull CompoundTag nbt) { this.timesForaged = nbt.getInt("timesForaged"); } }
@TestOn('vm') import 'package:_tests/compiler.dart'; import 'package:test/test.dart'; void main() { test('should fail on a non-".css" file extension', () async { await compilesExpecting(""" import '$ngImport'; @Component( selector: 'example', template: '', styleUrls: [ 'example.scss', ], ) class Example {} """, errors: [ contains('Unsupported extension in styleUrls: "example.scss"'), ]); }); test('should fail on an invalid URI', () async { await compilesExpecting(""" import '$ngImport'; @Component( selector: 'example', template: '', styleUrls: [ // Intentionally mis-spell package as packages. 'packages:foo/foo.css', ], ) class Example {} """, errors: [ contains('Invalid Style URL: "packages:foo/foo.css"'), ]); }); }
require 'csv' require 'faker' require 'json' require 'yaml' module Fake def self.data collection_data = {} ['.csv', '.json', '.yml'].each do |i| name = slug(Faker::RuPaul.unique.queen) data = generate_data(name, i, collection_data) path = '_data/' + name + i case i when '.csv' then write_csv(path, data) when '.json' then File.open(path, 'w') { |f| f.write(data.to_json) } when '.yml' then File.open(path, 'w') { |f| f.write(data.to_yaml) } end Faker::Dune.unique.clear Faker::Lovecraft.unique.clear end collection_data end def self.generate_data(name, type, collection_data) data = [] keys = ['pid'] 5.times { keys << slug(Faker::Lovecraft.unique.word) } # keys = pid + 5 5.times do # with 5 records record = { keys[0] => slug(Faker::Dune.unique.character), keys[1] => Faker::Lorem.sentence, keys[2] => Faker::TwinPeaks.quote, keys[3] => Faker::Name.name, keys[4] => Faker::Space.star, keys[5] => Faker::Lovecraft.sentence } data << record collection_data[name] = { 'keys' => keys, 'type' => type } end data end end
// // UITextField+StreamKit.h // StreamKit // // Created by ่‹ๅ— on 16/12/22. // Copyright ยฉ 2016ๅนด ๆŽๆตฉ. All rights reserved. // #import <UIKit/UIKit.h> /** Overrides the super's methods. */ @interface UITextField (StreamSuper) #pragma mark- UIView - (UITextField* (^)(CGRect frame))sk_frame; - (UITextField* (^)(CGFloat x))sk_x; - (UITextField* (^)(CGFloat y))sk_y; - (UITextField* (^)(CGFloat width))sk_width; - (UITextField* (^)(CGFloat height))sk_height; - (UITextField* (^)(CGSize size))sk_size; - (UITextField* (^)(CGRect bounds))sk_bounds; - (UITextField* (^)(CGPoint point))sk_center; - (UITextField* (^)(CGFloat centerX))sk_centerX; - (UITextField* (^)(CGFloat centerY))sk_centerY; - (UITextField* (^)(NSInteger tag))sk_tag; - (UITextField* (^)(BOOL autoresizesSubviews))sk_autoresizesSubviews; - (UITextField* (^)(UIViewAutoresizing autoresizingMask))sk_autoresizingMask; - (UITextField* (^)(UIColor* backgroundColor))sk_backgroundColor; - (UITextField* (^) (BOOL masksToBounds))sk_masksToBounds; - (UITextField* (^) (CGFloat cornerRadius))sk_cornerRadius; - (UITextField* (^)(CGFloat alpha))sk_alpha; - (UITextField* (^)(BOOL opaque))sk_opaque; - (UITextField* (^)(BOOL hidden))sk_hidden; - (UITextField* (^)(UIViewContentMode mode))sk_contentMode; - (UITextField* (^)(BOOL clipsToBounds))sk_clipsToBounds; - (UITextField* (^)(UIColor* tintColor))sk_tintColor; #pragma mark- UIControl - (UITextField* (^)(BOOL enabled))sk_enabled; - (UITextField* (^)(BOOL selected))sk_selected; - (UITextField* (^)(BOOL highlighted))sk_highlighted; - (UITextField* (^)(UIControlContentVerticalAlignment contentVerticalAlignment))sk_contentVerticalAlignment; - (UITextField* (^)(UIControlContentHorizontalAlignment contentHorizontalAlignment))sk_contentHorizontalAlignment; @end @interface UITextField (StreamKit) /** Creates a new textField by the given frame. @code UITextField* textField = UITextField.sk_init(frame); @endcode */ + (UITextField* (^)(CGRect frame))sk_init; /** Set text. @code self.sk_text(text); @endcode */ - (UITextField* (^)(NSString* text))sk_text; /** Set attributedText. @code self.sk_attributedText(attributedText); @endcode */ - (UITextField* (^)(NSAttributedString* attributedText))sk_attributedText; /** Set textColor. @code self.sk_textColor(textColor); @endcode */ - (UITextField* (^)(UIColor* textColor))sk_textColor; /** Set font. @code self.sk_fontSize(fontSize); @endcode */ - (UITextField* (^)(NSInteger fontSize))sk_fontSize; /** Set font. @code self.sk_font(font); @endcode */ - (UITextField* (^)(UIFont* font))sk_font; /** Set textAlignment. @code self.sk_textAlignment(textAlignment); @endcode */ - (UITextField* (^)(NSTextAlignment textAlignment))sk_textAlignment; /** Set borderStyle. @code self.sk_borderStyle(borderStyle); @endcode */ - (UITextField* (^)(UITextBorderStyle borderStyle))sk_borderStyle; /** Set defaultTextAttributes. @code self.sk_defaultTextAttributes(defaultTextAttributes); @endcode */ - (UITextField* (^)(NSDictionary<NSString*,id>* defaultTextAttributes))sk_defaultTextAttributes; /** Set placeholder. @code self.sk_placeholder(placeholder); @endcode */ - (UITextField* (^)(NSString* placeholder))sk_placeholder; /** Set attributedPlaceholder. @code self.sk_attributedPlaceholder(attributedPlaceholder); @endcode */ - (UITextField* (^)(NSAttributedString* attributedPlaceholder))sk_attributedPlaceholder; /** Set clearsOnBeginEditing. @code self.sk_clearsOnBeginEditing(clearsOnBeginEditing); @endcode */ - (UITextField* (^)(BOOL clearsOnBeginEditing))sk_clearsOnBeginEditing; /** Set adjustsFontSizeToFitWidth. @code self.sk_adjustsFontSizeToFitWidth(adjustsFontSizeToFitWidth); @endcode */ - (UITextField* (^)(BOOL adjustsFontSizeToFitWidth))sk_adjustsFontSizeToFitWidth; /** Set minimumFontSize. @code self.sk_minimumFontSize(minimumFontSize); @endcode */ - (UITextField* (^)(CGFloat minimumFontSize))sk_minimumFontSize; /** Set delegate. @code self.sk_delegate(delegate); @endcode */ - (UITextField* (^)(id<UITextFieldDelegate> delegate))sk_delegate; /** Set background. @code self.sk_background(background); @endcode */ - (UITextField* (^)(UIImage* background))sk_background; /** Set disabledBackground. @code self.sk_disabledBackground(disabledBackground); @endcode */ - (UITextField* (^)(UIImage* disabledBackground))sk_disabledBackground; /** Set allowsEditingTextAttributes. @code self.sk_allowsEditingTextAttributes(allowsEditingTextAttributes); @endcode */ - (UITextField* (^)(BOOL allowsEditingTextAttributes))sk_allowsEditingTextAttributes; /** Set typingAttributes. @code self.sk_typingAttributes(typingAttributes); @endcode */ - (UITextField* (^)(NSDictionary<NSString*,id>* typingAttributes))sk_typingAttributes; /** Set clearButtonMode. @code self.sk_clearButtonMode(clearButtonMode); @endcode */ - (UITextField* (^)(UITextFieldViewMode clearButtonMode))sk_clearButtonMode; /** Set leftView. @code self.sk_leftView(leftView); @endcode */ - (UITextField* (^)(UIView* leftView))sk_leftView; /** Set leftViewMode. @code self.sk_leftViewMode(leftViewMode); @endcode */ - (UITextField* (^)(UITextFieldViewMode leftViewMode))sk_leftViewMode; /** Set rightView. @code self.sk_rightView(rightView); @endcode */ - (UITextField* (^)(UIView* rightView))sk_rightView; /** Set rightViewMode. @code self.sk_rightViewMode(rightViewMode); @endcode */ - (UITextField* (^)(UITextFieldViewMode rightViewMode))sk_rightViewMode; @end
import { RendererComponent } from './Renderer'; import { ControlProps, ControlState } from '@jsonforms/core'; /** * A controlled component convenience wrapper that additionally manages a focused state. * * @template P control specific properties * @template S the state managed by the control */ export declare class Control<P extends ControlProps, S extends ControlState> extends RendererComponent<P, S> { constructor(props: P); /** * Propagates a value change. * * @param value the updated value */ handleChange: (value: any) => void; /** * Set the focused state to true. */ onFocus: () => void; /** * Set the focused state to false. */ onBlur: () => void; private updateData; }
--- layout: post title: Running Multiple Instances of nvALT date: '2014-03-27T10:00:19-04:00' tags: - nvalt - workflow redirect_from: /post/80876964138unning-multiple-instances-of-nvalt/ redirect_to: http://verifyandrepair.com/03-27-2014/running-multiple-instances-of-nvalt/ ---
import { spawn } from 'child_process' export default function execCommand(line: string, cwd = process.cwd()) { const [command, ...args] = line.split(/\s+/) const cp = spawn(command, args, { cwd }) return new Promise<void>((res, rej) => { cp.on('error', err => { rej(err) }).on('exit', code => { code === 0 && res() }) }) }
๏ปฟusing UnityEngine; using System.IO; using System.Collections.Generic; using NUnit.Framework; using MidiLoader.Parser; namespace MidiLoader.Tests { [Category("MidiLoader")] [TestFixture] public class VariableLengthQuantityTests { [ExpectedException( typeof( MidiLoader.Exceptions.MidiEndOfFileException ) )] [Test] public void EndOfFileException() { ParseVariableLengthQuantity( new byte[] { } ); } #pragma warning disable 414 Dictionary<ulong, byte[]> midiSpecificationCases = new Dictionary<ulong, byte[]>() { { 0x00000000, new byte[] { 0x00, 0x01, 0x01, 0x01, 0x01 } }, { 0x0000007f, new byte[] { 0x7f, 0x01, 0x01, 0x01, 0x01 } }, { 0x00000080, new byte[] { 0x81, 0x00, 0x01, 0x01, 0x01 } }, { 0x00002000, new byte[] { 0xc0, 0x00, 0x01, 0x01, 0x01 } }, { 0x00003fff, new byte[] { 0xff, 0x7f, 0x01, 0x01, 0x01 } }, { 0x00004000, new byte[] { 0x81, 0x80, 0x00, 0x01, 0x01 } }, { 0x001fffff, new byte[] { 0xff, 0xff, 0x7f, 0x01, 0x01 } }, { 0x00200000, new byte[] { 0x81, 0x80, 0x80, 0x00, 0x01 } }, { 0x08000000, new byte[] { 0xc0, 0x80, 0x80, 0x00, 0x01 } }, { 0x0fffffff, new byte[] { 0xff, 0xff, 0xff, 0x7f, 0x01 } } }; [Test] public void ExamplesFromMidiSpecification( [ValueSource( "midiSpecificationCases" )] KeyValuePair<ulong, byte[]> kvp ) { ulong result = ParseVariableLengthQuantity( kvp.Value ); Assert.That( result == kvp.Key ); } ulong ParseVariableLengthQuantity( byte[] bytes ) { MemoryStream fakeStream = new MemoryStream( bytes ); return VariableLengthQuantity.FromStream( fakeStream ); } } }
(ns overtone.sc.machinery.ugen.metadata.extras.vbap (:use [overtone.sc.machinery.ugen common check])) (def specs [ {:name "VBAP" :summary "Vector Based Amplitude Panner" :args [{:name "num-chans" :default 1 :mode :num-outs :doc "The number of output channels. This must be a fixed integer and not a signal or a control proxy. The architecture of the synth design cannot change after it is compiled." } {:name "in" :default :none :doc "The signal to be panned." :rates #{:ar}} {:name "bufnum" :default 10 :doc "The index of the buffer containing data calculated by the function vbap-speaker-array. Its number of channels must correspond to numChans above." } {:name "azimuth" :default 0 :doc "+/- 180 degrees from the median plane (i.e. straight ahead)" } {:name "elevation" :default 0 :doc "+/- 90 degrees from azimuth plane" } {:name "spread" :default 0 :doc "A value from 0-100. When 0, if the signal is panned exactly to a speaker location the signal is only on that speaker. At values higher than 0, the signal will always be on more than one speaker. This can smooth the panning effect by making localisation blur more constant." }] :rates #{:ar :kr} :check (nth-input-stream? 1) :doc "An implementation of Vector Base Amplitude Panning. This allows for equal power panning of a source over an array of speakers on arbitrary positions on a circle (2D) or sphere (3D) around the listener. Normally this would be a ring, a dome, or a partial ring or dome. VBAP was created by Ville Pulkki. For more information on VBAP see http://www.acoustics.hut.fi/research/cat/vbap/ Examples: ;;; ------------------------------------------------------------------------------------------ ;;; 2-D: (do ;;; define Loudspeaker Positions (def vbap-data (vbap-speaker-array [-45 0 45 90 135 180 -135 -90])) ;;; init buffer on server and store the loudspeaker data matrices in it (def b (buffer (count vbap-data))) (buffer-write! b vbap-data) ;;; define a simple synth with pink noise as source (defsynth vbaptest [buf 0 azi 0 ele 0 spread 0] (out 0 (vbap 8 (pink-noise) buf azi ele spread)))) ;;; start the synth (def vbapsynth (vbaptest b 0 0 0)) ;;; change the azimuth (map-indexed #(at (+ (now) (* 1000 %1)) (ctl vbapsynth :azi %2)) '(-45 0 45 90 135 180 -135 -90 -45)) ;;; change spread and repeat the above command: ;;; more than one speaker (ctl vbapsynth :spread 40) ;;; only one speaker (ctl vbapsynth :spread 0) ;;; stop the synth (kill vbapsynth) ;;; ------------------------------------------------------------------------------------------ ;;; 3-D: (do ;;; define Loudspeaker Positions in a zig-zag around the Listener (def vbap-data (vbap-speaker-array [[-45 0] [0 45] [45 0] [90 45] [135 0] [180 45] [-135 0] [-90 45]])) ;;; init buffer on server and store the loudspeaker data matrices in it (def b (buffer (count vbap-data))) (buffer-write! b vbap-data) ;;; define a simple synth with pink noise as source (defsynth vbaptest [buf 0 azi 0 ele 0 spread 0] (out 0 (vbap 8 (pink-noise) buf azi ele spread)))) ;;; start the synth (def vbapsynth (vbaptest b 0 0 0)) ;;; traverse all speakers in a zig-zag motion (map #(at (+ (now) (* 1000 %1)) (ctl vbapsynth :azi %2 :ele %3)) (range) '(-45 0 45 90 135 180 -135 -90 -45) '(0 45 0 45 0 45 0 45 0)) ;;; change spread and repeat the above command: ;;; more than one speaker involved (ctl vbapsynth :spread 40) ;;; only one speaker at a time (ctl vbapsynth :spread 0) ;;; stop the synth (kill vbapsynth) "}])
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User_Info extends Model { protected $table = 'user_info'; public function getUserinfoByUserIds($goodIds){ $result = $this->whereIn('user_id', $goodIds) ->distinct('user_id') ->get(['user_id', 'name', 'address', 'site', 'phone', 'email']); $usersInfo = []; if($result->count()){ $arr = $result->toArray(); foreach($arr as $value){ $usersInfo[$value['user_id']] = $value; } } return $usersInfo; } }
package _andlabsUI import ( "os" "bufio" ) func readFile(fileName string) ([]string, []string, error){ return revertLine(fileName) } func revertLine(fileName string) ([]string, []string, error){ file, err := os.Open(fileName) if checkError(err, true) {return nil, nil, err} defer file.Close() origin := []string{} revert := []string{} scanner := bufio.NewScanner(file) for scanner.Scan() { origin = append(origin, scanner.Text()) } for i := len(origin)-1; i >=0; i-- { revert = append(revert, origin[i]) } return origin, revert, nil }
package com.nawrot.mateusz.recipey.navigation import android.content.Context import android.util.Log import com.nawrot.mateusz.recipey.di.ActivityScope import javax.inject.Inject @ActivityScope class NavigationRouter @Inject constructor(private val context: Context, private val navigator: Navigator) { init { Log.d("NAVIGATION_ROUTER", "Context class = " + context.javaClass.simpleName) } fun navigateTo(navigationTarget: NavigationTarget) { navigator.navigateTo(context, navigationTarget) } }
package com.jade.customervisit.ui.view; import java.util.ArrayList; import java.util.List; import com.jade.customervisit.CVApplication; import com.jade.customervisit.R; import com.jade.customervisit.adapter.AbsListAdapter; import com.jade.customervisit.util.CommonUtils; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; /** * ๅผนๅ‡บ่œๅ• */ public class PopupMenuView extends PopupWindow implements OnKeyListener { private Context mContext; /** ๅผน็ช—ๅญ็ฑป้กน้€‰ไธญๆ—ถ็š„็›‘ๅฌ */ private OnItemClickListener mOnItemClickListener; /** ๅฎšไน‰ๅˆ—่กจๅฏน่ฑก */ private ListView mListView; /** ๅฎšไน‰ๅผน็ช—ๅญ็ฑป้กนๅˆ—่กจ */ private ArrayList<ActionItem> mActionItems = new ArrayList<ActionItem>(); /** * ้€‚้…ๅ™จ */ private MenuAdapter mAdapter; /** * ๅผนๅ‡บ่œๅ• * * @param context */ public PopupMenuView(Context context) { // ่ฎพ็ฝฎๅธƒๅฑ€็š„ๅ‚ๆ•ฐ this(context, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } public PopupMenuView(Context context, int width, int height) { super(LayoutInflater.from(context).inflate(R.layout.view_popupmenu, null), width, height); this.mContext = context; // ่ฎพ็ฝฎๅฏไปฅ่Žทๅพ—็„ฆ็‚น setFocusable(true); // ่ฎพ็ฝฎๅผน็ช—ๅ†…ๅฏ็‚นๅ‡ป setTouchable(true); // ่ฎพ็ฝฎๅผน็ช—ๅค–ๅฏ็‚นๅ‡ป setOutsideTouchable(true); setBackgroundDrawable(new ColorDrawable()); mAdapter = new MenuAdapter(mContext, mActionItems); initUI(); } /** * ๅˆๅง‹ๅŒ–ๅผน็ช—ๅˆ—่กจ */ private void initUI() { mListView = (ListView) getContentView().findViewById(R.id.title_list); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { // ็‚นๅ‡ปๅญ็ฑป้กนๅŽ๏ผŒๅผน็ช—ๆถˆๅคฑ dismiss(); if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(adapterView, view, position, id); } } }); mListView.setOnKeyListener(this); ((View) mListView.getParent()) .setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { dismiss(); return false; } }); } /** * ่ฎพ็ฝฎๆŒ‡ๅฎš่œๅ•้กน็š„ๆ–‡ๅญ—ๅŠๅ›พๆ ‡ * * @param id * @param title * @param drawableId */ public void set(int id, CharSequence title, int drawableId) { getAction(id).set(mContext, title, drawableId); mAdapter.notifyDataSetChanged(); } /** * ่Žทๅ–่œๅ•้กนๆ•ฐ้‡ * * @return */ public int getItemCount() { return mActionItems.size(); } /** * ๆทปๅŠ ่œๅ•้กน * * @param action */ public void addAction(ActionItem action) { if (action != null) { ((MenuAdapter) mAdapter).add(action); } } /** * ๆทปๅŠ ๅคšไธช่œๅ•้กน * * @param actions */ public void addAction(List<ActionItem> actions) { if (actions != null) { ((MenuAdapter) mAdapter).addAll(actions); } } /** * ่ฎพ็ฝฎๅญ้กนๆ˜พ็คบๆ•ฐๆฎ * * @param actions */ public void setActions(List<ActionItem> actions) { if (actions != null) { ((MenuAdapter) mAdapter).clear(); ((MenuAdapter) mAdapter).addAll(actions); } } /** * ๆธ…้™คๅญ็ฑป้กน */ public void cleanAction() { if (!mActionItems.isEmpty()) { ((MenuAdapter) mAdapter).clear(); } } /** * ๆ นๆฎไฝ็ฝฎๅพ—ๅˆฐๅญ็ฑป้กน */ public ActionItem getAction(int id) { int size = mActionItems.size(); for (int i = 0; i < size; i++) { if (mActionItems.get(i).id == id) { return mActionItems.get(i); } } return null; } /** * ่ฎพ็ฝฎ็›‘ๅฌไบ‹ไปถ */ public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } public void setAdapter(BaseAdapter adapter) { } /** * ๆ˜พ็คบๅœจๆญฃไธ‹ๆ–น * * @param anchor * @param shadeTv * ้ฎ็ฝฉๅฑ‚ */ public void showAsDown(View anchor, final TextView shadeTv) { if (shadeTv != null) { shadeTv.setAnimation(AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in)); shadeTv.setVisibility(View.VISIBLE); } showAsDown(anchor); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { if (shadeTv != null) { shadeTv.setAnimation(AnimationUtils.loadAnimation(mContext, android.R.anim.fade_out)); shadeTv.setVisibility(View.GONE); } } }); } /** * ๆ˜พ็คบๆญฃไธ‹ๆ–น * * @param anchor * @param shadeTv */ public void showAsDropDown(View anchor, final TextView shadeTv) { if (shadeTv != null) { shadeTv.setAnimation(AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in)); shadeTv.setVisibility(View.VISIBLE); } super.showAsDropDown(anchor); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { if (shadeTv != null) { shadeTv.setAnimation(AnimationUtils.loadAnimation(mContext, android.R.anim.fade_out)); shadeTv.setVisibility(View.GONE); } } }); } /** * ๆ˜พ็คบๅœจๆญฃไธ‹ๆ–น * * @param anchor */ public void showAsDown(View anchor) { int menuWidth = mContext.getResources().getDimensionPixelSize( R.dimen.titlebar_menu_view_width); showAsDropDown(anchor, -menuWidth / 2 + CommonUtils.dip2px(mContext, 5), 0); } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && KeyEvent.ACTION_UP == event.getAction()) { dismiss(); return true; } return false; } public ActionItem select(int position) { if (mAdapter == null) { return null; } ActionItem item = mAdapter.getItem(position); select(item); return item; } public ActionItem select(ActionItem item) { if (mAdapter == null) { return null; } mAdapter.select(item); return item; } public void notifyDataSetChanged() { if (mAdapter == null) { return; } mAdapter.notifyDataSetChanged(); } /** * ่œๅ•้€‚้…ๅ™จ * * @author zhoushujie 2014-7-25 ไธŠๅˆ8:29:50 */ class MenuAdapter extends AbsListAdapter<ActionItem> { private ActionItem selectItem; public MenuAdapter(Context context, List<ActionItem> mList) { super(context, mList); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder hd = null; if (convertView == null) { hd = new ViewHolder(); convertView = mInflater.inflate(R.layout.item_popupmenu, null); hd.iv = (ImageView) convertView .findViewById(R.id.item_leader_iv); hd.tv = (TextView) convertView .findViewById(R.id.item_leader_tv); convertView.setTag(hd); } else { hd = (ViewHolder) convertView.getTag(); } ActionItem item = mActionItems.get(position); hd.tv.setTextAppearance(mContext, CVApplication.cvApplication.getSettingsTextStyle()); // ่ฎพ็ฝฎๆ–‡ๆœฌๆ–‡ๅญ— hd.tv.setText(item.mTitle); // ่ฎพ็ฝฎๅœจๆ–‡ๅญ—็š„ๅทฆ่พนๆ”พไธ€ไธชๅ›พๆ ‡ if (item.mDrawable == null) { hd.iv.setVisibility(View.GONE); hd.tv.setPadding( mContext.getResources().getDimensionPixelSize( R.dimen.popupmenu_padingleft), 0, 0, 0); } else { hd.iv.setVisibility(View.VISIBLE); hd.iv.setImageDrawable(item.mDrawable); hd.tv.setPadding(0, 0, 0, 0); } if (item.equals(selectItem)) { hd.tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_selected, 0); hd.tv.setTextColor(mContext.getResources().getColor( R.color.blue_text)); } else { hd.tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); hd.tv.setTextColor(mContext.getResources().getColor( R.color.black_text)); } return convertView; } public void select(ActionItem selectItem) { this.selectItem = selectItem; notifyDataSetChanged(); } class ViewHolder { ImageView iv; TextView tv; } } public ActionItem getItem(int position) { if (mAdapter == null) { return null; } return mAdapter.getItem(position); } }
/* eslint-disable indent */ import Vue from 'vue'; import VueRouter from 'vue-router'; import PasswordPage from '../shared/pages/password'; import CodeGeneratorPage from '../shared/pages/code-generator'; import BlacklistItem from '../shared/components/backlist/blacklist-list-item.component'; const routes = [{ path: '/', component: PasswordPage, props: { removeHeader: true, removeForm: true } }, { path: '/code-generator', component: CodeGeneratorPage, props: { removeHeader: true, removeForm: true } }, { name: 'blacklist', path: '/blacklist', component: BlacklistItem, props: { item: -1 } } ]; Vue.use(VueRouter); export default new VueRouter({ routes });
# Copyright (c) 2019, Richard Levitte # All rights reserved. # # Licensed under the BSD 2-Clause License (the "License"). # You can obtain a copy in the file LICENSE in the source distribution. use strict; use warnings; package PLisp::Types::Condition; use parent qw(PLisp::Types::T); use Scalar::Util qw(refaddr); sub new { my $class = shift; return bless {}, $class; } sub print_object { my $self = shift; my $stream = shift; return $stream->print($self->stringify()); } 1;
--- title: tRPC --- # [tRPC](https://trpc.io/) > End-to-end typesafe APIs made easy ## Links - [OpenAPI support for tRPC](https://github.com/jlalmes/trpc-openapi) - [tRPC Shield](https://github.com/omar-dulaimi/trpc-shield) - tRPC tool to ease the creation of permission layer. - [tRPC-ified SWR hooks](https://github.com/sachinraja/trpc-swr) - [tRPC Kitchen Sink](https://github.com/trpc/examples-kitchen-sink) - Collection tRPC usage patterns. - [I Deleted HALF My Backend Code With tRPC (2022)](https://www.youtube.com/watch?v=PYUqYcPMPeQ) - [Solid-tRPC Demo](https://github.com/TheoBr/solid-trpc)
package com.finyou.fintrack.backend.repo.test import com.finyou.fintrack.backend.common.models.ErrorModel import com.finyou.fintrack.backend.common.models.FinTransactionIdModel import com.finyou.fintrack.backend.common.models.FinTransactionModel import com.finyou.fintrack.backend.repo.common.DbFinTransactionIdRequest import com.finyou.fintrack.backend.repo.common.IRepoFinTransaction import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test import java.util.* abstract class RepoFinTransactionReadTest { abstract val repo: IRepoFinTransaction @Test fun readSuccess() { val result = runBlocking { repo.read(DbFinTransactionIdRequest(successId)) } assertEquals(true, result.isSuccess) assertEquals(readSuccessStub, result.result) assertEquals(emptyList<ErrorModel>(), result.errors) } @Test fun readNotFound() { val result = runBlocking { repo.read(DbFinTransactionIdRequest(notFoundId)) } assertEquals(false, result.isSuccess) assertEquals(null, result.result) assertEquals( listOf(ErrorModel(field = "id", message = "Not Found")), result.errors ) } companion object: BaseInitFinTransactions() { override val initObjects: List<FinTransactionModel> = listOf( createInitTestModel("read") ) private val readSuccessStub = initObjects.first() val successId = readSuccessStub.id val notFoundId = FinTransactionIdModel(UUID.randomUUID().toString()) } }
๏ปฟ// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Windows.Shell; using ICSharpCode.Core; namespace ICSharpCode.SharpDevelop { /// <summary> /// This class handles the recent open files and the recent open project files of SharpDevelop /// it checks, if the files exists at every creation, and if not it doesn't list them in the /// recent files, and they'll not be saved during the next option save. /// </summary> public sealed class RecentOpen { /// <summary> /// This variable is the maximal length of lastfile/lastopen entries /// must be > 0 /// </summary> int MAX_LENGTH = 10; readonly ObservableCollection<string> lastfile = new ObservableCollection<string>(); readonly ObservableCollection<string> lastproject = new ObservableCollection<string>(); public IList<string> RecentFile { get { return lastfile; } } public IList<string> RecentProject { get { return lastproject; } } public RecentOpen() { } public RecentOpen(Properties p) { // don't check whether files exist because that might be slow (e.g. if file is on network // drive that's unavailable) // if one of these entries is a string, then it's from a previous SharpDevelop version - don't try loading it if (p.Contains("Files") && !(p.Get("Files") is string)) { lastfile.AddRange(p.Get("Files", new string[0])); } if (p.Contains("Projects") && !(p.Get("Files") is string)) { lastproject.AddRange(p.Get("Projects", new string[0])); } } public void AddLastFile(string name) { for (int i = 0; i < lastfile.Count; ++i) { if (lastfile[i].Equals(name, StringComparison.OrdinalIgnoreCase)) { lastfile.RemoveAt(i); } } while (lastfile.Count >= MAX_LENGTH) { lastfile.RemoveAt(lastfile.Count - 1); } lastfile.Insert(0, name); } public void ClearRecentFiles() { lastfile.Clear(); } public void ClearRecentProjects() { lastproject.Clear(); } public void AddLastProject(string name) { for (int i = 0; i < lastproject.Count; ++i) { if (lastproject[i].ToString().Equals(name, StringComparison.OrdinalIgnoreCase)) { lastproject.RemoveAt(i); } } while (lastproject.Count >= MAX_LENGTH) { lastproject.RemoveAt(lastproject.Count - 1); } lastproject.Insert(0, name); JumpList.AddToRecentCategory(name); } public static RecentOpen FromXmlElement(Properties properties) { return new RecentOpen(properties); } public Properties ToProperties() { Properties p = new Properties(); p.Set("Files", lastfile.ToArray()); p.Set("Projects", lastproject.ToArray()); return p; } internal void FileRemoved(object sender, FileEventArgs e) { for (int i = 0; i < lastfile.Count; ++i) { string file = lastfile[i].ToString(); if (e.FileName == file) { lastfile.RemoveAt(i); break; } } } internal void FileRenamed(object sender, FileRenameEventArgs e) { for (int i = 0; i < lastfile.Count; ++i) { string file = lastfile[i].ToString(); if (e.SourceFile == file) { lastfile.RemoveAt(i); lastfile.Insert(i, e.TargetFile); break; } } } } }
๏ปฟusing System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Uhuru.Openshift.Common.Models; using System.IO; using System.Collections.Generic; using YamlDotNet.RepresentationModel.Serialization; using YamlDotNet.Core; using Uhuru.Openshift.Runtime; namespace Uhuru.Openshift.Tests { [TestClass] public class CartridgeTest { [TestMethod] [TestCategory("Unit")] public void Test_Cartridge() { string cartridgePath = Path.Combine(CartridgeRepository.CartridgeBasePath, "dotnet"); string manifestPath = Path.Combine(cartridgePath, "metadata", "manifest.yml"); string document = File.ReadAllText(manifestPath); var input = new StringReader(document); var deserializer = new Deserializer(); dynamic spec = (dynamic)deserializer.Deserialize(input); Cartridge cart = Cartridge.FromDescriptor(spec); Assert.AreEqual("dotnet", cart.OriginalName); } [TestMethod] [TestCategory("Unit")] public void Test_ToDescriptor() { string cartridgePath = Path.Combine(CartridgeRepository.CartridgeBasePath, "dotnet"); string manifestPath = Path.Combine(cartridgePath, "metadata", "manifest.yml"); string document = File.ReadAllText(manifestPath); var input = new StringReader(document); var deserializer = new Deserializer(); dynamic spec = (dynamic)deserializer.Deserialize(input); Cartridge cart = Cartridge.FromDescriptor(spec); dynamic desc = cart.ToDescriptor(); Assert.IsTrue(desc.ContainsKey("Name")); } [TestMethod] [TestCategory("Unit")] public void Test_CartridgeFromDescriptor() { bool testresult = false; Manifest sampleManifest = TestHelper.GetSampleManifest(); var input = new StringReader(sampleManifest.ToManifestString()); var deserializer = new Deserializer(); dynamic spec = (dynamic)deserializer.Deserialize(input); Cartridge cart = Cartridge.FromDescriptor(spec); if (cart != null) { testresult = true; } Assert.AreEqual(true, testresult); } } }
/*jshint node:true*/ "use strict"; var jsmm = {}; jsmm.debug = true; jsmm.maxWidth = 60; jsmm.defaultLimits = { history: 30, base: { callStackDepth: 100, executionCounter: 4000, costCounter: 1000 }, event: { callStackDepth: 100, executionCounter: 400, costCounter: 100 } }; require('./jsmm.nodes')(jsmm); require('./jsmm.parser')(jsmm); require('./jsmm.tree')(jsmm); require('./jsmm.msg')(jsmm); require('./jsmm.context')(jsmm); require('./jsmm.run')(jsmm); require('./jsmm.func')(jsmm); require('./jsmm.dot')(jsmm); require('./jsmm.simple.runner')(jsmm); require('./jsmm.static.runner')(jsmm); require('./jsmm.test')(jsmm); require('./jsmm.editor')(jsmm); module.exports = jsmm;
/* * Copyright 2018 The Android Open Source Project * * 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 androidx.recyclerview.widget import android.view.ViewGroup import androidx.test.filters.SmallTest import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.mock import org.mockito.Mockito.reset import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions import org.mockito.Mockito.verifyZeroInteractions import java.util.Collections.emptyList @SmallTest @RunWith(JUnit4::class) class ListAdapterTest { private val mainThread = TestExecutor() private val diffThread = TestExecutor() private val differConfig = AsyncDifferConfig.Builder(STRING_DIFF_CALLBACK) .setBackgroundThreadExecutor(diffThread) .build() inner class Adapter( private val onChanged: AsyncListDiffer.ListListener<String>? = null ) : ListAdapter<String, RecyclerView.ViewHolder>(differConfig) { init { mDiffer.mMainThreadExecutor = mainThread } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { throw IllegalStateException("not supported") } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { throw IllegalStateException("not supported") } override fun onCurrentListChanged(previousList: List<String>, currentList: List<String>) { onChanged?.onCurrentListChanged(previousList, currentList) } fun getItemPublic(position: Int): String? { return super.getItem(position) } } @Test fun initialState() { @Suppress("UNCHECKED_CAST") val listener = mock(AsyncListDiffer.ListListener::class.java) as AsyncListDiffer.ListListener<String> val adapter = Adapter(listener) assertEquals(0, adapter.itemCount) assertEquals(emptyList<String>(), adapter.currentList) verifyZeroInteractions(listener) } @Test fun getItem() { val adapter = Adapter() adapter.submitList(listOf("a", "b")) assertEquals("a", adapter.getItemPublic(0)) assertEquals("b", adapter.getItemPublic(1)) } @Test fun getItemCount() { val adapter = Adapter() assertEquals(0, adapter.itemCount) adapter.submitList(listOf("a", "b")) assertEquals(2, adapter.itemCount) } @Test fun getCurrentList() { val adapter = Adapter() val list = listOf("a", "b") assertEquals(emptyList<String>(), adapter.currentList) adapter.submitList(list) assertEquals(list, adapter.currentList) } @Test fun callbacks() { val callback = mock(Runnable::class.java) @Suppress("UNCHECKED_CAST") val listener = mock(AsyncListDiffer.ListListener::class.java) as AsyncListDiffer.ListListener<String> val adapter = Adapter(listener) // first - simple insert val first = listOf("a", "b") verifyZeroInteractions(listener) adapter.submitList(first, callback) verify(listener).onCurrentListChanged(emptyList<String>(), first) verifyNoMoreInteractions(listener) verify(callback).run() verifyNoMoreInteractions(callback) reset(callback) // second - async update val second = listOf("c", "d") adapter.submitList(second, callback) verifyNoMoreInteractions(listener) verifyNoMoreInteractions(callback) drain() verify(listener).onCurrentListChanged(first, second) verifyNoMoreInteractions(listener) verify(callback).run() verifyNoMoreInteractions(callback) reset(callback) // third - same list - only triggers callback adapter.submitList(second, callback) verifyNoMoreInteractions(listener) verify(callback).run() verifyNoMoreInteractions(callback) drain() verifyNoMoreInteractions(listener) verifyNoMoreInteractions(callback) reset(callback) // fourth - null adapter.submitList(null, callback) verify(listener).onCurrentListChanged(second, emptyList<String>()) verifyNoMoreInteractions(listener) verify(callback).run() verifyNoMoreInteractions(callback) } private fun drain() { var executed: Boolean do { executed = diffThread.executeAll() executed = mainThread.executeAll() or executed } while (executed) } companion object { private val STRING_DIFF_CALLBACK = object : DiffUtil.ItemCallback<String>() { override fun areItemsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: String, newItem: String): Boolean { return oldItem == newItem } } } }
#!/usr/bin/env bash # This script create empty necessary directories to avoid # `stow` make symlinks to our sub-directories. So that programs # will not put their stuff in this repository. set -eu -o pipefail EMPTY_DIRS_IN_HOME=( .config/autostart .config/autostart-scripts .config/fontconfig .config/git .config/hg .config/tmux .config/Code/User .config/xfce4/terminal .config/xfce4/xfconf/xfce-perchannel-xml .config/sublime-text-3/Packages/User .vim/plugged .config/vim/autoload .config/nvim/ .local/share/nvim/site/autoload .config/pip .elinks .gnupg .cargo/bin .local/share/bash-completion/completion .zfunc ) for dir in "${EMPTY_DIRS_IN_HOME[@]}"; do mkdir -p "${HOME}/${dir}" done
import { readLines } from "https://deno.land/std@v0.52.0/io/bufio.ts"; console.log('Start typing...'); const encoder = new TextEncoder(); await Deno.writeFile("input.txt", new Uint8Array()); // Listen to stdin input by readLines for await(const line of readLines(Deno.stdin)) { const data = encoder.encode(line+"\n"); await Deno.writeFile("input.txt", data, {append: true}); console.log("Wrote the above text in input.txt\n") }
numbers = [10, 5, 7, 2, 1] print("List content:", numbers) # Printing original list content. numbers = [10, 5, 7, 2, 1] print("Original list content:", numbers) # Printing original list content. numbers[0] = 111 print("\nPrevious list content:", numbers) # Printing previous list content. numbers[1] = numbers[4] # Copying value of the fifth element to the second. print("New list content:", numbers) # Printing current list content. print("\nList length:", len(numbers)) # Printing the list's length. numbers = [10, 5, 7, 2, 1] print("Original list content:", numbers) # Printing original list content. numbers[0] = 111 print("\nPrevious list content:", numbers) # Printing previous list content. numbers[1] = numbers[4] # Copying value of the fifth element to the second. print("Previous list content:", numbers) # Printing previous list content. print("\nList's length:", len(numbers)) # Printing previous list length. ### del numbers[1] # Removing the second element from the list. print("New list's length:", len(numbers)) # Printing new list length. print("\nNew list content:", numbers) # Printing current list content. ### numbers = [111, 7, 2, 1] print(numbers[-1]) print(numbers[-2]) hat_list = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat. # Step 1: write a line of code that prompts the user # to replace the middle number with an integer number entered by the user. # Step 2: write a line of code that removes the last element from the list. # Step 3: write a line of code that prints the length of the existing list. print(hat_list) hat_list[2] = int(input("Enter a number: ")) print(hat_list) del(hat_list[-1]) print(hat_list) print(len(hat_list))
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:e_shop_tez/Admin/adminOrderDetails.dart'; import 'package:e_shop_tez/Models/item.dart'; import 'package:e_shop_tez/Widgets/orderCard.dart'; import 'package:flutter/material.dart'; import '../Store/storehome.dart'; int counter = 0; class AdminOrderCard extends StatefulWidget { final int itemCount; final List<DocumentSnapshot> data; final String orderID; final String addressID; final String orderBy; const AdminOrderCard({ Key key, this.itemCount, this.data, this.orderID, this.addressID, this.orderBy, }) : super(key: key); @override _AdminOrderCardState createState() => _AdminOrderCardState(); } class _AdminOrderCardState extends State<AdminOrderCard> { @override void initState() { counter = 0; super.initState(); } @override Widget build(BuildContext context) { return InkWell( onTap: () { Route route; route = MaterialPageRoute( builder: (context) => AdminOrderDetails( orderID: widget.orderID, orderBy: widget.orderBy, addressID: widget.addressID)); Navigator.push(context, route); }, child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, colors: [ Colors.orange[200], Colors.orange[100], Colors.orange[50], ], ), ), padding: EdgeInsets.all(10.0), margin: EdgeInsets.all(10.0), height: widget.itemCount * 190.0, child: ListView.builder( itemCount: widget.itemCount, physics: NeverScrollableScrollPhysics(), itemBuilder: (c, index) { ItemModel model = ItemModel.fromJson(widget.data[index].data); return sourceOrderInfo(model, context); }, ), ), ); } } Widget sourceInfo(ItemModel model, BuildContext context, {Color background}) { return Container(); }
package webapp type MuxHandlerAdapter struct { handler Handler } func NewMuxHandlerAdapter(handler Handler) *MuxHandlerAdapter { return &MuxHandlerAdapter{handler} } func (this *MuxHandlerAdapter) ServeHTTP(c interface{}) { this.handler.ServeHTTP(c.(*Context)) }
package console import ( "fmt" "github.com/MikeAWilliams/turing_machine/machine" "github.com/fatih/color" "github.com/eiannone/keyboard" ) func outputState(state machine.StateReport, row int) { fmt.Printf("%v ", row) for j := 0; j < state.SquareIndex; j++ { fmt.Printf("%v", string(state.Squares[j])) } redText := color.New(color.FgRed, color.Bold) currentSquare := state.Squares[state.SquareIndex] if ' ' == currentSquare { currentSquare = '_' } redText.Printf("%v", string(currentSquare)) for j := state.SquareIndex + 1; j < len(state.Squares); j++ { fmt.Printf("%v", string(state.Squares[j])) } fmt.Printf(" %v %v %v \n", state.CurrentConfiguration, state.OperationRow, state.OperationColumn) } func ExecuteOperations(machine machine.Machine, n int) { for i := 0; i < n; i++ { state := machine.StateReport() outputState(state, i) tmpMachine, err := machine.Operate() if nil != err { panic(err) } machine = tmpMachine } fmt.Printf("Done\nFinal Tape\n%v", machine.TapeAsString()) } func ExecuteInteractive(currentMachine machine.Machine) { if err := keyboard.Open(); err != nil { panic(err) } defer func() { _ = keyboard.Close() }() fmt.Println("Press b to pop state. q to quit. Any other key advances") row := 0 var machineStack []machine.Machine machineStack = append(machineStack, currentMachine) for { state := currentMachine.StateReport() outputState(state, row) key, _, err := keyboard.GetKey() if err != nil { panic(err) } switch key { case 'q': return case 'b': lastIndex := len(machineStack) - 1 currentMachine = machineStack[lastIndex] machineStack = machineStack[:lastIndex] row-- default: tmpMachine, err := currentMachine.Operate() if nil != err { panic(err) } machineStack = append(machineStack, currentMachine) currentMachine = tmpMachine row++ } } }
gitwww ------ Set up infrastructure for push-to-deploy websites. License ------- Apache 2 Contact ------- Andrew Leonard: * @anl on Github * @da0s1a on Twitter Support ------- Please log tickets and issues at on [Github](https://github.com/anl/puppet-gitwww).
import axios from 'axios' import tools from "../services/tools" // var tokenContent = tools.getCookie('token'); // var token = 'Basic ' + tokenContent; var instance = axios.create({ timeout: 10000, headers: { 'Content-Type': 'application/json' }, // transformResponse: [function (res) { // // ๅœจๆญค่ฝฌ็ ๆ•ฐๆฎ // return res; // }], }); instance.interceptors.response.use(function (response) { // ๅฏนๅ“ๅบ”ๆ•ฐๆฎๅš็‚นไป€ไนˆ return response.data; }, function (error) { // ๅฏนๅ“ๅบ”้”™่ฏฏๅš็‚นไป€ไนˆ console.log("ๅฏนๅ“ๅบ”้”™่ฏฏๅš็‚นไป€ไนˆ",error); return Promise.reject(error); }); var post = function (apiurl, data, fn,err) { return instance.post(apiurl, data).then(res => { fn(res) return res; }).catch(e => { err && err(e); }); } var get = function (url, data, fn) { return instance.get(url, data).then(res => { fn(res) return res; }); } const assemblUrl = function(url){ var pageDomain = { release: "https://opensource.zealink.com/simulatedTransactionH5", deBug: "http://web.zealink.net/simulatedTransactionH5", isDeBug : false //็ป™ๅผ ่ˆช๏ผštrue,ๅ‘ๅธƒๆต‹่ฏ•ๆœๅŠกๅ™จ๏ผšfalse }; var page = pageDomain.isDeBug ? pageDomain.release : pageDomain.deBug; if (url == undefined) { return page; } return page + url; } //"https://opensource.zealink.com", const assemblApi = function(url){ var apiDomain = { release: "https://cusitscapi.zealink.com", deBug: "https://apitest.zealink.com", isDeBug : true //็ป™ๅผ ่ˆช๏ผštrue,ๅ‘ๅธƒๆต‹่ฏ•ๆœๅŠกๅ™จ๏ผšfalse }; var api = apiDomain.isDeBug ? apiDomain.release : apiDomain.deBug; if (url == undefined) { return api; } return api + url; } const assemblOSS = function(url){ var OSSDomain = 'https://projectcache.zealink.com'; if (url == undefined) { return OSSDomain; } return OSSDomain + url; } const urlObj = { //ๆ–นๆณ• post: post, get: get, assemblApi:assemblApi, assemblUrl:assemblUrl, } export default urlObj;
--- title: "[์ •๋ณด์ฒ˜๋ฆฌ๊ธฐ์‚ฌ ํ•„๊ธฐ] 4-1. ์„œ๋ฒ„ ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„" excerpt: ์ •๋ณด์ฒ˜๋ฆฌ๊ธฐ์‚ฌ ํ•„๊ธฐ 4๊ณผ๋ชฉ 1์žฅ categories: - JCKP tags: - - JCKP toc: true toc_sticky: true popular: true date: '2021-08-01T09:00:00' last_modified_at: 2021-08-01T09:00:00 --- 2020 ์‹œ๋‚˜๊ณต ์ •๋ณด์ฒ˜๋ฆฌ๊ธฐ์‚ฌ ํ•„๊ธฐ์ฑ… ์ฐธ๊ณ  {: .notice--primary} **์ฃผ์˜!** ์ค‘์š”๋„๊ฐ€ ๋‚ฎ์€ ํ•ญ๋ชฉ(C)์€ ์ผ๋ถ€ ์ œ์™ธ {: .notice--danger} ## 1. ๊ฐœ๋ฐœ ํ™˜๊ฒฝ ๊ตฌ์ถ• -- B ### - ๊ฐœ๋ฐœ ํ™˜๊ฒฝ ๊ตฌ์ถ•์˜ ๊ฐœ์š” - ๊ฐœ๋ฐœ ํ”„๋กœ์ ํŠธ๋ฅผ ์ดํ•ดํ•˜๊ณ  ์†Œํ”„ํŠธ์›จ์–ด ๋ฐ ํ•˜๋“œ์›จ์–ด ์žฅ๋น„๋ฅผ ๊ตฌ์ถ•ํ•˜๋Š” ๊ฒƒ - ์‘์šฉ ์†Œํ”„ํŠธ์›จ์–ด๊ฐ€ ์šด์˜๋  ํ™˜๊ฒฝ๊ณผ ์œ ์‚ฌํ•œ ๊ตฌ์กฐ๋กœ ๊ตฌ์ถ• - ๊ฐœ๋ฐœ ํ”„๋กœ์ ํŠธ์˜ ๋ถ„์„ ๋‹จ๊ณ„์˜ ์‚ฐ์ถœ๋ฌผ์„ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐœ๋ฐœ์— ํ•„์š”ํ•œ ํ•˜๋“œ์›จ์–ด์™€ ์†Œํ”„ํŠธ์›จ์–ด๋ฅผ ์„ ์ • - ๋น„์ฆˆ๋‹ˆ์Šค ํ™˜๊ฒฝ์— ์ ํ•ฉํ•œ ์ œํ’ˆ๋“ค์„ ์ตœ์ข…์ ์œผ๋กœ ๊ฒฐ์ •ํ•˜์—ฌ ๊ตฌ์ถ• ### - ํ•˜๋“œ์›จ์–ด ํ™˜๊ฒฝ - ์ธํ„ฐํŽ˜์ด์Šค ์—ญํ• ์„ ํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ, ํด๋ผ์ด์–ธํŠธ์™€ ํ†ต์‹ ํ•˜์—ฌ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๋Š” ์„œ๋ฒ„๋กœ ๊ตฌ์„ฑ - ํด๋ผ์ด์–ธํŠธ์—๋Š” PC, ์Šค๋งˆํŠธํฐ ๋“ฑ์ด ์žˆ์Œ - ์„œ๋ฒ„๋Š” ์‚ฌ์šฉ ๋ชฉ์ ์— ๋”ฐ๋ผ ์›น ์„œ๋ฒ„, ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์„œ๋ฒ„, DB ์„œ๋ฒ„, ํŒŒ์ผ ์„œ๋ฒ„ ๋“ฑ์ด ์žˆ์Œ - ์›น ์„œ๋ฒ„(Web Server) - ํด๋ผ์ด์–ธํŠธ๋กœ๋ถ€ํ„ฐ ์ง์ ‘ ์š”์ฒญ์„ ๋ฐ›์•„ ์ฒ˜๋ฆฌํ•˜๋Š” ์„œ๋ฒ„. ์ •์  ํŒŒ์ผ๋“ค์„ ์ œ๊ณต - Apache HTTP Server, Microsoft Internet Information Service, Google Web Server ๋“ฑ - ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์„œ๋ฒ„(WAS; Web Application Server) - ๋™์  ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•ด ์›น ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์š”์ฒญ์„ ๋ฐ›์•„ ๋ฐ์ดํ„ฐ ๊ฐ€๊ณต ์ž‘์—…์„ ์ˆ˜ํ–‰ - ์›น ์„œ๋ฒ„์™€ DB์„œ๋ฒ„ ๋˜๋Š” ์›น ์„œ๋ฒ„์™€ ํŒŒ์ผ ์„œ๋ฒ„ ์‚ฌ์ด์—์„œ ์ธํ„ฐํŽ˜์ด์Šค ์—ญํ•  ์ˆ˜ํ–‰ - Apache Tomcat, IBM WebSphere, Oracle WebLogic ๋“ฑ - DB Server - DB์™€ ์ด๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” DBMS๋ฅผ ์šด์˜ํ•˜๋Š” ์„œ๋ฒ„ - MySQL Server, Oracle Server, Microsoft SQL Server ๋“ฑ - ํŒŒ์ผ ์„œ๋ฒ„(File Server) - DB์— ์ €์žฅํ•˜๊ธฐ์—๋Š” ๋น„ํšจ์œจ์ ์ด๊ฑฐ๋‚˜, ์„œ๋น„์Šค ์ œ๊ณต์„ ๋ชฉ์ ์œผ๋กœ ์œ ์ง€ํ•˜๋Š” ํŒŒ์ผ๋“ค์„ ์ €์žฅํ•˜๋Š” ์„œ๋ฒ„ - AWS S3 ๋“ฑ ### - Web Server์˜ ๊ธฐ๋Šฅ - HTTP/HTTPS ์ง€์› : ๋ธŒ๋ผ์šฐ์ €๋กœ๋ถ€ํ„ฐ ์š”์ฒญ์„ ๋ฐ›์•„ ์‘๋‹ตํ•  ๋•Œ ์‚ฌ์šฉ๋˜๋Š” ํ”„๋กœํ† ์ฝœ - ํ†ต์‹  ๊ธฐ๋ก : ์ฒ˜๋ฆฌํ•œ ์š”์ฒญ๋“ค์„ ๋กœ๊ทธ ํŒŒ์ผ๋กœ ๊ธฐ๋กํ•˜๋Š” ๊ธฐ๋Šฅ - ์ •์  ํŒŒ์ผ ๊ด€๋ฆฌ : HTML, CSS, ์ด๋ฏธ์ง€ ๋“ฑ์˜ ์ •์  ํŒŒ์ผ๋“ค์„ ์ €์žฅํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๋Š” ๊ธฐ๋Šฅ - ๋Œ€์—ญํญ ์ œํ•œ : ๋„คํŠธ์›Œํฌ ํŠธ๋ž˜ํ”ฝ์˜ ํฌํ™”๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ์‘๋‹ต ์†๋„๋ฅผ ์ œํ•œํ•˜๋Š” ๊ธฐ๋Šฅ - ๊ฐ€์ƒ ํ˜ธ์ŠคํŒ… : ํ•˜๋‚˜์˜ ์„œ๋ฒ„๋กœ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋„๋ฉ”์ธ ์ด๋ฆ„์„ ์—ฐ๊ฒฐํ•˜๋Š” ๊ธฐ๋Šฅ - ์ธ์ฆ : ์‚ฌ์šฉ์ž๊ฐ€ ํ•ฉ๋ฒ•์ ์ธ ์‚ฌ์šฉ์ž์ธ์ง€๋ฅผ ํ™•์ธํ•˜๋Š” ๊ธฐ๋Šฅ ### - ์†Œํ”„ํŠธ์›จ์–ด ํ™˜๊ฒฝ - ํด๋ผ์ด์–ธํŠธ + ์„œ๋ฒ„ ์šด์˜์„ ์œ„ํ•œ ์‹œ์Šคํ…œ S/W + ๊ฐœ๋ฐœ์— ์‚ฌ์šฉ๋˜๋Š” ๊ฐœ๋ฐœ S/W - ์‹œ์Šคํ…œ S/W : ์šด์˜์ฒด์ œ, ์›น ์„œ๋ฒ„ ๋ฐ WAS ์šด์šฉ์„ ์œ„ํ•œ ์„œ๋ฒ„ ํ”„๋กœ๊ทธ๋žจ, DBMS ๋“ฑ - ๊ฐœ๋ฐœ S/W : ์š”๊ตฌ์‚ฌํ•ญ ๊ด€๋ฆฌ ๋„๊ตฌ, ์„ค๊ณ„/๋ชจ๋ธ๋ง ๋„๊ตฌ, ๊ตฌํ˜„ ๋„๊ตฌ, ๋นŒ๋“œ ๋„๊ตฌ, ํ…Œ์ŠคํŠธ ๋„๊ตฌ, ํ˜•์ƒ๊ด€๋ฆฌ ๋„๊ตฌ - ์š”๊ตฌ์‚ฌํ•ญ ๊ด€๋ฆฌ ๋„๊ตฌ - ์š”๊ตฌ์‚ฌํ•ญ์˜ ์ˆ˜์ง‘๊ณผ ๋ถ„์„, ์ถ”์  ๋“ฑ์„ ํŽธ๋ฆฌํ•˜๊ฒŒ ๋„์™€์ฃผ๋Š” S/W - JIRA, IBM DOORS, inteGREAT, Reqtify, Trello ๋“ฑ - ์„ค๊ณ„/๋ชจ๋ธ๋ง ๋„๊ตฌ - UML์„ ์ง€์›ํ•˜๋ฉฐ, ๊ฐœ๋ฐœ์˜ ์ „ ๊ณผ์ •์—์„œ ์„ค๊ณ„ ๋ฐ ๋ชจ๋ธ๋ง์„ ๋„์™€์ฃผ๋Š” S/W - DB Designer, PlantUML, ArgoUML - ๊ตฌํ˜„ ๋„๊ตฌ - ๊ฐœ๋ฐœ ์–ธ์–ด๋ฅผ ํ†ตํ•ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์‹ค์ œ ๊ตฌํ˜„์„ ์ง€์›ํ•˜๋Š” S/W - Eclipse, IntelliJ IDEA, Visual Studio, Netbeans, Node.js ๋“ฑ - ๋นŒ๋“œ ๋„๊ตฌ - ๊ตฌํ˜„ ๋„๊ตฌ๋ฅผ ํ†ตํ•ด ์ž‘์„ฑ๋œ ์†Œ์Šค์˜ ๋นŒ๋“œ ๋ฐ ๋ฐฐํฌ, ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ด€๋ฆฌ๋ฅผ ์ง€์›ํ•˜๋Š” S/W - Ant, Graddle, Maven, Jenkins ๋“ฑ - ํ…Œ์ŠคํŠธ ๋„๊ตฌ - ๋ชจ๋“ˆ๋“ค์ด ์š”๊ตฌ์‚ฌํ•ญ์— ์ ํ•ฉํ•˜๊ฒŒ ๊ตฌํ˜„๋˜์—ˆ๋Š”์ง€ ํ…Œ์ŠคํŠธํ•˜๋Š” S/W - CppUnit, JUnit, HttpUnit, NUnit, SpringTest ๋“ฑ - ํ˜•์ƒ ๊ด€๋ฆฌ ๋„๊ตฌ - ์‚ฐ์ถœ๋ฌผ๋“ค์„ ๋ฒ„์ „๋ณ„๋กœ ๊ด€๋ฆฌํ•˜์—ฌ ํ’ˆ์งˆ ํ–ฅ์ƒ์„ ์ง€์›ํ•˜๋Š” S/W - GIT, CVS, Subversion, Mercurial ### - ๊ฐœ๋ฐœ ์–ธ์–ด์˜ ์„ ์ • ๊ธฐ์ค€ - ์ ์ •์„ฑ, ํšจ์œจ์„ฑ, ์ด์‹์„ฑ, ์นœ๋ฐ€์„ฑ, ๋ฒ”์šฉ์„ฑ <br> ## 2. ๋ณด์•ˆ ๋ฐ API -- B ### - ์†Œํ”„ํŠธ์›จ์–ด ๊ฐœ๋ฐœ ๋ณด์•ˆ์˜ ๊ฐœ์š” - ๋ณด์•ˆ ์ทจ์•ฝ์ ์„ ์ตœ์†Œํ™”ํ•˜์—ฌ ๋ณด์•ˆ ์œ„ํ˜‘์œผ๋กœ๋ถ€ํ„ฐ ์•ˆ์ „ํ•œ S/W๋ฅผ ๊ฐœ๋ฐœํ•˜๊ธฐ ์œ„ํ•œ ์ผ๋ จ์˜ ๋ณด์•ˆ ํ™œ๋™ - S/W ๊ฐœ๋ฐœ ๋ณด์•ˆ์€ ๋ฐ์ดํ„ฐ์˜ ๊ธฐ๋ฐ€์„ฑ, ๋ฌด๊ฒฐ์„ฑ, ๊ฐ€์šฉ์„ฑ์„ ์œ ์ง€ํ•˜๋Š” ๊ฒƒ์„ ๋ชฉํ‘œ๋กœ ํ•จ - S/W ๊ฐœ๋ฐœ ๋ณด์•ˆ ๊ฐ€์ด๋“œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ์ ๊ฒ€ํ•ด์•ผ ํ•  ๋ณด์•ˆ ํ•ญ๋ชฉ๋“ค์„ ์ ๊ฒ€ ### - ์†Œํ”„ํŠธ์›จ์–ด ๊ฐœ๋ฐœ ๋ณด์•ˆ ์ ๊ฒ€ ํ•ญ๋ชฉ - ์„ธ์…˜ ํ†ต์ œ - ์„ธ์…˜์˜ ์—ฐ๊ฒฐ๊ณผ ์—ฐ๊ฒฐ๋กœ ์ธํ•ด ๋ฐœ์ƒํ•˜๋Š” ์ •๋ณด๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” ๋ถˆ์ถฉ๋ถ„ํ•œ ์„ธ์…˜ ๊ด€๋ฆฌ, ์ž˜๋ชป๋œ ์„ธ์…˜์— ์˜ํ•œ ์ •๋ณด ๋…ธ์ถœ ๋“ฑ - ์ž…๋ ฅ ๋ฐ์ดํ„ฐ ๊ฒ€์ฆ ๋ฐ ํ‘œํ˜„ - ์ž…๋ ฅ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์œ ํšจ๊ฒ€ ๊ฒ€์ฆ์ฒด๊ณ„๋ฅผ ๊ฐ–์ถ”๊ณ , ๊ฒ€์ฆ ์‹คํŒจ ์‹œ ์ด๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ์ฝ”๋”ฉ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” SQL ์‚ฝ์ž…, ๊ฒฝ๋กœ ์กฐ์ž‘ ๋ฐ ์ž์› ์‚ฝ์ž…, ํฌ๋กœ์Šค์‚ฌ์ดํŠธ ์Šคํฌ๋ฆฝํŒ…(XSS) ๋“ฑ - ๋ณด์•ˆ ๊ธฐ๋Šฅ - ์ธ์ฆ, ์ ‘๊ทผ์ œ์–ด, ๊ธฐ๋ฐ€์„ฑ, ์•”ํ˜ธํ™” ๋“ฑ์˜ ๊ธฐ๋Šฅ์„ ์˜๋ฏธ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” ์ ์ ˆํ•œ ์ธ์ฆ ์—†๋Š” ์ค‘์š”๊ธฐ๋Šฅ ํ—ˆ์šฉ, ๋ถ€์ ์ ˆํ•œ ์ธ๊ฐ€ ๋“ฑ - ์‹œ๊ฐ„ ๋ฐ ์ƒํƒœ - ๋‹ค์ˆ˜์˜ ํ”„๋กœ์„ธ์Šค๊ฐ€ ๋™์ž‘ํ•˜๋Š” ํ™˜๊ฒฝ์—์„œ ์‹œ๊ฐ„๊ณผ ์‹คํ–‰ ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜์—ฌ ์‹œ์Šคํ…œ์ด ์›ํ™œํžˆ ๋™์ž‘๋˜๋„๋ก ์ฝ”๋”ฉ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” ๊ฒ€์‚ฌ ์‹œ์ ๊ณผ ์‚ฌ์šฉ ์‹œ์ (TOCTOU) ๊ฒฝ์Ÿ์กฐ๊ฑด, ์ข…๋ฃŒ๋˜์ง€ ์•Š๋Š” ๋ฐ˜๋ณต๋ฌธ ๋˜๋Š” ์žฌ๊ท€ํ•จ์ˆ˜ ๋“ฑ - ์—๋Ÿฌ์ฒ˜๋ฆฌ - ์˜ค๋ฅ˜๋“ค์„ ์‚ฌ์ „์— ์ •์˜ํ•˜์—ฌ ์—๋Ÿฌ๋กœ ์ธํ•ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋“ค์„ ์˜ˆ๋ฐฉ - ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€๋ฅผ ํ†ตํ•œ ์ •๋ณด ๋…ธ์ถœ, ์˜ค๋ฅ˜ ์ƒํ™ฉ ๋Œ€์‘ ๋ถ€์žฌ ๋“ฑ - ์ฝ”๋“œ ์˜ค๋ฅ˜ - ์ฝ”๋”ฉ ์ค‘ ์‹ค์ˆ˜ํ•˜๊ธฐ ์‰ฌ์šด Type ๋ณ€ํ™˜, ์ž์›์˜ ๋ฐ˜ํ™˜ ๋“ฑ์„ ๊ณ ๋ คํ•˜๋ฉฐ ์ฝ”๋”ฉ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” ๋„ ํฌ์ธํ„ฐ ์—ญ์ฐธ์กฐ, ๋ถ€์ ์ ˆํ•œ ์ž์› ํ•ด์ œ ๋“ฑ - ์บก์Аํ™” - ๋ฐ์ดํ„ฐ์™€ ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ํ•˜๋‚˜์˜ ๊ฐ์ฒด๋กœ ๋ฌถ์–ด ์ฝ”๋”ฉํ•˜๋Š” ๊ฒƒ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” ์ž˜๋ชป๋œ ์„ธ์…˜์— ์˜ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด ๋…ธ์ถœ, ์ œ๊ฑฐ๋˜์ง€ ์•Š๊ณ  ๋‚จ์€ ๋””๋ฒ„๊ทธ ์ฝ”๋“œ ๋“ฑ - API ์˜ค์šฉ - API๋ฅผ ์ž˜๋ชป ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋ณด์•ˆ์— ์ทจ์•ฝํ•œ API๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋„๋ก ๊ณ ๋ คํ•˜์—ฌ ์ฝ”๋”ฉ - ๋ณด์•ˆ ์•ฝ์ ์—๋Š” DNS lookup์— ์˜์กดํ•œ ๋ณด์•ˆ๊ฒฐ์ •, ์ทจ์•ฝํ•œ API ์‚ฌ์šฉ ### - API(Application Programming Interface) - ์šด์˜์ฒด์ œ๋‚˜ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด ๋“ฑ์— ์žˆ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ทœ์น™ ๋“ฑ์„ ์ •์˜ํ•ด ๋†“์€ ์ธํ„ฐํŽ˜์ด์Šค - ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์—์„œ ํŠน์ •ํ•œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ - ์šด์˜์ฒด์ œ์˜ ํŒŒ์ผ ์ œ์–ด, ํ™”์ƒ ์ฒ˜๋ฆฌ, ๋ฌธ์ž ์ œ์–ด ๋“ฑ์˜ ๊ธฐ๋Šฅ์„ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ - ๊ฐœ๋ฐœ์— ํ•„์š”ํ•œ ์—ฌ๋Ÿฌ ๋„๊ตฌ๋ฅผ ์ œ๊ณต. ์›ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์‰ฝ๊ณ  ํšจ์œจ์ ์œผ๋กœ ๊ตฌํ˜„ ๊ฐ€๋Šฅ - ๊ณต๊ฐœ๋œ API๋ฅผ Open API๋ผ๊ณ  ํ•จ <br> ## 3. ๋ฐฐ์น˜ ํ”„๋กœ๊ทธ๋žจ -- B ### - ๋ฐฐ์น˜ ํ”„๋กœ๊ทธ๋žจ์˜ ๊ฐœ์š” - ์‚ฌ์šฉ์ž์™€์˜ ์ƒํ˜ธ ์ž‘์šฉ ์—†์ด ์—ฌ๋Ÿฌ ์ž‘์—…๋“ค์„ ๋ฏธ๋ฆฌ ์ •ํ•ด์ง„ ์ผ๋ จ์˜ ์ˆœ์„œ์— ๋”ฐ๋ผ ์ผ๊ด„์ ์œผ๋กœ ์ฒ˜๋ฆฌ - ์ •๊ธฐ ๋ฐฐ์น˜ : ์ •ํ•ด์ง„ ๊ธฐ๊ฐ„์— ์ •๊ธฐ์ ์œผ๋กœ ์ˆ˜ํ–‰ - ์ด๋ฒคํŠธ์„ฑ ๋ฐฐ์น˜ : ์กฐ๊ฑด์ด ์ถฉ์กฑ๋  ๋•Œ๋งŒ ์ˆ˜ํ–‰ - On-Demand ๋ฐฐ์น˜ : ์‚ฌ์šฉ์ž ์š”์ฒญ ์‹œ ์ˆ˜ํ–‰ - ํ•„์ˆ˜์š”์†Œ : ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ, ์ž๋™ํ™”, ๊ฒฌ๊ณ ์„ฑ, ์•ˆ์ •์„ฑ/์‹ ๋ขฐ์„ฑ, ์„ฑ๋Šฅ ### - ๋ฐฐ์น˜ ์Šค์ผ€์ค„๋Ÿฌ - ์ผ๊ด„ ์ฒ˜๋ฆฌ ์ž‘์—…์ด ์„ค์ •๋œ ์ฃผ๊ธฐ์— ๋งž์ถฐ ์ž๋™์œผ๋กœ ์ˆ˜ํ–‰๋˜๋„๋ก ์ง€์›ํ•ด์ฃผ๋Š” ๋„๊ตฌ - ํŠน์ • ์—…๋ฌด๋ฅผ ์›ํ•˜๋Š” ์‹œ๊ฐ„์— ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ์ง€์›. ์žก์Šค์ผ€์ค„๋Ÿฌ๋ผ๊ณ ๋„ ํ•จ - ์Šคํ”„๋ง ๋ฐฐ์น˜ - ์Šคํ”„๋ง์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ๋“ค์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ - DB๋‚˜ ํŒŒ์ผ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ตํ™˜ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์ปดํฌ๋„ŒํŠธ๋“ค์„ ์ œ๊ณต - ๋กœ๊ทธ ๊ด€๋ฆฌ, ์ถ”์ , ํŠธ๋žœ์žญ์…˜ ๊ด€๋ฆฌ, ์ž‘์—… ์ฒ˜๋ฆฌ ํ†ต๊ณ„, ์ž‘์—… ์žฌ์‹œ์ž‘ ๋“ฑ - ๊ตฌ์„ฑ ์š”์†Œ์™€ ์—ญํ•  - Job : ์ˆ˜ํ–‰ํ•  ์ž‘์—… ์ •์˜ - Job Launcher : ์‹คํ–‰์„ ์œ„ํ•œ ์ธํ„ฐํŽ˜์ด์Šค - Step : Job ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ์ œ์–ด ์ •๋ณด - Job Repository : Step์˜ ์ œ์–ด ์ •๋ณด๋ฅผ ํฌํ•จํ•˜์—ฌ ์ž‘์—… ์‹คํ–‰์„ ์œ„ํ•œ ๋ชจ๋“  ์ •๋ณด ์ €์žฅ - Quartz - ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ๋“ค์˜ ์ผ๊ด„ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ ์ œ๊ณต. ์˜คํ”ˆ ์†Œ์Šค ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ - ์š”์†Œ๋“ค์„ ๋ถ„๋ฆฌํ•˜์—ฌ ์ผ๊ด„ ์ฒ˜๋ฆฌ ์ž‘์—…์— ์œ ์—ฐ์„ฑ ์ œ๊ณต - ๊ตฌ์„ฑ ์š”์†Œ์™€ ์—ญํ•  - Scheduler : ์‹คํ–‰ ํ™˜๊ฒฝ ๊ด€๋ฆฌ - Job : ์ˆ˜ํ–‰ํ•  ์ž‘์—… ์ •์˜ - JobDetail : Job์˜ ์ƒ์„ธ ์ •๋ณด - Trigger : Job์˜ ์‹คํ–‰ ์Šค์ผ€์ค„ ์ •์˜
--- layout: page title: About --- <center> Tens mais razรตes? Manda-nos essas razรตes para <a href="mailto:votarandreventura@gmail.com">votarandreventura@gmail.com</a>! </center>
๏ปฟusing System; using Newtonsoft.Json; namespace GR.Paypal.Abstractions.ViewModels { public class PaymentExecuteVm { [JsonProperty("paymentID")] public string PaymentId { get; set; } [JsonProperty("payerID")] public string PayerId { get; set; } public Guid? OrderId { get; set; } } }
๏ปฟusing Api.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Api.Data.Repositories { public class MessageRepository: IMessageRepository { private readonly FriendContext _mcontext; private readonly DbSet<Message> _messages; public MessageRepository(FriendContext dbContext) { _mcontext = dbContext; _messages = dbContext.Messages; } public void Add(Message message) { _messages.Add(message); } public void Delete(Message message) { _messages.Remove(message); } public IEnumerable<Message> GetAll() { return _messages.ToList(); return _messages; } public Message GetBy(int id) { return _messages.SingleOrDefault(f => f.Id == id); } public IEnumerable<Message> GetBy(string text, DateTime date, string sender) { var messages = _messages.AsQueryable(); return messages.OrderBy(r => r.Text).ToList(); } public void SaveChanges() { _mcontext.SaveChanges(); ; } public void Update(Message message) { _mcontext.Update(message); } } }
BASELINE_DIR=$(pwd) GYM_HOME=/home/wil/workspace/buflightdev/projects/gymfc cd $GYM_HOME COMMIT=$(git describe --always) ENV=AttFC_GyroErr1-Noise0.1_M4_Ep-v0 DIR_NAME=ALG=ppo-ENV=${COMMIT}_${ENV} RESULT_HOME=/home/wil/workspace/buflightdev/projects/results/experiments/${DIR_NAME} export OPENAI_LOGDIR=$RESULT_HOME/logs cd $BASELINE_DIR python3 -m baselines.ppo1.run_flightcontrol \ --env-id=$ENV \ --ckpt-dir=$RESULT_HOME/checkpoints \ --flight-log-dir=$RESULT_HOME/model-progress \ --num-timesteps=1000000 spd-say "Your results are ready for review"
FactoryGirl.define do factory :local_inline, :class => 'CspReport::CspReport' do document_uri "http://localhost:3000" referrer "" blocked_uri "" violated_directive "script-src 'self'" original_policy "script-src 'self'; report-uri /csp/csp_reports" incoming_ip "127.0.0.1" end factory :local_home_index_inline, parent: :local_inline do document_uri "http://localhost:3000/home/index" end factory :local_ipv6_home_index_inline, parent: :local_home_index_inline do incoming_ip "::1" end factory :local_home_about_inline, parent: :local_inline do document_uri "http://localhost:3000/home/about" end factory :local_script_star, parent: :local_inline do violated_directive "script-src *" original_policy "script-src *; report-uri /csp/csp_reports" end end
#include <lingx/core/times.h> #include <sys/time.h> // gettimeofday() #include <time.h> // gmtime_r(), localtime_r() #include <cstdio> // sprintf() #include <mutex> namespace lnx { namespace { const uint TIME_SLOTS_ = 64; uint Slot_ = 0; int Cached_gmtoff_ = 0; Time Cached_time_[TIME_SLOTS_]; char Cached_err_log_time_[TIME_SLOTS_][sizeof("1970/09/28 12:00:00")]; std::mutex Mutex_; } msec_t Current_msec = 0; Time* Cached_time = nullptr; std::string_view Cached_err_log_time; void Time_init() noexcept { Cached_time = &Cached_time_[0]; Time_update(); } void Time_update() noexcept { if (!Mutex_.try_lock()) return; std::lock_guard<std::mutex> lock(Mutex_, std::adopt_lock); struct timeval tv; ::gettimeofday(&tv, nullptr); long sec = tv.tv_sec; long msec = tv.tv_usec / 1000; Current_msec = (msec_t) sec * 1000 + msec; Time* tp = &Cached_time_[Slot_]; if (tp->sec == sec) { tp->msec = msec; return; } Slot_ = (Slot_ + 1) % TIME_SLOTS_; tp = &Cached_time_[Slot_]; tp->sec = sec; tp->msec = msec; struct tm gmt; ::gmtime_r(&sec, &gmt); struct tm tm; ::localtime_r(&sec, &tm); tm.tm_mon++; tm.tm_year += 1900; Cached_gmtoff_ = tm.tm_gmtoff / 60; tp->gmtoff = Cached_gmtoff_; char* p1 = &Cached_err_log_time_[Slot_][0]; std::sprintf(p1, "%4d/%02d/%02d %02d:%02d:%02d", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); Cached_time = tp; Cached_err_log_time = p1; } void Time_sigsafe_update() noexcept { if (!Mutex_.try_lock()) return; std::lock_guard<std::mutex> lock(Mutex_, std::adopt_lock); struct timeval tv; ::gettimeofday(&tv, nullptr); long sec = tv.tv_sec; Time* tp = &Cached_time_[Slot_]; if (tp->sec == sec) return; Slot_ = (Slot_ + 1) % TIME_SLOTS_; tp = &Cached_time_[Slot_]; tp->sec = 0; struct tm tm; long tmp = sec + Cached_gmtoff_ * 60; ::gmtime_r(&tmp, &tm); char* p1 = &Cached_err_log_time_[Slot_][0]; std::sprintf(p1, "%4d/%02d/%02d %02d:%02d:%02d", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); Cached_err_log_time = p1; } /* * Linux does not test /etc/localtime change in localtime(), * but may stat("/etc/localtime") several times in every strftime(), * therefore we use it to update timezone. */ void Timezone_update() noexcept { time_t t = ::time(0); struct tm* tm = ::localtime(&t); char buf[4]; ::strftime(buf, 4, "%H", tm); } }
// Stub header file of cuTENSOR #ifndef INCLUDE_GUARD_STUB_CUPY_CUTENSOR_H #define INCLUDE_GUARD_STUB_CUPY_CUTENSOR_H #include "../cupy_cuda_common.h" extern "C" { typedef enum {} cudaDataType_t; typedef enum { CUTENSOR_STATUS_SUCCESS = 0, } cutensorStatus_t; typedef enum {} cutensorAlgo_t; typedef enum {} cutensorOperator_t; typedef enum {} cutensorWorksizePreference_t; typedef enum {} cutensorComputeType_t; typedef void* cutensorHandle_t; typedef void* cutensorTensorDescriptor_t; typedef void* cutensorContractionDescriptor_t; typedef void* cutensorContractionFind_t; typedef void* cutensorContractionPlan_t; cutensorStatus_t cutensorInit(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorInitTensorDescriptor(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorElementwiseTrinary(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorElementwiseBinary(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorInitContractionDescriptor(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorInitContractionFind(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorInitContractionPlan(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorContraction(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorContractionGetWorkspace(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorContractionMaxAlgos(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorReduction(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorReductionGetWorkspace(...) { return CUTENSOR_STATUS_SUCCESS; } cutensorStatus_t cutensorGetAlignmentRequirement(...) { return CUTENSOR_STATUS_SUCCESS; } size_t cutensorGetVersion(...) { return CUTENSOR_STATUS_SUCCESS; } const char* cutensorGetErrorString(...) { return NULL; } } // extern "C" #endif // #ifndef INCLUDE_GUARD_STUB_CUPY_CUTENSOR_H
require 'helper' describe Quaderno::Item do context 'A user with an authenticate token with items' do before(:each) do Quaderno::Base.configure do |config| config.auth_token = TEST_KEY config.url = TEST_URL config.api_version = nil end end it 'should get all items (populated db)' do VCR.use_cassette('all items') do items = Quaderno::Item.all expect(items.is_a? Array).to be true items.each { |item| expect(item.is_a? Quaderno::Item).to be true } end end it 'should find an item' do VCR.use_cassette('found item') do new_item = Quaderno::Item.create(code: Time.now.to_i.to_s, name: 'Test_Skynet', unit_cost: 21.00) item = Quaderno::Item.find new_item.id expect(item.is_a? Quaderno::Item).to be true expect(item.id).to eq(new_item.id) end end it 'should create an item' do VCR.use_cassette('new item') do item = Quaderno::Item.create(code: '000000', name: 'Test_Skynet', unit_cost: 21.00) expect(item.is_a? Quaderno::Item).to be true expect(item.code).to eq '000000' expect(item.name).to eq 'Test_Skynet' end end it 'should update an item' do VCR.use_cassette('updated item') do new_item = Quaderno::Item.create(code: Time.now.to_i.to_s, name: 'Test_Skynet', unit_cost: 21.00) item = Quaderno::Item.update(new_item.id, name: 'Test_OCP') expect(item.is_a? Quaderno::Item).to be true expect(item.name).to eq 'Test_OCP' end end it 'should delete a item' do VCR.use_cassette('deleted item') do items_before = Quaderno::Item.all item_id = items_before.last.id Quaderno::Item.delete item_id items_after = Quaderno::Item.all expect(items_before.length - items_after.length).to eq 1 end end it 'should know the rate limit' do VCR.use_cassette('rate limit') do rate_limit_info = Quaderno::Base.rate_limit_info expect(rate_limit_info[:remaining] < 2000).to be true end end end end
module Main where import BGPRib.PTE import BGPRib.PT main :: IO () main = do let v0 = (42,4) v1 = (42,6) v2 = (42,1) v3 = (42,3) vw = (42,0) t0 = [] t1 = [v0] t2 = [(42,3)] t3 = [(42,5)] t4 = [(99,3)] t5 = [(99,5)] t6 = [(99,5),(99,3)] t7 = [(99,5),(99,3),(42,2)] t8 = [(99,5),(42,3),(99,2)] t9 = [(42,7),(99,5),(99,2)] test :: RD -> [RD] -> IO() test a b = putStrLn $ show (pteUpdate a b) ++ " (" ++ show b ++ ")" putStrLn "delete cases" test vw t0 test vw t1 test vw t2 test vw t3 test vw t4 test vw t5 test vw t6 test vw t7 test vw t8 test vw t9 putStrLn "insert cases - mid preference" test v0 t0 test v0 t1 test v0 t2 test v0 t3 test v0 t4 test v0 t5 test v0 t6 test v0 t7 test v0 t8 test v0 t9 putStrLn "insert cases - high preference" test v1 t4 test v1 t5 test v1 t6 test v1 t7 test v1 t8 test v1 t9 putStrLn "insert cases - low preference" test v2 t4 test v2 t5 test v2 t6 test v2 t7 test v2 t8 test v2 t9 putStrLn "insert cases - mid/equal preference" test v3 t4 test v3 t5 test v3 t6 test v3 t7 test v3 t8 test v3 t9
package matms.domain; public enum Permission { PARTICIPANT, TRAINER, ORGANIZER; }
๏ปฟusing System; using System.CodeDom; using System.Reflection; namespace CodeDomExt.Helpers { /// <summary> /// Possible accessibility levels /// </summary> public enum AccessibilityLevel { #pragma warning disable 1591 Public, Protected, Internal, ProtectedInternal, Private, PrivateProtected, Default #pragma warning restore 1591 } /// <summary> /// Utility class for accessibility level /// </summary> public static class AccessibilityLevelUtils { /// <summary> /// Returns the accessibility level /// </summary> /// <param name="attr"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static AccessibilityLevel GetAccessibilityLevel(this TypeAttributes attr) { switch (TypeAttributes.VisibilityMask & attr) { case TypeAttributes.Public: case TypeAttributes.NestedPublic: return AccessibilityLevel.Public; case TypeAttributes.NotPublic: case TypeAttributes.NestedAssembly: return AccessibilityLevel.Internal; case TypeAttributes.NestedPrivate: return AccessibilityLevel.Private; case TypeAttributes.NestedFamily: return AccessibilityLevel.Protected; case TypeAttributes.NestedFamANDAssem: return AccessibilityLevel.PrivateProtected; case TypeAttributes.NestedFamORAssem: return AccessibilityLevel.ProtectedInternal; } throw new ArgumentOutOfRangeException(); } /// <summary> /// Returns the type attribute visibility flag for the correponding accessibility level /// </summary> /// <param name="accessibilityLevel"></param> /// <returns></returns> public static TypeAttributes GetTypeAttribute(this AccessibilityLevel accessibilityLevel) { switch (accessibilityLevel) { case AccessibilityLevel.Public: return TypeAttributes.Public; case AccessibilityLevel.Protected: return TypeAttributes.NestedFamily; case AccessibilityLevel.ProtectedInternal: return TypeAttributes.NestedFamORAssem; case AccessibilityLevel.Private: return TypeAttributes.NestedPrivate; case AccessibilityLevel.PrivateProtected: return TypeAttributes.NestedFamANDAssem; case AccessibilityLevel.Internal: case AccessibilityLevel.Default: return TypeAttributes.NotPublic; default: throw new ArgumentOutOfRangeException(nameof(accessibilityLevel), accessibilityLevel, null); } } /// <summary> /// Returns the accessibility level /// </summary> /// <param name="attr"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static AccessibilityLevel GetAccessibilityLevel(this MemberAttributes attr) { switch (MemberAttributes.AccessMask & attr) { case MemberAttributes.Public: return AccessibilityLevel.Public; case MemberAttributes.Assembly: return AccessibilityLevel.Internal; case MemberAttributes.Private: return AccessibilityLevel.Private; case MemberAttributes.Family: return AccessibilityLevel.Protected; case MemberAttributes.FamilyAndAssembly: return AccessibilityLevel.PrivateProtected; case MemberAttributes.FamilyOrAssembly: return AccessibilityLevel.ProtectedInternal; case 0: return AccessibilityLevel.Default; } throw new ArgumentOutOfRangeException(); } } }
/* ID: baymax01 PROG: text LANG: C++ */ #include <iostream> #include <cmath> #include <iomanip> #include <cstring> #include <algorithm> #include <cstdio> #include <cstdlib> #include <vector> #include <stack> #include <cassert> #include <cctype> #include <queue> using namespace std; int main(){ int n,hi[80005]={0},stack[80005]={0},k=0; long long ans=0; cin>>n; for(int i=1;i<=n;i++)cin>>hi[i]; for(int i=1;i<=n;i++) { while(hi[i]>=stack[k]&&k)k--; ans+=k;//่ฎฐๅฝ•ๅฏไปฅ็œ‹่ง็š„็‰›๏ผˆๆ ˆไธญ๏ผ‰ stack[++k]=hi[i];//ๅ…ฅๆ ˆ } cout<<ans; return 0; }
๏ปฟusing Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using TewiClipool.Server.Data; using TewiClipool.Shared; using TewiClipool.Shared.Models; namespace TewiClipool.Server.Controllers { [ApiController] [Route(Literal.ApiUrls.Staff)] [Authorize] public class StaffController : DbControllerBase<StaffItem> { public StaffController(ApplicationDbContext db, ILogger<DbControllerBase<StaffItem, int>> logger, HtmlEncoder htmlEncoder) : base(db, logger, htmlEncoder) { } [HttpPost] [Authorize(Roles = Literal.Roles.User)] public override async Task<ActionResult<int>> Create(StaffItem model) { if (!(await GetUser()).IsUser) return Forbid(); if (!HttpContext.User.IsInRole(Enum.GetName(model.Type))) { return BadRequest(); } var clip = await db.Clips.FirstOrDefaultAsync(c => c.Id == model.ClipId); if (clip == null || clip.Priority == PriorityType.Completed || clip.Priority == PriorityType.Desperated) { return BadRequest(); } model.Process = ProcessType.Accepted; model.AcceptTime = DateTime.Now; model.Description = model.Description; model.StaffNickName = model.StaffNickName; model.UserName = await GetUserName(); var staff = await db.StaffItems.AddAsync(model); await db.SaveChangesAsync(); return Ok(staff.Entity.Id); } [HttpDelete("id/{id}")] [Authorize(Roles = Literal.Roles.User)] public override async Task<ActionResult> Delete(int id) { if (!(await GetUser()).IsUser) return Forbid(); var staff = await db.StaffItems.FindAsync(id); var permission = staff.UserName == await GetUserName(); if (permission || HttpContext.User.IsInRole(Literal.Roles.Operator)) { logger.LogInformation($"Staff {id} is deleted"); db.StaffItems.Remove(staff); await db.SaveChangesAsync(); return Ok(); } return BadRequest(); } [HttpGet] public override async Task<ActionResult<List<StaffItem>>> Get() { if (!(await GetUser()).IsUser) return Forbid(); return Ok(await db.StaffItems.ToListAsync()); } [HttpGet("id/{id}")] public override async Task<ActionResult<StaffItem>> Get(int id) { if (!(await GetUser()).IsUser) return Forbid(); var staff = await db.StaffItems.FindAsync(id); return staff == null ? NotFound() : Ok(staff); } [HttpGet("clip/{clipid}")] public async Task<ActionResult<StaffItem>> GetByClipId(int clipid) { if (!(await GetUser()).IsUser) return Forbid(); var clip = await db.Clips.FirstOrDefaultAsync(c => c.Id == clipid); if (clip == null) { return NotFound(); } var staff = await db.StaffItems .Where(s => s.ClipId == clipid) .ToListAsync(); return staff == null ? NotFound() : Ok(staff); } [HttpGet("sage/{id}")] public async Task<ActionResult<bool>> ToggleSage(int id) { if (!(await GetUser()).IsUser) return Forbid(); var userid = GetUserId(); var user = await db.Users.FirstOrDefaultAsync(u => u.Id == userid); var staff = await db.StaffItems.FirstOrDefaultAsync(s => s.Id == id); if (user == null || staff == null) { return BadRequest(); } bool permission = user.IsReviewer || user.IsOperator; if (permission) { staff.ToggleSage(); staff.SagedUser = await GetUserName(); db.StaffItems.Update(staff); await db.SaveChangesAsync(); } return Ok(staff.Saged); } [HttpPut] [Authorize(Roles = Literal.Roles.User)] public override async Task<ActionResult> Update(StaffItem model) { if (!(await GetUser()).IsUser) return Forbid(); var staff = await db.StaffItems.FindAsync(model.Id); var clip = await db.Clips.FirstOrDefaultAsync(c => c.Id == staff.ClipId); var permission = staff.UserName == await GetUserName(); if (permission || HttpContext.User.IsInRole(Literal.Roles.Operator)) { staff.Description = model.Description; staff.StaffNickName = model.StaffNickName; staff.ResAddress = model.ResAddress; if (clip.Priority != PriorityType.Desperated && clip.Priority != PriorityType.Completed) { if (staff.Process != ProcessType.Completed && model.Process == ProcessType.Completed) { staff.CompletedTime = DateTime.Now; } staff.Process = model.Process; } db.StaffItems.Update(staff); await db.SaveChangesAsync(); return Ok(); } return BadRequest(); } } }
use vizia::*; fn main() { Application::new(WindowDescription::new().with_title("Binding in View"), |cx| { Data { something: 55 }.build(cx); CustomView::new(cx); }) .run(); } #[derive(Lens)] pub struct Data { something: i32, } impl Model for Data {} pub struct CustomView {} impl CustomView { pub fn new(cx: &mut Context) -> Handle<Self> { Self {}.build(cx) } } impl View for CustomView { fn body(&mut self, cx: &mut Context) { Binding::new(cx, Data::something, |cx, something| { Label::new(cx, &something.get(cx).to_string()); }); } }
SELECT MARA.MANDT AS Client_MANDT, MARA.MATNR AS MaterialNumber_MATNR, MARA.ERSDA AS CreatedOn_ERSDA, MARA.ERNAM AS NameOfPersonWhoCreatedTheObject_ERNAM, MARA.LAEDA AS DateOfLastChange_LAEDA, MARA.AENAM AS NameOfPersonWhoChangedObject_AENAM, MARA.VPSTA AS MaintenanceStatusOfCompleteMaterial_VPSTA, MARA.PSTAT AS MaintenanceStatus_PSTAT, MARA.LVORM AS FlagMaterialForDeletionAtClientLevel_LVORM, MARA.MTART AS MaterialType_MTART, MARA.MBRSH AS IndustrySector_MBRSH, MARA.MATKL AS MaterialGroup_MATKL, MARA.BISMT AS OldMaterialNumber_BISMT, MARA.MEINS AS BaseUnitOfMeasure_MEINS, MARA.BSTME AS OrderUnit_BSTME, MARA.ZEINR AS DocumentNumber_WithoutDocumentManagementSystem_ZEINR, MARA.ZEIAR AS DocumentType_WithoutDocumentManagementSystem_ZEIAR, MARA.ZEIVR AS DocumentVersion_WithoutDocumentManagementSystem_ZEIVR, MARA.ZEIFO AS PageFormatOfDocument_WithoutDocumentManagementSystem_ZEIFO, MARA.AESZN AS DocumentChangeNumber_WithoutDocumentManagementSystem_AESZN, MARA.BLATT AS PageNumberOfDocument_WithoutDocumentManagementSystem_BLATT, MARA.BLANZ AS NumberOfSheets_WithoutDocumentManagementSystem_BLANZ, MARA.FERTH AS ProductioInspectionMemo_FERTH, MARA.FORMT AS PageFormatOfProductionMemo_FORMT, MARA.GROES AS SizeDimensions_GROES, MARA.WRKST AS BasicMaterial_WRKST, MARA.NORMT AS IndustryStandardDescription_SuchAsAnsiOrIso_NORMT, MARA.LABOR AS LaboratoryDesignOffice_LABOR, MARA.EKWSL AS PurchasingValueKey_EKWSL, MARA.BRGEW AS GrossWeight_BRGEW, MARA.NTGEW AS NetWeight_NTGEW, MARA.GEWEI AS WeightUnit_GEWEI, MARA.VOLUM AS Volume_VOLUM, MARA.VOLEH AS VolumeUnit_VOLEH, MARA.BEHVO AS ContainerRequirements_BEHVO, MARA.RAUBE AS StorageConditions_RAUBE, MARA.TEMPB AS TemperatureConditionsIndicator_TEMPB, MARA.DISST AS LowLevelCode_DISST, MARA.TRAGR AS TransportationGroup_TRAGR, MARA.STOFF AS HazardousMaterialNumber_STOFF, MARA.SPART AS Division_SPART, MARA.KUNNR AS Competitor_KUNNR, MARA.EANNR AS EuropeanArticleNumber_EANNR, MARA.WESCH AS Quantity_NumberOfGrgiSlipsToBePrinted_WESCH, MARA.BWVOR AS ProcurementRule_BWVOR, MARA.BWSCL AS SourceOfSupply_BWSCL, MARA.SAISO AS SeasonCategory_SAISO, MARA.ETIAR AS LabelType_ETIAR, MARA.ETIFO AS LabelForm_ETIFO, MARA.ENTAR AS Deactivated_ENTAR, MARA.EAN11 AS InternationalArticleNumber_Eanupc_EAN11, MARA.NUMTP AS CategoryOfInternationalArticleNumber_Ean_NUMTP, MARA.LAENG AS Length_LAENG, MARA.BREIT AS Width_BREIT, MARA.HOEHE AS Height_HOEHE, MARA.MEABM AS UnitOfDimensionForLengthwidthheight_MEABM, MARA.PRDHA AS ProductHierarchy_PRDHA, MARA.AEKLK AS StockTransferNetChangeCosting_AEKLK, MARA.CADKZ AS CadIndicator_CADKZ, MARA.QMPUR AS QmInProcurementIsActive_QMPUR, MARA.ERGEW AS AllowedPackagingWeight_ERGEW, MARA.ERGEI AS UnitOfWeight_AllowedPackagingWeight_ERGEI, MARA.ERVOL AS AllowedPackagingVolume_ERVOL, MARA.ERVOE AS VolumeUnit_AllowedPackagingVolume_ERVOE, MARA.GEWTO AS ExcessWeightToleranceForHandlingUnit_GEWTO, MARA.VOLTO AS ExcessVolumeToleranceOfTheHandlingUnit_VOLTO, MARA.VABME AS VariablePurchaseOrderUnitActive_VABME, MARA.KZREV AS RevisionLevelHasBeenAssignedToTheMaterial_KZREV, MARA.KZKFG AS ConfigurableMaterial_KZKFG, MARA.XCHPF AS BatchManagementRequirementIndicator_XCHPF, MARA.VHART AS PackagingMaterialType_VHART, MARA.FUELG AS MaximumLevel_ByVolume_FUELG, MARA.STFAK AS StackingFactor_STFAK, MARA.MAGRV AS MaterialGroup_PackagingMaterials_MAGRV, MARA.BEGRU AS AuthorizationGroup_BEGRU, MARA.DATAB AS ValidFromDate_DATAB, MARA.LIQDT AS DeletionDate_LIQDT, MARA.SAISJ AS SeasonYear_SAISJ, MARA.PLGTP AS PriceBandCategory_PLGTP, MARA.MLGUT AS EmptiesBillOfMaterial_MLGUT, MARA.EXTWG AS ExternalMaterialGroup_EXTWG, MARA.SATNR AS CrossPlantConfigurableMaterial_SATNR, MARA.ATTYP AS MaterialCategory_ATTYP, MARA.KZKUP AS Indicator_MaterialCanBeCoProduct_KZKUP, MARA.KZNFM AS Indicator_TheMaterialHasAFollowUpMaterial_KZNFM, MARA.PMATA AS PricingReferenceMaterial_PMATA, MARA.MSTAE AS CrossPlantMaterialStatus_MSTAE, MARA.MSTAV AS CrossDistributionChainMaterialStatus_MSTAV, MARA.MSTDE AS DateFromWhichTheCrossPlantMaterialStatusIsValid_MSTDE, MARA.MSTDV AS DateFromWhichTheXDistrChainMaterialStatusIsValid_MSTDV, MARA.TAKLV AS TaxClassificationOfTheMaterial_TAKLV, MARA.RBNRM AS CatalogProfile_RBNRM, MARA.MHDRZ AS MinimumRemainingShelfLife_MHDRZ, MARA.MHDHB AS TotalShelfLife_MHDHB, MARA.MHDLP AS StoragePercentage_MHDLP, MARA.INHME AS ContentUnit_INHME, MARA.INHAL AS NetContents_INHAL, MARA.VPREH AS ComparisonPriceUnit_VPREH, MARA.INHBR AS GrossContents_INHBR, MARA.CMETH AS QuantityConversionMethod_CMETH, MARA.CUOBF AS InternalObjectNumber_CUOBF, MARA.KZUMW AS EnvironmentallyRelevant_KZUMW, MARA.KOSCH AS ProductAllocationDeterminationProcedure_KOSCH, MARA.SPROF AS PricingProfileForVariants_SPROF, MARA.NRFHG AS MaterialQualifiesForDiscountInKind_NRFHG, MARA.MFRPN AS ManufacturerPartNumber_MFRPN, MARA.MFRNR AS ManufacturerNumber_MFRNR, MARA.BMATN AS NumberInventoryManagedMaterial_BMATN, MARA.MPROF AS MfrPartProfile_MPROF, MARA.KZWSM AS UnitsOfMeasureUsage_KZWSM, MARA.SAITY AS RolloutInASeason_SAITY, MARA.PROFL AS DangerousGoodsIndicatorProfile_PROFL, MARA.IHIVI AS Indicator_HighlyViscous_IHIVI, MARA.ILOOS AS Indicator_InBulkLiquid_ILOOS, MARA.SERLV AS LevelOfExplicitnessForSerialNumber_SERLV, MARA.KZGVH AS PackagingMaterialIsClosedPackaging_KZGVH, MARA.XGCHP AS Indicator_ApprovedBatchRecordRequired_XGCHP, MARA.KZEFF AS AssignEffectivityParameterValuesOverrideChangeNumbers_KZEFF, MARA.COMPL AS MaterialCompletionLevel_COMPL, MARA.IPRKZ AS PeriodIndicatorForShelfLifeExpirationDate_IPRKZ, MARA.RDMHD AS RoundingRuleForCalculationOfSled_RDMHD, MARA.PRZUS AS Indicator_ProductCompositionPrintedOnPackaging_PRZUS, MARA.MTPOS_MARA AS GeneralItemCategoryGroup_MTPOS_MARA, MARA.BFLME AS GenericMaterialWithLogisticalVariants_BFLME, MARA.MATFI AS MaterialIsLocked_MATFI, MARA.CMREL AS RelevantForConfigurationManagement_CMREL, MARA.BBTYP AS AssortmentListType_BBTYP, MARA.SLED_BBD AS ExpirationDate_SLED_BBD, MARA.GTIN_VARIANT AS GlobalTradeItemNumberVariant_GTIN_VARIANT, MARA.GENNR AS MaterialNumberOfTheGenericMaterialInPrepackMaterials_GENNR, MARA.RMATP AS ReferenceMaterialForMaterialsPackedInSameWay_RMATP, MARA.GDS_RELEVANT AS Indicator_GlobalDataSynchronizationRelevant_GDS_RELEVANT, MARA.WEORA AS AcceptanceAtOrigin_WEORA, MARA.HUTYP_DFLT AS StandardHuType_HUTYP_DFLT, MARA.PILFERABLE AS Pilferable_PILFERABLE, MARA.WHSTC AS WarehouseStorageCondition_WHSTC, MARA.WHMATGR AS WarehouseMaterialGroup_WHMATGR, MARA.HNDLCODE AS HandlingIndicator_HNDLCODE, MARA.HAZMAT AS RelevantForHazardousSubstances_HAZMAT, MARA.HUTYP AS HandlingUnitType_HUTYP, MARA.TARE_VAR AS VariableTareWeight_TARE_VAR, MARA.MAXC AS MaximumAllowedCapacityOfPackagingMaterial_MAXC, MARA.MAXC_TOL AS OvercapacityToleranceOfTheHandlingUnit_MAXC_TOL, MARA.MAXL AS MaximumPackingLengthOfPackagingMaterial_MAXL, MARA.MAXB AS MaximumPackingWidthOfPackagingMaterial_MAXB, MARA.MAXH AS MaximumPackingHeightOfPackagingMaterial_MAXH, MARA.MAXDIM_UOM AS UnitOfMeasureForMaximumPackingLengthwidthheight_MAXDIM_UOM, MARA.HERKL AS CountryOfOriginOfMaterial_HERKL, MARA.MFRGR AS MaterialFreightGroup_MFRGR, MARA.QQTIME AS QuarantinePeriod_QQTIME, MARA.QQTIMEUOM AS TimeUnitForQuarantinePeriod_QQTIMEUOM, MARA.QGRP AS QualityInspectionGroup_QGRP, MARA.SERIAL AS SerialNumberProfile_SERIAL, MARA.PS_SMARTFORM AS FormName_PS_SMARTFORM, MARA.LOGUNIT AS EwmCw_LogisticsUnitOfMeasure_LOGUNIT, MARA.CWQREL AS EwmCw_MaterialIsACatchWeightMaterial_CWQREL, MARA.CWQPROC AS EwmCw_CatchWeightProfileForEnteringCwQuantity_CWQPROC, MARA.CWQTOLGR AS EwmCatchWeightToleranceGroupForEwm_CWQTOLGR, MARA.ADPROF AS AdjustmentProfile_ADPROF, MARA.IPMIPPRODUCT AS IdForAnIntellectualProperty_CrmProduct_IPMIPPRODUCT, MARA.ALLOW_PMAT_IGNO AS VariantPriceAllowed_ForMaterialMaster_ALLOW_PMAT_IGNO, MARA.MEDIUM AS Medium_MEDIUM, MARA.COMMODITY AS PhysicalCommodity_COMMODITY, --MARA.LVOMA AS FlagMaterialForDeletionAtClientLevel_LVORM, MARA.BRAND_ID AS Brand_BRAND_ID, MAKT.SPRAS AS Language_SPRAS, MAKT.MAKTX AS MaterialText_MAKTX FROM {{ project_id_src }}.{{ dataset_cdc_processed }}.mara AS MARA INNER JOIN {{ project_id_src }}.{{ dataset_cdc_processed }}.makt AS MAKT ON MARA.MANDT = MAKT.MANDT AND MARA.MATNR = MAKT.MATNR
package com.livinglifetechway.quickpermissions_plugin import com.android.build.gradle.AppPlugin import com.android.build.gradle.FeaturePlugin import com.android.build.gradle.InstantAppPlugin import com.android.build.gradle.LibraryPlugin import org.gradle.api.Plugin import org.gradle.api.Project class QuickPermissionsPlugin : Plugin<Project> { override fun apply(project: Project?) { // check for the android plugins // app, lib, feature, instant app // it should be one of the above project?.let { if (project.plugins.hasPlugin(AppPlugin::class.java) || project.plugins.hasPlugin(LibraryPlugin::class.java) || project.plugins.hasPlugin(FeaturePlugin::class.java) || project.plugins.hasPlugin(InstantAppPlugin::class.java)) { // register a transformer project.androidModule?.registerTransform(QuickPermissionsTransform(project)) // add necessary dependencies project.dependencies.add("implementation", "org.aspectj:aspectjrt:1.8.13") project.dependencies.add("api", "com.github.quickpermissions:quickpermissions-annotations:0.3.2") } else { // throw exception it doesn't work on any other module throw IllegalStateException("'com.android.application', 'com.android.library', " + "'com.android.feature' or 'com.android.instantapp' plugin required.") } } } }
import {Router, Request, Response, NextFunction} from 'express'; const router = Router() router.use((err: any, req: Request, res: Response, next: NextFunction) => { res.status(err.status || 500); res.json({ status: err.status || 500, message: process.env.NODE_ENV === 'development' ? err.message : '' }); }) export default router