Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
move.w #$0100,d0
clr.l d1
move.w #$0400,d4
clr.l d2
move.w #$1000,d3
NotReached:
addi.b #$10,d2
add.w d0,d1
cmp.w d1,d4
bgt.s NotReached
sub.w d2,d1
subi.w #$1000,d3
bpl.s NotReached
move.w d1,d0
swap d0
move.w d3,d0
sep #%00100000 ;8 bit accumulator
ldx #4 ;modifying 5 locations
;
loop lda $ab1234,x ;load
inc a ;increment
sta $ab1234,x ;store
dex
bpl loop ;next
phb ;save current data bank
sep #%00110000 ;8 bit registers
lda #$ab ;target bank
pha ;push it to the stack & pull it...
plb ;into DB, making it the default bank
ldx #4 ;modifying 5 locations
;
loop inc $1234,x ;effectively INC $AB1234,X
dex
bpl loop ;next
;
plb ;restore previous bank
sei ;IRQs off
wai ;wait for interrupt
lda via001 ;start of interrupt handler
#!/bin/bash
TARGET_DIR=("$@")
[ "x$1" == "x" ] && TARGET_DIR=(".")
function confirmDeletion() {
local confirm=""
until [ "x$confirm" == 'xy' ] || [ "x$confirm" == 'xn' ]
do
read -ep " Delete [y/n]: " confirm
confirm=$(echo "$confirm" | tr [:upper:] [:lower:])
done
[ "x$confirm" == 'xy' ]
}
function deleteWithConfirmation() {
for file in "${@}"
do
if rm "$file"; then
echo " OK: $file"
else
echo " FAIL: $file"
fi
done
}
for i in {'*~','a.out','*.o','*.gch','*nppdf32Log*'}
do
echo "Files matching: $i"
FILES=()
while read -rd '' file
do
FILES+=("$file")
echo " $file"
done < <(find "${TARGET_DIR[@]}" -depth -iname "$i" -print0)
if [ "x${FILES[*]}" != "x" ]; then
if confirmDeletion; then
deleteWithConfirmation "${FILES[@]}"
else
echo " Skipping"
fi
fi
done
Return the open file descriptor to the calling function via the eight bit accumulator by overwriting the appropriate register stack frame element:
sep #%00100000 ;select 8 bit accumulator
lda #0 ;clear...
xba ;.B
lda filedes ;get file descriptor, ...
rep #%00100000 ;select 16 bit accumulator &...
sta reg_a,s ;overwrite .C's stack copy
When the accumulator is pulled it will contain the value that was in filedes.
Flag an error by setting the carry bit in SR:
sep #%00100000 ;select 8 bit accumulator
lda reg_sr,s ;stack copy of SR
ora #%00000001 ;set carry bit &...
sta reg_sr,s ;rewrite
Flag a successful operation by clearing the carry bit in SR:
sep #%00100000 ;select 8 bit accumulator
lda reg_sr,s ;stack copy of SR
and #%11111110 ;clear carry bit &...
sta reg_sr,s ;rewrite
class PromptFormat:
botname = "Chatbort"
username = "User"
def __init__(self):
pass
#
def default_system_prompt(self):
raise NotImplementedError
def first_prompt(self):
raise NotImplementedError
def subs_prompt(self):
raise NotImplementedError
def stop_conditions(self, tokenizer):
raise NotImplementedError
def encoding_options(self): # (add_bos, add_eos, encode_special_tokens)
raise NotImplementedError
def print_bot_name(self):
return False
def print_extra_newline(self):
return False
class PromptFormat_raw(PromptFormat):
description = "Model-agnostic mode simulating a raw chatlog"
def __init__(self):
super().__init__()
pass
def default_system_prompt(self):
return \
f"""This is a conversation between a helpful AI assistant named {self.botname} and a """ + \
(f"""user named {self.username}.""" if self.username != "User" else """user.""")
def first_prompt(self):
return \
f"""<|system_prompt|>\n{self.username}: <|user_prompt|>\n{self.botname}:"""
def subs_prompt(self):
return \
f"""{self.username}: <|user_prompt|>\n{self.botname}:"""
def stop_conditions(self, tokenizer):
return \
[self.username + ":",
self.username[0:1] + ":",
self.username.upper() + ":",
self.username.lower() + ":",
tokenizer.eos_token_id]
def encoding_options(self):
return False, False, False
def print_bot_name(self):
return True
########################################################
class PromptFormat_llama(PromptFormat):
description = "Llama-chat, Llama2-chat and Mistral-instruct models"
def __init__(self):
super().__init__()
pass
def default_system_prompt(self):
return \
"""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. """ + \
"""Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. """ + \
"""Please ensure that your responses are socially unbiased and positive in nature."""
def first_prompt(self):
return \
"""[INST] <<SYS>>\n<|system_prompt|>\n<</SYS>>\n\n<|user_prompt|> [/INST]"""
def subs_prompt(self):
return \
"""[INST] <|user_prompt|> [/INST]"""
def stop_conditions(self, tokenizer):
return \
[tokenizer.eos_token_id]
def encoding_options(self):
return True, False, False
def print_extra_newline(self):
return True
def build_attn_mask(self, batch_size, seq_len, past_len, input_mask, device):
if input_mask is None and seq_len == 1: return None
if isinstance(past_len, tuple):
attn_masks = []
for i in range(len(past_len[1])):
attn_mask = torch.zeros((1, 1, seq_len, past_len[1][i] + seq_len), dtype = torch.float16, device = device)
attn_mask_triu = torch.triu(torch.full((seq_len - 1, seq_len - 1), -65504.))
attn_mask[:, :, : seq_len - 1, past_len[1][i] + 1: past_len[1][i] + seq_len] = attn_mask_triu
if input_mask is not None:
min_mask_width = min(input_mask[i].shape[-1], seq_len + past_len[1][i])
input_mask_part = safe_move_tensor(input_mask[i][:, :min_mask_width], attn_mask.device)
input_mask_part = input_mask_part.unsqueeze(1).unsqueeze(2)
attn_mask[:, :, :, :min_mask_width] = torch.minimum(attn_mask[:, :, :, :min_mask_width], input_mask_part)
attn_masks.append(attn_mask)
return attn_masks
else:
attn_mask = torch.zeros((batch_size, 1, seq_len, past_len + seq_len), dtype = torch.float16, device = device)
attn_mask_triu = torch.triu(torch.full((seq_len - 1, seq_len - 1), -65504.))
attn_mask[:, :, : seq_len - 1, past_len + 1: past_len + seq_len] = attn_mask_triu
if input_mask is not None:
min_mask_width = min(input_mask.shape[-1], seq_len + past_len)
input_mask_part = safe_move_tensor(input_mask[:, :min_mask_width], attn_mask.device)
input_mask_part = input_mask_part.unsqueeze(1).unsqueeze(2)
attn_mask[:, :, :, :min_mask_width] = torch.minimum(attn_mask[:, :, :, :min_mask_width], input_mask_part)
return attn_mask
We have to develop a Java program to calculate the sum of n natural numbers. Sum of natural number N as given as sum = 1+2+3+….+N
Examples:-
1+2+3+4+5 = 15
1+2+3+4+5+6+7+8+9+10 = 55
Procedure to develop a method to find the sum of N natural numbers in Java,
Take the N value.
Declare an iterator variable and initialize it with 1 because natural numbers start with 1.
Add iterator variable value into the sum variable
Increase the value of the iterator variable by 1
Repeat 3 and 4 steps until the number remains greater than the iterator variable
The time complexity of this procedure is O(n).
import java.util.Scanner;
public class NaturalNumberSum {
// method to find sum of N natural numbers
public static int naturalNumberSum(int number){
int i = 1; // iterator variable
// variable to store sum value
int sum = 0;
// loop to repeat the process
while (i<=number) {
// add into sum value
sum = sum + i;
// increase iterator variable
i++;
}
// return sum value
return sum;
}
public static void main(String[] args) {
// declare variables
int number = 0;
int sum = 0;
// create Scanner class object
Scanner scan = new Scanner(System.in);
// read input
System.out.print("Enter N value:: ");
number = scan.nextInt();
// Calculate the sum value
sum = naturalNumberSum(number);
// display result
System.out.println("Sum = "+sum);
// close Scanner class objects
scan.close();
}
}
The output for different test-cases:-
Enter N value:: 5
Sum = 15
Enter N value:: 10
Sum = 55
In this program, we have used a while loop to find the sum of natural numbers in Java. While loop is a pre-test loop where the expression is evaluated then only statements are executed. It uses a test expression to control the loop. Before every iteration of the loop, the test expression is evaluated.
Also See:-
Sum of digits of a number
The sum of even digits in a number
Sum of odd digits in a number
Sum of first & last digit of a number
The Sum of Digits Until Single Digit
We can also use for loop instead of using a while loop. The for loop is also a pre-test loop, where first of all initialization expression is evaluated then the condition is checked and if the condition is true then only the statements of the for loop are executed.
public static int naturalNumberSum(int number){
int sum = 0;
for(int i=1; i<=number; i++)
sum+=i;
return sum;
}
Or,
public static int naturalNumberSum(int number){
int sum = 0;
for(int i=1; ; sum+=i, i++)
if(i>number) return sum;
}
The time complexity of all above methods are O(n).
Sum of Natural Numbers in Java without using the loop
We can also do the same work without using the loop. The formula for this operation,
Sum = n * (n+1) / 2;
Example:-
Sum of first 10 natural numbers = 10*(10+1)/2 = 10*11/2 = 5*11 = 55
It is the best way to find the sum of natural numbers. The time complexity of this method is O(1).
import java.util.Scanner;
public class NaturalNumberSum {
// method to find sum of N natural numbers
public static int naturalNumberSum(int number){
return number*(number+1)/2;
}
public static void main(String[] args) {
// declare variables
int number = 0;
int sum = 0;
// create Scanner class object
Scanner scan = new Scanner(System.in);
// read input
System.out.print("Enter N value:: ");
number = scan.nextInt();
// Calculate the sum value
sum = naturalNumberSum(number);
// display result
System.out.println("Sum = "+sum);
// close Scanner class objects
scan.close();
}
}
Using recursion
We already developed java program to find the sum of the natural number using for loop, or while loop, or without using the loop. Now we will find the same using the recursion technique. In Recursion, We divided the big problems into smaller problems or sub-problems.
Sum of N natural numbers given as 1+2+….+(n-1)+n. So, the problem can be divided as n + ( (n-1) +… + 2 + 1 )
General case for finding the sum of natural number => sum(n) = n + sum(n-1); Similarly, the base case for finding the sum of natural number => sum(0) = 0; or sum(1) = 1;
import
module jtransmissiongatetb;
wire y;
reg a,control;
jtransmissiongate jtgate(y,control,a);
initial
begin
$display ("RESULT\ta\ty");
a = 0; control = 0; # 50; // Initial value is set
if ( y === 1'bz ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
a = 0; control = 1; # 50; // Initial value is set
if ( y === 0 ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
a = 1; control = 0; # 50; // Another value
if ( y === 1'bz ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
a = 1; control = 1; # 50; // Another value
if ( y === 1 ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
end
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
endmodule
module jtransmissiongate(y,control,a);
output y;
input a,control;
wire cbar;
assign cbar = ~control;
nmos n1(y,a,control);
pmos p1(y,a,cbar);
//cmos c1(y,a,control,cbar);
endmodule
module juniversalShiftRegisterTb;
wire [3:0] DATAOUT;
reg clock, reset;
reg [1:0] MODE;
reg [3:0] DATAIN;
juniversalShiftRegister jusr(DATAOUT, clock, reset, MODE, DATAIN);
initial
begin
clock =0; MODE = 2'b00; DATAIN = 4'b0000;
reset = 1; #10; reset = 0; #10;
$display("RSLT\tD == DOUT");
// Start testing Right Shift mode
MODE = 2'b00; reset = 1; #10; reset = 0; #10;
MODE = 2'b01; DATAIN = 4'b0011; #10;
if ( DATAOUT === 4'b1000 ) // look at previous value of DATAOUT as well
$display("PASS\t%p is %p with %p", DATAIN, MODE, DATAOUT);
else
$display("FAIL\t%p is %p with %p", DATAIN, MODE, DATAOUT);
MODE = 2'b01; DATAIN = 4'b0011; #10;
if ( DATAOUT === 4'b1100 ) // look at previous value of DATAOUT as well
$display("PASS\t%p is %p with %p", DATAIN, MODE, DATAOUT);
else
$display("FAIL\t%p is %p with %p", DATAIN, MODE, DATAOUT);
// Start testing Left Shift mode
MODE = 2'b00; reset = 1; #10; reset = 0; #10;
MODE = 2'b10; DATAIN = 4'b0111; #10;
if ( DATAOUT === 4'b0001 ) //
$display("PASS\t%p is %p with %p", DATAIN, MODE, DATAOUT);
else
$display("FAIL\t%p is %p with %p", DATAIN, MODE, DATAOUT);
MODE = 2'b10; DATAIN = 4'b0111; #10;
if ( DATAOUT === 4'b0011 ) //
$display("PASS\t%p is %p with %p", DATAIN, MODE, DATAOUT);
else
$display("FAIL\t%p is %p with %p", DATAIN, MODE, DATAOUT);
// Start testing parallel load mode
MODE = 2'b00; reset = 1; #10; reset = 0; #10;
MODE = 2'b11; DATAIN = 4'b1010; #10;
if ( DATAOUT === 4'b1010 )
$display("PASS\t%p is %p with %p", DATAIN, MODE, DATAOUT);
else
$display("FAIL\t%p is %p with %p", DATAIN, MODE, DATAOUT);
#20;
$finish;
end
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
always #5 clock = ~clock;
endmodule
#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'
# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'
#use $@ to print out all arguments at once
echo $@ ' -> echo $@'
# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'
Let’s try executing this script and providing three arguments.
$ ./arguments.sh Bash Scripting Tutorial
The results when we execute this script:
Bash Scripting Tutorial -> echo $1 $2 $3
Bash Scripting Tutorial -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}
Bash Scripting Tutorial -> echo $@
Number of arguments passed: 3 -> echo Number of arguments passed: $#
Executing shell commands with bash
The best way to execute a separate shell command inside of a Bash script is by creating a new subshell through the $( ) syntax. Check the example below where we echo the result of running the uname -o command.
#!/bin/bash
# use a subshell $() to execute shell command
echo $(uname -o)
# executing bash command without subshell
echo uname -o
Notice that in the final line of our script, we do not execute the uname command within a subshell, therefore the text is taken literally and output as such.
$ uname -o
GNU/LINUX
$ ./subshell.sh
GNU/LINUX
uname -o
Reading User Input
We can use the read command to read input from the user. This allows a user to interact with a Bash script and help dictate the way it proceeds. Here’s an example:
#!/bin/bash
echo -e "Hi, please type the word: \c "
read word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
Our Bash script asks multiple questions and then is able to repeat the information back to us through variables and arrays:
$ ./read.sh
Hi, please type the word: Linuxconfig.org
The word you entered is: Linuxconfig.org
Can you please enter two words?
Debian Linux
Here is your input: "Debian" "Linux"
How do you feel about bash scripting?
good
You said good, I'm glad to hear that!
What are your favorite colours ?
blue green black
My favorite colours are also blue, green and black:-)
Bash Trap Command
The trap command can be used in Bash scripts to catch signals sent to the script and then execute a subroutine when they occur. The script below will detect a Ctrl + C interrupt.
#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
echo "$a/10 to Exit."
sleep 1;
done
echo "Exit Bash Trap Example!!!"
In the output below you can see that we try to Ctrl + C two times but the script continues to execute.
$ ./trap.sh
1/10 to Exit.
2/10 to Exit.
^CCTRL+C Detected !...executing bash trap !
3/10 to Exit.
4/10 to Exit.
5/10 to Exit.
6/10 to Exit.
7/10 to Exit.
^CCTRL+C Detected !...executing bash trap !
8/10 to Exit.
9/10 to Exit.
10/10 to Exit.
Exit Bash Trap Example!!!
Arrays
Bash is capable of storing values in arrays. Check the sections below for two different examples.
Declare simple bash array
This example declares an array with four elements.
#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}
# echo each element in array
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
echo ${ARRAY[${i}]}
done
Executing the script will output the elements of our array:
$ ./arrays.sh
Debian Linux
Redhat Linux
Ubuntu
Linux
Read file into bash array
Rather than filling out all of the elements of our array in the Bash script itself, we can program our script to read input and put it into an array.
#!/bin/bash
# Declare array
declare -a ARRAY
# Link filedescriptor 10 with stdin
exec 10<&0
# stdin replaced with a file supplied as a first argument
exec < $1
let count=0
while read LINE; do
ARRAY[$count]=$LINE
((count++))
done
echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-
Now let’s execute the script and store four elements in the array by using a file’s contents for input.
$ cat bash.txt
Bash
Scripting
Tutorial
Guide
$ ./bash-script.sh bash.txt
Number of elements: 4
Bash Scripting Tutorial Guide
*** CompressADPCM3 ***
; JoinCode = CompressADPCM3(Source, Length, Destination, JoinCode)
; d0 a0 d0 a1 d1
;
; This function compresses a RAW sample to a given memory. The
; result is a 3bit ADPCM code. The destination buffer must be
; at least (Length+7)/8*3 bytes in size.
;
; Function of the JoinCode: See above.
XDEF _CompressADPCM3
_CompressADPCM3
movem.l d2-d4,-(sp)
move.w d1,d3 ; d3=EstMax
swap d1
move.w d1,d2 ; d2=Delta
bne.s c3_loop
moveq #5,d2
c3_loop moveq #0,d1 ; d1=Shifter
bsr.s c3_byte
lsl.b #3,d1
bsr.s c3_byte
lsl.w #3,d1
bsr.s c3_byte
lsl.w #3,d1
bsr.s c3_byte
lsl.w #3,d1
bsr.s c3_byte
lsl.l #3,d1
bsr.s c3_byte
lsl.l #3,d1
bsr.s c3_byte
lsl.l #3,d1
bsr.s c3_byte
swap d1
move.b d1,(a1)+
rol.l #8,d1
move.b d1,(a1)+
rol.l #8,d1
move.b d1,(a1)+
subq.l #8,d0 ; d0=Counter
bhi.s c3_loop
move.w d2,d0 ; -> d0=JoinCode
swap d0
move.w d3,d0
movem.l (sp)+,d2-d4
rts
c3_byte move.b (a0)+,d4
ext.w d4
asl.w #6,d4
sub.w d3,d4
bpl.s c3_positive
or.b #%100,d1
neg.w d4
c3_positive sub.w d2,d4
bls.s c3_00
sub.w d2,d4
bls.s c3_01
sub.w d2,d4
bls.s c3_10
c3_11 or.b #%11,d1
bra.s c3_00
c3_10 or.b #%10,d1
bra.s c3_00
c3_01 or.b #%01,d1
c3_00 bsr.s adaptive
rts
*** Adaptions-Routine ***
adaptive ; d1 = SignBit + DataBit
move.w d2,d4
lsr.w #1,d4
btst #1,d1
beq.s d3_0
d3_1 btst #0,d1
beq.s d3_10
d3_11 add.w d2,d4
add.w d2,d4
add.w d2,d4
mulu #$6607,d2
bra.s d3_sign
d3_10 add.w d2,d4
add.w d2,d4
mulu #$4D14,d2
bra.s d3_sign
d3_0 btst #0,d1
beq.s d3_00
d3_01 add.w d2,d4
mulu #$3A9F,d2
bra.s d3_sign
d3_00 mulu #$399A,d2
d3_sign btst #2,d1
beq.s d3_add
neg.w d4
d3_add add.w d4,d3
add.l #8192,d2
moveq #14,d4
asr.l d4,d2
rts
END
mov
mov bp, 255
traceloop:
; Evaluate whether sample point is inside or outside the shape:
;
; ( a & ( b | c ) ) | ( b & c ) = 0 <=> voxel overlaps fractal
push bx
mov dx, bx
or dx, cx
and dx, ax
and bx, cx
or dx, bx
pop bx
; Ignore the lower bits or the fractal will be too fine to see
shr dx, 6
jz endtrace
dec bp
jnz traceloop
endtrace:
; BP is 255 - the distance we had to trace
mov dx, bp
not dl
; Plot pixel
mov ds:[di],dl
inc di
// ******************
#include <torch/extension.h>
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda_runtime.h>module jtransmissiongatetb;
wire y;
reg a,control;
jtransmissiongate jtgate(y,control,a);
initial
begin
$display ("RESULT\ta\ty");
a = 0; control = 0; # 50; // Initial value is set
if ( y === 1'bz ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
a = 0; control = 1; # 50; // Initial value is set
if ( y === 0 ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
a = 1; control = 0; # 50; // Another value
if ( y === 1'bz ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
control = 1; # 50; // Simply change the control signal
control = 0; # 50; // Simply change the control signal
a = 1; control = 1; # 50; // Another value
if ( y === 1 ) // Test for inversion
$display ("PASS \t%d\t%d",a,y);
else
$display ("FAIL \t%d\t%d",a,y);
end
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
endmodule
#include <cuda_fp16.h>
#include <cstdint>
#include <cstdio>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "config.h"
#include "cuda/pack_tensor.cuh"
#include "cuda/quantize.cuh"
#include "cuda/q_matrix.cuh"
#include "cuda/q_attn.cuh"
#include "cuda/q_mlp.cuh"
#include "cuda/q_gemm.cuh"
#include "cuda/rms_norm.cuh"
#include "cuda/rope.cuh"
#include "cuda/cache.cuh"
#include "cuda/h_gemm.cuh"
#include "cpp/quantize_func.h"
#include "cpp/sampling.h"
#include "cpp/util.h"
// Some decluttering macros
#define TORCH_CHECK_DTYPE(__x, __dtype) TORCH_CHECK((__x).dtype() == torch::__dtype, #__x " is incorrect datatype, must be " #__dtype)
#define TORCH_CHECK_DTYPE_OPT(__x, __dtype) TORCH_CHECK((__x).device().is_meta() || (__x).dtype() == torch::__dtype, #__x " is incorrect datatype, must be " #__dtype)
#define TORCH_CHECK_SHAPES(__x, __dim_x, __y, __dim_y, __scale_y) TORCH_CHECK((__x).size(__dim_x) == (__y).size(__dim_y) * __scale_y, #__x " and " #__y " have incompatible shapes")
#define TORCH_CHECK_SHAPES_OPT(__x, __dim_x, __y, __dim_y, __scale_y) TORCH_CHECK((__x).device().is_meta() || (__x).size(__dim_x) == (__y).size(__dim_y) * __scale_y, #__x " and " #__y " have incompatible shapes")
// Packing functions
void pack_rows_4
(
torch::Tensor input,
torch::Tensor output
)
{
const at::cuda::OptionalCUDAGuard device_guard(device_of(input));
TORCH_CHECK_DTYPE(input, kShort);
TORCH_CHECK_DTYPE(output, kInt);
TORCH_CHECK_SHAPES(input, 0, output, 0, 1);
TORCH_CHECK_SHAPES(input, 1, output, 1, 8);
int rows = input.size(0);
int columns = input.size(1);
pack_rows_4_cuda
(
(uint16_t*) input.data_ptr(),
(uint32_t*) output.data_ptr(),
rows,
columns
);
}
void pack_columns
(
torch::Tensor input,
torch::Tensor output,
int bits
)
{
const at::cuda::OptionalCUDAGuard device_guard(device_of(input));
TORCH_CHECK_DTYPE(input, kShort);
TORCH_CHECK_DTYPE(output, kInt);
TORCH_CHECK_SHAPES(input, 1, output, 1, 1);
int in_rows = input.size(0);
int columns = input.size(1);
int out_rows = output.size(0);
int exp_out_rows = in_rows * bits / 32;
TORCH_CHECK(out_rows == exp_out_rows, "Wrong output shape for input and bitrate")
pack_columns_cuda
(
(uint16_t*) input.data_ptr(),
(uint32_t*) output.data_ptr(),
in_rows,
out_rows,
columns,
bits
);
}
#include "quantize_func.h"
#include "../cuda/quantize.cuh"
void quantize_range
(
torch::Tensor quant,
torch::Tensor scale,
torch::Tensor out_q,
float qzero,
float maxq,
torch::Tensor hessian_inv,
torch::Tensor weights,
torch::Tensor error,
int a,
int b
)
{
int columns = weights.size(1);
int hcolumns = hessian_inv.size(1);
for (int c = a; c < b; c++)
{
quantize_cuda
(
((const float*) weights.data_ptr()) + c * columns,
((float*) quant.data_ptr()) + c * columns,
(const float*) scale.data_ptr(),
out_q.device().is_meta() ? NULL : ((uint16_t*) out_q.data_ptr()) + c * columns,
1,
columns,
qzero,
maxq
);
adjust_error_row_cuda
(
(const float*) hessian_inv.data_ptr(),
(float*) error.data_ptr(),
(const float*) weights.data_ptr(),
(const float*) quant.data_ptr(),
c,
columns,
hcolumns
);
vv_mul_sub_cuda
(
((const float*) hessian_inv.data_ptr()) + c * hcolumns + c,
((const float*) error.data_ptr()) + c * columns,
((float*) weights.data_ptr()) + c * columns,
b - c,
columns
);
}
torch::Tensor x = hessian_inv.slice(0, a, b).slice(1, b).transpose(0, 1);
torch::Tensor y = error.slice(0, a, b);
weights.slice(0, b).addmm_(x, y, 1.0f, -1.0f);
}
//---------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
__forceinline__ __device__ half dot22_8_h(half2(&dq)[4], const half* a_ptr, const half g_result, const half qs_h)
{
half2 result = {};
const half2* a2_ptr = (const half2*)a_ptr;
#pragma unroll
for (int i = 0; i < 4; i++) result = __hfma2(dq[i], *a2_ptr++, result);
half result_h = __hadd(__low2half(result), __high2half(result));
return __hfma(result_h, qs_h, g_result);
}
__forceinline__ __device__ half dot22_16_h(half2(&dq)[8], const half* a_ptr, const half g_result, const half qs_h)
{
half2 result = {};
const half2* a2_ptr = (const half2*)a_ptr;
#pragma unroll
for (int i = 0; i < 8; i++) result = __hfma2(dq[i], *a2_ptr++, result);
half result_h = __hadd(__low2half(result), __high2half(result));
return __hfma(result_h, qs_h, g_result);
}
__forceinline__ __device__ half dot22_32_h(half2(&dq)[16], const half* a_ptr, const half g_result, const half qs_h)
{
half2 result = {};
const half2* a2_ptr = (const half2*)a_ptr;
#pragma unroll
for (int i = 0; i < 16; i += 1) result = __hfma2(dq[i], *a2_ptr++, result);
half result_h = __hadd(__low2half(result), __high2half(result));
return __hfma(result_h, qs_h, g_result);
}
name: Build Wheels
on: workflow_dispatch
jobs:
build_wheels:
name: ${{ matrix.os }} Python ${{ matrix.pyver }} CUDA ${{ matrix.cuda }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-20.04, windows-latest]
pyver: ["3.8", "3.9", "3.10", "3.11"]
cuda: ["11.7.0", "11.8.0", "12.1.1"]
defaults:
run:
shell: pwsh
env:
CUDAVER: ${{ matrix.cuda }}
PYVER: ${{ matrix.pyver }}
steps:
- name: Free Disk Space
uses: jlumbroso/[email protected]
if: runner.os == 'Linux'
with:
tool-cache: false
android: true
dotnet: true
haskell: true
large-packages: false
swap-storage: false
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
with:
python-version: ${{ matrix.pyver }}
- name: Setup Mamba
uses: conda-incubator/[email protected]
with:
activate-environment: "build"
python-version: ${{ matrix.pyver }}
miniforge-variant: Mambaforge
miniforge-version: latest
use-mamba: true
add-pip-as-python-dependency: true
auto-activate-base: false
- name: Install Dependencies
run: |
$cudaVersion = $env:CUDAVER
$cudaVersionPytorch = $env:CUDAVER.Remove($env:CUDAVER.LastIndexOf('.')).Replace('.','')
$cudaChannels = ''
$cudaNum = [int]$cudaVersion.substring($cudaVersion.LastIndexOf('.')+1)
while ($cudaNum -ge 0) { $cudaChannels += '-c nvidia/label/cuda-' + $cudaVersion.Remove($cudaVersion.LastIndexOf('.')+1) + $cudaNum + ' '; $cudaNum-- }
mamba install -y 'cuda' $cudaChannels.TrimEnd().Split()
if (!(mamba list cuda)[-1].contains('cuda')) {sleep -s 10; mamba install -y 'cuda' $cudaChannels.TrimEnd().Split()}
if (!(mamba list cuda)[-1].contains('cuda')) {throw 'CUDA Toolkit failed to install!'}
if ([version]$env:CUDAVER -lt [version]'11.8.0') {$torchver = "torch==2.0.1"} else {$torchver = "torch==2.1.0"}
python -m pip install $torchver --index-url https://download.pytorch.org/whl/cu$cudaVersionPytorch
python -m pip install build wheel safetensors sentencepiece ninja
- name: Build Wheel
run: |
$env:CUDA_PATH = $env:CONDA_PREFIX
$env:CUDA_HOME = $env:CONDA_PREFIX
$cudaVersion = $env:CUDAVER
$cudaVersionPytorch = $env:CUDAVER.Remove($env:CUDAVER.LastIndexOf('.')).Replace('.','')
$BUILDTAG = "+cu$cudaVersionPytorch"
if ($IsLinux) {$env:LD_LIBRARY_PATH = $env:CONDA_PREFIX + '/lib:' + $env:LD_LIBRARY_PATH}
$env:TORCH_CUDA_ARCH_LIST = if ([version]$env:CUDAVER -lt [version]'11.8') {'6.0 6.1 7.0 7.5 8.0 8.6+PTX'} else {'6.0 6.1 7.0 7.5 8.0 8.6 8.9 9.0+PTX'}
python -m build -n --wheel -C--build-option=egg_info "-C--build-option=--tag-build=$BUILDTAG"
if ($IsLinux -and $env:PYVER -eq '3.11' -and $env:CUDAVER -eq '11.8.0') {$env:EXLLAMA_NOCOMPILE=1; python -m build -n}
- uses: actions/upload-artifact@v3
with:
name: 'wheels'
path: ./dist/*
build_rocm:
name: Build ROCm Wheels & Release
needs: build_wheels
uses: ./.github/workflows/build-wheels-rocm.yml
Metadata-Version: 2.1
Name: exllamav2
Version: 0.0.10
Home-page: https://github.com/turboderp/exllamav2
Author: turboderp
License: MIT
License-File: LICENSE
Requires-Dist: pandas
Requires-Dist: ninja
Requires-Dist: fastparquet
Requires-Dist: torch>=2.0.1
Requires-Dist: safetensors>=0.3.2
Requires-Dist: sentencepiece>=0.1.97
Requires-Dist: pygments
Requires-Dist: websockets
Requires-Dist: regex
# ExLlamaV2
ExLlamaV2 is an inference library for running local LLMs on modern consumer GPUs.
## Overview of differences compared to V1
- Faster, better kernels
- Cleaner and more versatile codebase
- Support for a new quant format (see below)
## Performance
Some quick tests to compare performance with V1. There may be more performance optimizations in the future, and
speeds will vary across GPUs, with slow CPUs still being a potential bottleneck:
| Model | Mode | Size | grpsz | act | V1: 3090Ti | V1: 4090 | V2: 3090Ti | V2: 4090 |
|------------|--------------|-------|-------|-----|------------|----------|------------|-------------|
| Llama | GPTQ | 7B | 128 | no | 143 t/s | 173 t/s | 175 t/s | **195** t/s |
| Llama | GPTQ | 13B | 128 | no | 84 t/s | 102 t/s | 105 t/s | **110** t/s |
| Llama | GPTQ | 33B | 128 | yes | 37 t/s | 45 t/s | 45 t/s | **48** t/s |
| OpenLlama | GPTQ | 3B | 128 | yes | 194 t/s | 226 t/s | 295 t/s | **321** t/s |
| CodeLlama | EXL2 4.0 bpw | 34B | - | - | - | - | 42 t/s | **48** t/s |
| Llama2 | EXL2 3.0 bpw | 7B | - | - | - | - | 195 t/s | **224** t/s |
| Llama2 | EXL2 4.0 bpw | 7B | - | - | - | - | 164 t/s | **197** t/s |
| Llama2 | EXL2 5.0 bpw | 7B | - | - | - | - | 144 t/s | **160** t/s |
| Llama2 | EXL2 2.5 bpw | 70B | - | - | - | - | 30 t/s | **35** t/s |
| TinyLlama | EXL2 3.0 bpw | 1.1B | - | - | - | - | 536 t/s | **635** t/s |
| TinyLlama | EXL2 4.0 bpw | 1.1B | - | - | - | - | 509 t/s | **590** t/s |
## How to
Clone the repository and install dependencies:
```
git clone https://github.com/turboderp/exllamav2
cd exllamav2
pip install -r requirements.txt
python test_inference.py -m <path_to_model> -p "Once upon a time,"
```
A simple console chatbot is included. Run it with:
```
python examples/chat.py -m <path_to_model> -mode llama
```
The `-mode` argument chooses the prompt format to use. `llama` is for the Llama(2)-chat finetunes, while `codellama`
probably works better for CodeLlama-instruct. `raw` will produce a simple chatlog-style chat that works with base
models and various other finetunes. You can also provide a custom system prompt with `-sp`.
## Integration and APIs
- [TabbyAPI](https://github.com/theroyallab/tabbyAPI/) is a FastAPI-based server that provides an OpenAI-style web API
compatible with [SillyTavern](https://sillytavernai.com/) and other frontends.
- [ExUI](https://github.com/turboderp/exui) is a simple, standalone single-user web UI that serves an ExLlamaV2 instance
directly with chat and notebook modes.
- [text-generation-webui](https://github.com/oobabooga/text-generation-webui) supports ExLlamaV2 through the **exllamav2**
and **exllamav2_HF** loaders.
## Installation
### Method 1: Install from source
To install the current dev version, clone the repo and run the setup script:
```
git clone https://github.com/turboderp/exllamav2
cd exllamav2
python setup.py install --user
```
By default this will also compile and install the Torch C++ extension (`exllamav2_ext`) that the library relies on.
You can skip this step by setting the `EXLLAMA_NOCOMPILE` environment variable:
```
EXLLAMA_NOCOMPILE= python setup.py install --user
```
This will install the "JIT version" of the package, i.e. it will install the Python components without building the
C++ extension in the process. Instead, the extension will be built the first time the library is used, then cached in
`~/.cache/torch_extensions` for subsequent use.
### Method 2: Install from release (with prebuilt extension)
Releases are available [here](https://github.com/turboderp/exllamav2/releases), with prebuilt wheels that contain the
extension binaries. Make sure to grab the right version, matching your platform, Python version (`cp`) and CUDA version.
Download an appropriate wheel, then run:
```
pip install exllamav2-0.0.4+cu118-cp310-cp310-linux_x86_64.whl
```
The `py3-none-any.whl` version is the JIT version which will build the extension on first launch. The `.tar.gz` file
can also be installed this way, and it will build the extension while installing.
### Method 3: Install from PyPI
A PyPI package is available as well. It can be installed with:
```
pip install exllamav2
```
The version available through PyPI is the JIT version (see above). Still working on a solution for distributing
prebuilt wheels via PyPI.
## EXL2 quantization
ExLlamaV2 supports the same 4-bit GPTQ models as V1, but also a new "EXL2" format. EXL2 is based on the same
optimization method as GPTQ and supports 2, 3, 4, 5, 6 and 8-bit quantization. The format allows for mixing quantization
levels within a model to achieve any average bitrate between 2 and 8 bits per weight.
Moreover, it's possible to apply multiple quantization levels to each linear layer, producing something akin to sparse
quantization wherein more important weights (columns) are quantized with more bits. The same remapping trick that lets
ExLlama work efficiently with act-order models allows this mixing of formats to happen with little to no impact on
performance.
Parameter selection is done automatically by quantizing each matrix multiple times, measuring the quantization
error (with respect to the chosen calibration data) for each of a number of possible settings, per layer. Finally, a
combination is chosen that minimizes the maximum quantization error over the entire model while meeting a target
average bitrate.
In my tests, this scheme allows Llama2 70B to run on a single 24 GB GPU with a 2048-token context, producing coherent
and mostly stable output with 2.55 bits per weight. 13B models run at 2.65 bits within 8 GB of VRAM, although currently
none of them uses GQA which effectively limits the context size to 2048. In either case it's unlikely that the model
will fit alongside a desktop environment. For now.
[](doc/llama2_70b_chat.png)
[](doc/codellama_13b_instruct.png)
### Conversion
A script is provided to quantize models. Converting large models can be somewhat slow, so be warned. The conversion
script and its options are explained in [detail here](doc/convert.md)
### HuggingFace repos
- I've uploaded a few EXL2-quantized models to Hugging Face to play around with, [here](https://huggingface.co/turboderp).
- [LoneStriker](https://huggingface.co/LoneStriker) provides a large number of EXL2 models on Hugging Face.
// The macro below is used to shift rows of the A matrix and columns of the B matrix
// in shared memory to minimize possible bank conflicts.
// Before performing the nvcuda::wmma::mma_sync operation, the warp must load the matrix
// data using the nvcuda::wmma::load_matrix_sync operation. Although the memory access pattern
// is not specified for that function, each lane in the warp can read one or multiple matrix
// elements from different matrix rows or columns.
// For shared memory, such access can result in bank conflicts if different rows / columns
// of the matrix map to the same bank. By shifting each row and column by a few bytes, we
// make sure that they map to different banks, thus reducing the number of possible bank
// conflicts.
// The number of 16 two-byte "__nv_bfloat16" elements is chosen as the minimum possible shift because
// we must keep each row and column 256-bit aligned, as required by nvcuda::wmma::load_matrix_sync.
// #define SKEW_BF16 16
//
#define checkKernelErrors(expr) do { \
expr; \
\
cudaError_t __err = cudaGetLastError(); \
if (__err != cudaSuccess) { \
printf("Line %d: '%s' failed: %s\n", __LINE__, # expr, cudaGetErrorString(__err)); \
abort(); \
} \
} while(0)
DO ,1 <- #13
PLEASE DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
DO ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64
DO ,1 SUB #6 <- #194
PLEASE DO ,1 SUB #7 <- #48
DO ,1 SUB #8 <- #26
DO ,1 SUB #9 <- #244
PLEASE DO ,1 SUB #10 <- #168
DO ,1 SUB #11 <- #24
DO ,1 SUB #12 <- #16
DO ,1 SUB #13 <- #162
PLEASE READ OUT ,1
PLEASE GIVE UP
DO .9 <- #16
DO .10 <- #0
DO .11 <- #1
(1) PLEASE READ OUT .11
DO .1 <- .10
DO .2 <- .11
PLEASE (1009) NEXT
DO .10 <- .11
DO .11 <- .3
DO (3) NEXT
DO (1) NEXT
(3) DO (4) NEXT
PLEASE GIVE UP
(4) DO .1 <- .9
DO .2 <- #1
PLEASE (1010) NEXT
DO .9 <- .3
DO .1 <- '.9~.9'~#1
PLEASE (1020) NEXT
DO RESUME .1
__global__ void testPtx(int *devBuff,float *devDummy,unsigned int *timeBuff){
unsigned int temp=0;
unsigned int start,end;
volatile unsigned int *tempPtr;
tempPtr = (volatile unsigned int *)&devBuff[0];
start = clock64();
temp=*tempPtr;
__threadfence();
end = clock64();
*devDummy=(float)(1.0/(float)(temp));
*timeBuff = (unsigned int)(end-start);
}
<% Option Explicit %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>VBScript Example</title>
</head>
<body>
<div><%
' Grab current time from Now() function.
' An '=' sign occurring after a context switch (<%) is shorthand
' for a call to the Write() method of the Response object.
Dim timeValue : timeValue = Now %>
The time, in 24-hour format, is
<%=Hour(timeValue)%>:<%=Minute(timeValue)%>:<%=Second(timeValue)%>.
</div>
</body>
</html>
using System;
namespace interptest
{
class MainClass
{
static UInt16[] pwmTable =
{
0,
1,
15,
53,
127,
249,
431,
685,
1023,
1457,
1999,
2661,
3455,
4393,
5487,
6749,
8191,
9825,
11663,
13717,
15999,
18521,
21295,
24333,
27647,
31249,
35151,
39365,
43903,
48777,
53999,
59581,
65535
};
static UInt16 intToPWM(UInt16 intensity)
{
UInt32 index = ((UInt32)intensity) >> 11;
UInt32 low = ((UInt32)pwmTable[index]);
UInt32 high = ((UInt32)pwmTable[index + 1]);
UInt32 highp = ((UInt32)intensity & 0x7ff) + 1;
UInt32 lowp = 0x800 - highp;
UInt32 mid = (lowp * low + highp * high) >> 11;
return (UInt16)mid;
}
public static void Main(string[] args)
{
for (UInt32 i = 0; i < 65536; i++)
{
UInt16 t = intToPWM((UInt16)i);
Console.WriteLine(t);
}
}
}
}
// Suppress all warnings from casts which overflow.
#![allow(overflowing_literals)]
fn main() {
let decimal = 65.4321_f32;
// Error! No implicit conversion
let integer: u8 = decimal;
// FIXME ^ Comment out this line
// Explicit conversion
let integer = decimal as u8;
let character = integer as char;
// Error! There are limitations in conversion rules.
// A float cannot be directly converted to a char.
let character = decimal as char;
// FIXME ^ Comment out this line
println!("Casting: {} -> {} -> {}", decimal, integer, character);
// when casting any value to an unsigned type, T,
// T::MAX + 1 is added or subtracted until the value
// fits into the new type
// 1000 already fits in a u16
println!("1000 as a u16 is: {}", 1000 as u16);
// 1000 - 256 - 256 - 256 = 232
// Under the hood, the first 8 least significant bits (LSB) are kept,
// while the rest towards the most significant bit (MSB) get truncated.
println!("1000 as a u8 is : {}", 1000 as u8);
// -1 + 256 = 255
println!(" -1 as a u8 is : {}", (-1i8) as u8);
// For positive numbers, this is the same as the modulus
println!("1000 mod 256 is : {}", 1000 % 256);
// When casting to a signed type, the (bitwise) result is the same as
// first casting to the corresponding unsigned type. If the most significant
// bit of that value is 1, then the value is negative.
// Unless it already fits, of course.
println!(" 128 as a i16 is: {}", 128 as i16);
// In boundary case 128 value in 8-bit two's complement representation is -128
println!(" 128 as a i8 is : {}", 128 as i8);
// repeating the example above
// 1000 as u8 -> 232
println!("1000 as a u8 is : {}", 1000 as u8);
// and the value of 232 in 8-bit two's complement representation is -24
println!(" 232 as a i8 is : {}", 232 as i8);
// Since Rust 1.45, the `as` keyword performs a *saturating cast*
// when casting from float to int. If the floating point value exceeds
// the upper bound or is less than the lower bound, the returned value
// will be equal to the bound crossed.
// 300.0 as u8 is 255
println!(" 300.0 as u8 is : {}", 300.0_f32 as u8);
// -100.0 as u8 is 0
println!("-100.0 as u8 is : {}", -100.0_f32 as u8);
// nan as u8 is 0
println!(" nan as u8 is : {}", f32::NAN as u8);
// This behavior incurs a small runtime cost and can be avoided
// with unsafe methods, however the results might overflow and
// return **unsound values**. Use these methods wisely:
unsafe {
// 300.0 as u8 is 44
println!(" 300.0 as u8 is : {}", 300.0_f32.to_int_unchecked::<u8>());
// -100.0 as u8 is 156
println!("-100.0 as u8 is : {}", (-100.0_f32).to_int_unchecked::<u8>());
// nan as u8 is 0
println!(" nan as u8 is : {}", f32::NAN.to_int_unchecked::<u8>());
}
}
// This function only gets compiled if the target OS is linux
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
println!("You are running linux!");
}
// And this function only gets compiled if the target OS is *not* linux
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
println!("You are *not* running linux!");
}
fn main() {
are_you_on_linux();
println!("Are you sure?");
if cfg!(target_os = "linux") {
println!("Yes. It's definitely linux!");
} else {
println!("Yes. It's definitely *not* linux!");
}
}
struct Droppable {
name: &'static str,
}
// This trivial implementation of `drop` adds a print to console.
impl Drop for Droppable {
fn drop(&mut self) {
println!("> Dropping {}", self.name);
}
}
fn main() {
let _a = Droppable { name: "a" };
// block A
{
let _b = Droppable { name: "b" };
// block B
{
let _c = Droppable { name: "c" };
let _d = Droppable { name: "d" };
println!("Exiting block B");
}
println!("Just exited block B");
println!("Exiting block A");
}
println!("Just exited block A");
// Variable can be manually dropped using the `drop` function
drop(_a);
// TODO ^ Try commenting this line
println!("end of the main function");
// `_a` *won't* be `drop`ed again here, because it already has been
// (manually) `drop`ed
}
#include "Comms.h"
Subdevice::Subdevice(const uint8_t _address, Device& _device) :
address(_address),
next(NULL),
device(_device)
{
device.AddSubdevice(this);
}
MainSubdevice::MainSubdevice(const uint8_t _address, Device& _device) :
Subdevice(_address, _device)
{}
void MainSubdevice::command(const uint32_t cmd)
{
switch (cmd)
{
case MAINSUBDEVICE_CMD_PING: cmd_ping(); break;
case MAINSUBDEVICE_CMD_LIST_SUBDEVICES: cmd_list_subdevices(); break;
default:
device.send32(ERROR_BAD_COMMAND);
break;
}
}
void MainSubdevice::cmd_ping()
{
device.send32(ACK);
}
void MainSubdevice::cmd_list_subdevices()
{
int size = 9;
uint32_t* p = (uint32_t*) (device.txBuffer + 4);
*p++ = id();
Subdevice* subdevice = this;
while (subdevice = subdevice->next)
{
*p++ = subdevice->id();
size += 4;
}
device.finishPacket(size);
}
Device::Device(const uint8_t _address) :
address(_address),
subdevices(NULL),
mainSubdevice(MainSubdevice(0, *this))
{
Serial.begin(115200);
rxHead = 0;
rxTail = 0;
lastRX = millis();
}
void Device::pump()
{
readSerial();
int rec = rxTail - rxHead;
if (rec < 0) rec += RX_BUFFER_SIZE;
if (rec >= 2)
{
uint8_t a = rxBuffer[rxHead];
uint8_t b = rxBuffer[(rxHead + 1) & RX_BUFFER_MASK];
int exp = (b << 8) | a;
if (exp == rec)
{
if (exp < 9)
{
// malformed packet
Serial.println("malform"); // TODO
rxHead = (rxHead + exp) & RX_BUFFER_MASK;
}
else if (!checkChecksum())
{
// failed checksum
Serial.println("badchecsum"); // TODO
rxHead = (rxHead + exp) & RX_BUFFER_MASK;
}
else
{
uint16_t size = consume16();
uint8_t deviceAddress = consume8();
if (deviceAddress != address)
{
rxHead = (rxHead + size - 3) & RX_BUFFER_MASK;
}
else
{
uint8_t subdeviceAddress = consume8();
uint32_t command = consume32();
int endOfPacket = (rxHead + size - 8) & RX_BUFFER_MASK;
dispatch(subdeviceAddress, command);
rxHead = endOfPacket;
}
}
}
}
}
void Device::readSerial()
{
if (Serial.available())
{
uint8_t input = Serial.read();
rxBuffer[rxTail++] = input;
rxTail &= RX_BUFFER_MASK;
if (rxTail == rxHead)
{
// overflow
}
Serial.write(input);// TODO
lastRX = millis();
}
else if (rxTail != rxHead)
{
uint32_t timeSinceReceive = millis() - lastRX;
if (timeSinceReceive >= RX_TIMEOUT)
{
Serial.println("tieout"); // TODO
rxHead = rxTail;
}
}
}
void Device::dispatch(const uint8_t subdeviceAddress, const uint32_t cmd)
{
Subdevice* subdevice = subdevices;
while (subdevice != NULL)
{
if (subdevice->address == subdeviceAddress)
{
subdevice->command(cmd);
return;
}
subdevice = subdevice->next;
}
send32(ERROR_SUBDEVICE_NOT_FOUND);
}
uint8_t Device::consume8()
{
uint8_t a = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
return a;
}
uint16_t Device::consume16()
{
uint8_t a = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
uint8_t b = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
return (((uint16_t)b) << 8) | ((uint16_t) a);
}
uint32_t Device::consume32()
{
uint8_t a = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
uint8_t b = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
uint8_t c = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
uint8_t d = rxBuffer[rxHead++];
rxHead &= RX_BUFFER_MASK;
return (((uint32_t)d) << 24) | (((uint32_t)c) << 16) | (((uint32_t)b) << 8) | ((uint32_t)a);
}
void Device::send32(const uint32_t msg)
{
uint32_t* p = (uint32_t*) (txBuffer + 4);
*p = msg;
finishPacket(9);
}
static const uint8_t crc_table[] =
{
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31,
0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65,
0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9,
0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1,
0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2,
0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe,
0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,
0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16,
0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42,
0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80,
0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,
0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8,
0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c,
0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10,
0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,
0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f,
0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b,
0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7,
0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83,
0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef,
0xfa, 0xfd, 0xf4, 0xf3
};
bool Device::checkChecksum()
{
uint8_t crc = 0;
int c = rxHead;
int ce = rxTail - 1;
while (c != ce)
{
crc = crc_table[crc ^ rxBuffer[c++]];
c &= RX_BUFFER_MASK;
}
return crc == rxBuffer[c];
}
void Device::finishPacket(const int len)
{
txBuffer[0] = len & 0xff;
txBuffer[1] = len >> 8;
txBuffer[2] = 0;
txBuffer[3] = 0;
uint8_t crc = 0;
uint8_t* p = txBuffer;
uint8_t* pe = txBuffer + len - 1;
while(p < pe)
{
crc = crc_table[crc ^ *p++];
}
*p = crc;
Serial.write(txBuffer, len);
}
void Device::AddSubdevice(Subdevice* subdevice)
{
if (subdevices == NULL)
{
subdevices = subdevice;
}
else
{
Subdevice* dev = subdevices;
while (dev->next) dev = dev->next;
dev->next = subdevice;
}
}
# ExLlama
A standalone Python/C++/CUDA implementation of Llama for use with 4-bit GPTQ weights, designed to be fast and
memory-efficient on modern GPUs.
Disclaimer: The project is coming along, but it's still a work in progress!
## Hardware requirements
I am developing on an RTX 4090 and an RTX 3090-Ti. 30-series and later NVIDIA GPUs should be well supported, but
anything Pascal or older with poor FP16 support isn't going to perform well.
[AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ) or [GPTQ-for-LLaMa](https://github.com/qwopqwop200/GPTQ-for-LLaMa)
are better options at the moment for older GPUs. ROCm is also theoretically supported (via HIP) though I currently
have no AMD devices to test or optimize on.
## Dependencies
* Python 3.9 or newer
* `torch` tested on 2.0.1 and 2.1.0 (nightly) with cu118
* `safetensors` 0.3.2
* `sentencepiece`
* `ninja`
Additionally, only for the web UI:
* `flask`
* `waitress`
## Linux/WSL prerequisites
pip install --pre torch --index-url https://download.pytorch.org/whl/nightly/cu118
## Windows prerequisites
To run on Windows (without WSL):
1. Install [MSVC 2022](https://visualstudio.microsoft.com/downloads/). You can choose to install the whole `Visual
Studio 2022` IDE, or alternatively just the `Build Tools for Visual Studio 2022` package (make sure `Desktop
development with C++` is ticked in the installer), it doesn't really matter which.
2. Install the appropriate version of [PyTorch](https://pytorch.org/get-started/locally/), choosing one of the CUDA
versions. I am developing on the nightly build, but the stable version (2.0.1) should also work.
3. Install CUDA Toolkit, ([11.7](https://developer.nvidia.com/cuda-11-7-0-download-archive) and
[11.8](https://developer.nvidia.com/cuda-11-8-0-download-archive) both seem to work, just make sure to match PyTorch's
Compute Platform version).
4. For best performance, enable Hardware Accelerated GPU Scheduling.
## How to
Clone repo, install dependencies, and run benchmark:
git clone https://github.com/turboderp/exllama
cd exllama
pip install -r requirements.txt
python test_benchmark_inference.py -d <path_to_model_files> -p -ppl
The CUDA extension is loaded at runtime so there's no need to install it separately. It will be compiled on the first
run and cached to `~/.cache/torch_extensions/` which could take a little while. If nothing happens at first, give it
a minute to compile.
Chatbot example:
python example_chatbot.py -d <path_to_model_files> -un "Jeff" -p prompt_chatbort.txt
## Python module
jllllll currently maintains an installable Python module [here](https://github.com/jllllll/exllama) which may be more
suitable for integrating ExLlama with other projects
## Web UI
I also made a simple web UI for it. Don't look at the JavaScript, it was mostly written by ChatGPT and it will haunt
your dreams. But it sort of works, and it's kinda fun, especially multibot mode:

To run it:
pip install -r requirements-web.txt
python webui/app.py -d <path_to_model_files>
Note that sessions are stored in `~/exllama_sessions/` by default. You can change that location with `-sd` if you want.
## Docker
For security benefits and easier deployment, it is also possible to run the web UI in an isolated docker container. Note: the docker image currently only supports NVIDIA GPUs.
### Requirements
- [Docker](https://docs.docker.com/engine/install/)
- [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html)
It is recommended to run docker in [rootless mode](https://docs.docker.com/engine/security/rootless/).
### Build
The easiest way to build the docker image is using docker compose. First, set the `MODEL_PATH` and `SESSIONS_PATH` variables in the `.env` file to the actual directories on the host. Then run:
```
docker compose build
```
It is also possible to manually build the image:
```
docker build -t exllama-web .
```
NOTE: by default, the service inside the docker container is run by a non-root user. Hence, the ownership of bind-mounted directories (`/data/model` and `/data/exllama_sessions` in the default `docker-compose.yml` file) is changed to this non-root user in the container entrypoint (`entrypoint.sh`). To disable this, set `RUN_UID=0` in the `.env` file if using `docker compose`, or the following command if you manually build the image:
```
docker build -t exllama-web --build-arg RUN_UID=0 .
```
### Run
Using docker compose:
```
docker compose up
```
The web UI can now be accessed on the host at http://localhost:5000.
The configuration can be viewed in `docker-compose.yml` and changed by creating a `docker-compose.override.yml` file.
Run manually:
```
docker run --gpus all -p 5000:5000 -v <path_to_model_dir>:/data/model/ -v <path_to_session_dir>:/data/exllama_sessions --rm -it exllama-web --host 0.0.0.0:5000
```
## Results so far
### New implementation
| Model | Size | grpsz | act | Seq. len. | VRAM | Prompt | Best | Worst | Ppl |
|------------|-------|-------|-----|----------------------|-----------|------------|---------|---------|------|
| Llama | 7B | 128 | no | 2,048 t | 5,194 MB | 13,918 t/s | 173 t/s | 140 t/s | 6.45 |
| Llama | 13B | 128 | no | 2,048 t | 9,127 MB | 7,507 t/s | 102 t/s | 86 t/s | 5.60 |
| Llama | 33B | 128 | no | 2,048 t | 20,795 MB | 2,959 t/s | 47 t/s | 40 t/s | 4.60 |
| Llama | 33B | 128 | yes | 2,048 t | 20,795 MB | 2,784 t/s | 45 t/s | 37 t/s | 4.55 |
| Llama | 33B | 32 | yes | 1,550 t <sup>1</sup> | 21,486 MB | 2,636 t/s | 41 t/s | 37 t/s | 4.52 |
| Koala | 13B | 128 | yes | 2,048 t | 9,127 MB | 5,529 t/s | 93 t/s | 79 t/s | 6.73 |
| WizardLM | 33B | - | yes | 2,048 t | 20,199 MB | 2,313 t/s | 47 t/s | 40 t/s | 5.75 |
| OpenLlama | 3B | 128 | yes | 2,048 t | 3,128 MB | 16,419 t/s | 226 t/s | 170 t/s | 7.81 |
<sup>1</sup> Can not achieve full sequence length without OoM
All tests done on stock RTX 4090 / 12900K, running with a desktop environment, with a few other apps also using VRAM.
**"Prompt"** speed is inference over the sequence length listed minus 128 tokens. **"Worst"** is the average speed for
the last 128 tokens of the full context (worst case) and **"Best"** lists the speed for the first 128 tokens in an
empty sequence (best case.)
VRAM usage is as reported by PyTorch and does not include PyTorch's own overhead (CUDA kernels,
internal buffers etc.) This is somewhat unpredictable anyway. Best bet is to just optimize VRAM usage by the model,
probably aiming for 20 GB on a 24 GB GPU to ensure there is room for a desktop environment and all of Torch's
internals.
Perplexity is measured only to verify that the models are working. The dataset used is a particular, small sample from
WikiText, so scores are not comparable to other Llama benchmarks and only useful for comparing the different Llama
models to one another.
### Dual GPU results
The following benchmarks are from a 4090 + 3090-Ti with `-gs 17.2,24`:
| Model | Size | groupsize | act | Seq. len. | VRAM | Prompt | Best | Worst | Ppl |
|---------|------|-----------|-----|----------------|-----------|-----------|--------|---------|-------|
| Llama | 65B | 128 | yes | 2,048 t | 39,804 MB | 1,109 t/s | 20 t/s | 18 t/s | 4.20 |
| Llama | 65B | 32 | yes | 2,048 t | 43,424 MB | 1,037 t/s | 17 t/s | 16 t/s | 4.11 |
| Llama-2 | 70B | 128 | yes | 2,048 t | 40,680 MB | 914 t/s | 17 t/s | 14 t/s | 4.15 |
| Llama-2 | 70B | 32 | yes | 2,048 t | 36,815 MB | 874 t/s | 15 t/s | 12 t/s | 4.10 |
Note that perplexity scores may not be strictly apples-to-apples between Llama and Llama 2 due to their different
pretraining datasets.
## Todo
Moved the todo list [here](doc/TODO.md).
## Compatibility
[Here](doc/model_compatibility.md) is a list of models confirmed to be working right now.
import * as util from "./util.js";
import * as mainmenu from "./mainmenu.js";
import * as globals from "./globals.js";
import * as controls from "./controls.js";
import * as overlay from "./overlay.js";
export class NotepadSettings {
constructor(parent) {
this.element = util.newHFlex();
this.parent = parent;
this.settings = this.parent.notepadSettings;
//console.log(this.settings);
this.populate();
}
populate() {
this.element.innerHTML = "";
this.sss_genParams = new controls.CollapsibleSection(null, "Generation parameters");
this.sss_sampling = new controls.CollapsibleSection(null, "Sampling");
this.element.appendChild(this.sss_genParams.element);
this.element.appendChild(this.sss_sampling.element);
// Generation params
this.sss_i_maxTokens = new controls.SettingsSlider("sss-item-left", "Max tokens", "sss-item-mid", "sss-item-right sss-item-textbox-r", 0, 16, 2048, null, this.settings, "maxtokens", () => { this.updateView(true); });
this.sss_i_chunkTokens = new controls.SettingsSlider("sss-item-left", "Chunk tokens", "sss-item-mid", "sss-item-right sss-item-textbox-r", 0, 16, 2048, null, this.settings, "chunktokens", () => { this.updateView(true); });
this.sss_stopConditions = new controls.CollapsibleSection(null, "Stop conditions");
this.sss_genParams.inner.appendChild(this.sss_i_maxTokens.element);
this.sss_genParams.inner.appendChild(this.sss_i_chunkTokens.element);
this.element.appendChild(this.sss_stopConditions.element);
// Sampling
this.sss_i_temperature = new controls.SettingsSlider("sss-item-left", "Temperature", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0, 3, null, this.settings, "temperature", () => { this.updateView(true); });
this.sss_i_topK = new controls.SettingsSlider("sss-item-left", "Top K", "sss-item-mid", "sss-item-right sss-item-textbox-r", 0, 0, 1000, { "0": "off" }, this.settings, "top_k", () => { this.updateView(true); });
this.sss_i_topP = new controls.SettingsSlider("sss-item-left", "Top P", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0, 1, { "0.00": "off", "1.00": "off" }, this.settings, "top_p", () => { this.updateView(true); });
this.sss_i_minP = new controls.SettingsSlider("sss-item-left", "Min P", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0, 1, { "0.00": "off", "1.00": "off" }, this.settings, "min_p", () => { this.updateView(true); });
this.sss_i_tfs = new controls.SettingsSlider("sss-item-left", "TFS", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0, 1, { "0.00": "off", "1.00": "off" }, this.settings, "tfs", () => { this.updateView(true); });
this.sss_i_typical = new controls.SettingsSlider("sss-item-left", "Typical", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0, 1, { "0.00": "off", "1.00": "off" }, this.settings, "typical", () => { this.updateView(true); });
this.sss_i_repPenalty = new controls.SettingsSlider("sss-item-left", "Rep. penalty", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 1, 3, { "1.00": "off" }, this.settings, "repp", () => { this.updateView(true); });
this.sss_i_repRange = new controls.SettingsSlider("sss-item-left", "Rep. range", "sss-item-mid", "sss-item-right sss-item-textbox-r", 0, 0, 4096, { "0": "off" }, this.settings, "repr", () => { this.updateView(true); });
this.sss_i_mirostat = new controls.CheckboxLabel("sss-item-right clickable", "Mirostat", this.settings, "mirostat", () => { this.updateView(true); });
this.sss_i_mirostat_tau = new controls.SettingsSlider("sss-item-left", "Mirostat tau", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0.01, 10, null, this.settings, "mirostat_tau", () => { this.updateView(true); });
this.sss_i_mirostat_eta = new controls.SettingsSlider("sss-item-left", "Mirostat eta", "sss-item-mid", "sss-item-right sss-item-textbox-r", 2, 0.01, 5, null, this.settings, "mirostat_eta", () => { this.updateView(true); });
this.sss_sampling.inner.appendChild(this.sss_i_temperature.element);
this.sss_sampling.inner.appendChild(this.sss_i_topK.element);
this.sss_sampling.inner.appendChild(this.sss_i_topP.element);
this.sss_sampling.inner.appendChild(this.sss_i_minP.element);
this.sss_sampling.inner.appendChild(this.sss_i_tfs.element);
this.sss_sampling.inner.appendChild(this.sss_i_typical.element);
this.sss_sampling.inner.appendChild(this.sss_i_repPenalty.element);
this.sss_sampling.inner.appendChild(this.sss_i_repRange.element);
this.sss_sampling.inner.appendChild(this.sss_i_mirostat.element);
this.sss_sampling.inner.appendChild(this.sss_i_mirostat_tau.element);
this.sss_sampling.inner.appendChild(this.sss_i_mirostat_eta.element);
// Stop conditions
this.populate_stop_conditions();
this.updateView();
}
populate_stop_conditions() {
this.sss_stopConditions.inner.innerHTML = "";
this.sss_i_stopconditions = [];
for (let i = 0; i < this.settings.stop_conditions.length; i++) {
this.sss_i_stopconditions[i] = new controls.CheckboxTextboxButton(
"stop_condition_" + i,
"sss-item-left",
"Incl.",
"sss-item-mid sss-item-textbox",
"",
this.settings,
"stop_conditions",
i,
"text",
"inclusive",
(v) => { return v != ""; },
() => { this.updateView(true); },
"✕ Remove",
() => {
this.settings.stop_conditions.splice(i, 1);
this.populate_stop_conditions();
this.updateView(true);
}
);
}
for (let i = 0; i < this.settings.stop_conditions.length; i++)
this.sss_stopConditions.inner.appendChild(this.sss_i_stopconditions[i].element);
if (this.settings.stop_conditions.length < 10) {
this.sss_i_addStopCondition = new controls.LinkButton("+ Add...", null, () => {
this.settings.stop_conditions.push({text: "", inclusive: false});
this.populate_stop_conditions();
this.updateView(true);
}, "sss-item-link");
this.sss_stopConditions.inner.appendChild(this.sss_i_addStopCondition.element);
}
}
updateView(send = false) {
// Settings visibility
let mirostat = this.settings.mirostat;
this.sss_i_mirostat_tau.setVisible(mirostat);
this.sss_i_mirostat_eta.setVisible(mirostat);
// Send
if (send) this.send();
//console.log(this.settings);
}
send(post = null) {
//console.log(this.settings);
let packet = {};
packet.settings = this.settings;
if (!this.parent.notepadID || this.parent.notepadID == "new") {
fetch("/api/new_notepad", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(packet) })
.then(response => response.json())
.then(response => {
this.parent.parent.lastNotepadUUID = response.notepad.notepad_uuid;
this.parent.parent.onEnter();
if (post) post(response);
});
} else {
fetch("/api/update_notepad_settings", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(packet) })
.then(response => response.json())
.then(response => {
if (post) post(response);
});
}
}
}
input[type=range] {
-webkit-appearance: none;
margin: 4px 0;
width: 100%;
background: transparent;
}
input[type=range]:focus {
outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 6.4px;
cursor: pointer;
box-shadow: 1px 1px 1px #00000020, 0px 0px 1px #0d0d0d40;
background: var(--slider-track-color);
border-radius: 1.0px;
border: 0.2px solid #01010120;
}
input[type=range]::-webkit-slider-thumb {
box-shadow: 1px 1px 1px #00000080, 0px 0px 1px #0d0d0d40;
border: 1px solid #00000080;
height: 16px;
width: 16px;
border-radius: 3px;
background: var(--slider-thumb-color);
cursor: pointer;
-webkit-appearance: none;
margin-top: -5px;
}
input[type=range]:hover::-webkit-slider-runnable-track {
/* background: var(--slider-hover-color);*/
}
input[type=range]::-moz-range-track {
width: 100%;
height: 4.4px;
cursor: pointer;
box-shadow: 1px 1px 1px #00000080, 0px 0px 1px #0d0d0d40;
background: var(--slider-track-color);
border-radius: 1.3px;
border: 0.2px solid var(--slider-track-color);;
}
input[type=range]::-moz-range-thumb {
box-shadow: 1px 1px 1px #00000080, 0px 0px 1px #0d0d0d40;
border: 1px solid #00000080;
height: 13px;
width: 13px;
border-radius: 3px;
background: var(--slider-thumb-color);
cursor: pointer;
}
input[type=range]:hover::-moz-range-track {
/* background: var(--slider-hover-color);*/
}
import * as util from "./util.js";
class PageOverlay {
constructor() {
this.keyboardDisabled = false;
document.addEventListener("keydown", (e) => {
if (this.keyboardDisabled) e.preventDefault();
});
this.overlayElement = util.newDiv(null, "page-overlay");
document.body.appendChild(this.overlayElement);
this.items = new Map();
}
add(mode, control) {
this.items.set(mode, control);
this.overlayElement.appendChild(control.element);
return control;
}
setMode(mode = null) {
if (!mode) {
this.keyboardDisabled = false;
this.overlayElement.style.display = "none";
this.items.forEach((v, k) => { v.setVisible(false); });
} else {
this.keyboardDisabled = true;
this.overlayElement.style.display = "flex";
this.items.forEach((v, k) => { v.setVisible(mode === k); });
}
}
}
class Overlay {
constructor() {
this.element = util.newDiv(null, "overlay");
}
setVisible(visible) {
this.element.style.display = visible ? "flex" : "none";
}
}
class BusyOverlay extends Overlay {
constructor() {
super();
this.element.innerHTML = "<p class='p-header'>Please wait</p>" +
"<div class='spinner'><div></div><div></div><div></div><div></div></div>";
}
}
class LoadingOverlay extends Overlay {
constructor() {
super();
this.element.innerHTML = "<p class='p-header'>Loading</p>";
this.box = util.newDiv(null, "progressbar-box");
this.element.appendChild(this.box);
this.bar = util.newDiv(null, "progressbar-bar");
this.box.appendChild(this.bar);
}
setProgress(a, b) {
let percentage = 100 * (a / b);
this.bar.style.width = percentage + '%';
}
}
export var pageOverlay = new PageOverlay();
export var busyOverlay = pageOverlay.add("busy", new BusyOverlay());
export var loadingOverlay = pageOverlay.add("loading", new LoadingOverlay());
@app.route("/api/load_model", methods=['POST'])
def api_load_model():
global api_lock, verbose
if verbose: print("/api/load_model")
with api_lock:
data = request.get_json()
if verbose: print("<-", data)
if verbose: print("-> ...")
result = Response(stream_with_context(load_model(data)), mimetype = 'application/json')
if verbose: print("->", result)
return result
@app.route("/api/unload_model")
def api_unload_model():
global api_lock, verbose
if verbose: print("/api/unload_model")
with api_lock:
result = unload_model()
if verbose: print("->", result)
return json.dumps(result) + "\n"
@app.route("/api/list_sessions")
def api_list_sessions():
global api_lock, verbose
if verbose: print("/api/list_sessions")
with api_lock:
s, c = list_sessions()
result = { "result": "ok", "sessions": s, "current_session": c }
if verbose: print("-> (...)")
return json.dumps(result) + "\n"
@app.route("/api/get_default_settings")
def api_get_default_settings():
global api_lock, verbose
if verbose: print("/api/get_default_settings")
with api_lock:
result = { "result": "ok",
"session_settings": get_default_session_settings(),
"notepad_settings": get_default_notepad_settings(),
"prompt_formats": list_prompt_formats() }
return json.dumps(result) + "\n"
@app.route("/api/set_session", methods=['POST'])
def api_set_session():
global api_lock, verbose
if verbose: print("/api/set_session")
with api_lock:
data = request.get_json()
if verbose: print("<-", data)
session = set_session(data)
if session is not None:
result = { "result": "ok",
"session": session,
"prompt_formats": list_prompt_formats() }
if verbose: print("-> (...)")
else:
result = { "result": "fail" }
if verbose: print("->", result)
return json.dumps(result) + "\n"
@app.route("/api/new_session", methods=['POST'])
def api_new_session():
global api_lock, verbose
if verbose: print("/api/new_session")
with api_lock:
data = request.get_json()
if verbose: print("<-", data)
session = new_session()
if "settings" in data: get_session().update_settings(data["settings"])
if "user_input_text" in data: get_session().user_input(data)
if "new_name" in data: get_session().rename(data)
result = { "result": "ok", "session": session }
if verbose: print("-> (...)")
return json.dumps(result) + "\n"
@app.route("/api/rename_session", methods=['POST'])
def api_rename_session():
global api_lock, verbose
if verbose: print("/api/rename_session")
with api_lock:
data = request.get_json()
if verbose: print("<-", data)
s = get_session()
s.rename(data)
result = { "result": "ok" }
if verbose: print("->", result)
return json.dumps(result) + "\n"
def is_rocm_installed():
# Implement a check for ROCm (e.g., looking for specific files or running a command)
# Return True if ROCm is found, False otherwise
pass
def is_cuda_installed():
# Implement a check for CUDA
# Return True if CUDA is found, False otherwise
pass
def install_packages():
if is_rocm_installed():
subprocess.run([sys.executable, '-m', 'pip', 'install', 'some_rocm_package'])
elif is_cuda_installed():
subprocess.run([sys.executable, '-m', 'pip', 'install', 'some_cuda_package'])
else:
print("Neither ROCm nor CUDA detected.")
if __name__ == "__main__":
install_packages()
#ifndef _qdq_4_cuh
#define _qdq_4_cuh
#include "qdq_util.cuh"
#include "../../config.h"
#if QMODE_4BIT == 1
// Permutation:
//
// 77775555 33331111 66664444 22220000
__forceinline__ __device__ void shuffle_4bit_8
(
uint32_t* q,
int stride
)
{
uint32_t qa = q[0];
uint32_t qb = 0;
#pragma unroll
for (int i = 0; i < 4; i++)
{
uint32_t qa0 = qa & 0x0f;
uint32_t qa1 = (qa & 0xf0) >> 4;
qa >>= 8;
qb |= (qa1 << (i * 4 + 16));
qb |= (qa0 << (i * 4));
}
q[0] = qb;
}
__forceinline__ __device__ void dequant_4bit_8
(
const uint32_t q_0,
half2 (&dq)[4],
int stride
)
{
const uint32_t c0 = 0x64006400;
const half y16_ = __float2half_rn(1.0f / 16.0f);
const half2 y16 = __halves2half2(y16_, y16_);
const half z1_ = __float2half_rn(-1024.0f - 8.0f);
const half z16_ = __float2half_rn(-1024.0f / 16.0f - 8.0f);
const half2 z1 = __halves2half2(z1_, z1_);
const half2 z16 = __halves2half2(z16_, z16_);
uint32_t qa = q_0;
half2_uint32 q0((qa & 0x000f000f) | c0); // half2(q[ 0], q[ 1]) + 1024
half2_uint32 q1((qa & 0x00f000f0) | c0); // half2(q[ 2], q[ 3]) * 16 + 1024
qa >>= 8;
half2_uint32 q2((qa & 0x000f000f) | c0); // half2(q[ 4], q[ 5]) + 1024
half2_uint32 q3((qa & 0x00f000f0) | c0); // half2(q[ 6], q[ 7]) * 16 + 1024
dq[0] = __hadd2(q0.as_half2, z1);
dq[1] = __hfma2(q1.as_half2, y16, z16);
dq[2] = __hadd2(q2.as_half2, z1);
dq[3] = __hfma2(q3.as_half2, y16, z16);
}
__forceinline__ __device__ void dequant_4bit_8_prep_zero_scale
(
const uint32_t zero,
const half scale,
half2 (&z1z16)[2],
half2 (&y1y16)[2]
)
{
half_uint16 z1(0xe400 | zero); // half(-1024.0f - zero);
half z16 = __hsub(__int2half_rn(-64), __int2half_rn(zero));
half2 scale2 = __half2half2(scale);
z1z16[0] = __hmul2(scale2, __half2half2(z1.as_half));
z1z16[1] = __hmul2(scale2, __half2half2(z16));
const half y1 = __float2half_rn(1.0f);
const half y16 = __float2half_rn(1.0f / 16.0f);
y1y16[0] = __hmul2(scale2, __half2half2(y1));
y1y16[1] = __hmul2(scale2, __half2half2(y16));
}
__forceinline__ __device__ void dequant_4bit_8_prep_zero
(
const uint32_t zero,
half2(&z1z16)[2],
half2(&y1y16)[2]
)
{
half_uint16 z1(0xe400 | zero); // half(-1024.0f - zero);
half z16 = __hsub(__int2half_rn(-64), __int2half_rn(zero));
z1z16[0] = __half2half2(z1.as_half);
z1z16[1] = __half2half2(z16);
const half y1 = __float2half_rn(1.0f);
const half y16 = __float2half_rn(1.0f / 16.0f);
y1y16[0] = __half2half2(y1);
y1y16[1] = __half2half2(y16);
}
__forceinline__ __device__ void dequant_4bit_8_gptq
(
const uint32_t q_0,
half2 (&dq)[4],
half2 (&z1z16)[2],
half2 (&y1y16)[2],
int stride,
bool scaled
)
{
const uint32_t c0 = 0x64006400;
uint32_t qa = q_0;
half2_uint32 q0((qa & 0x000f000f) | c0); // half2( q[0] + 1024, q[1] + 1024 )
half2_uint32 q1((qa & 0x00f000f0) | c0); // half2( q[2] * 16 + 1024, q[3] * 16 + 1024 )
qa >>= 8;
half2_uint32 q2((qa & 0x000f000f) | c0); // half2( q[4] + 1024, q[5] + 1024 )
half2_uint32 q3((qa & 0x00f000f0) | c0); // half2( q[6] * 16 + 1024, q[7] * 16 + 1024 )
if (scaled)
{
dq[0] = __hfma2(q0.as_half2, y1y16[0], z1z16[0]); // half2( q[0] * s - z * s, q[1] * s - z * s)
dq[1] = __hfma2(q1.as_half2, y1y16[1], z1z16[1]); // half2( q[2] * s - z * s, q[3] * s - z * s)
dq[2] = __hfma2(q2.as_half2, y1y16[0], z1z16[0]);
dq[3] = __hfma2(q3.as_half2, y1y16[1], z1z16[1]);
}
else
{
dq[0] = __hadd2(q0.as_half2, z1z16[0]); // half2( q[0] - z, q[1] - z )
dq[1] = __hfma2(q1.as_half2, y1y16[1], z1z16[1]); // half2( q[2] - z, q[3] - z )
dq[2] = __hadd2(q2.as_half2, z1z16[0]); // half2( q[4] - z, q[5] - z )
dq[3] = __hfma2(q3.as_half2, y1y16[1], z1z16[1]); // half2( q[6] - z, q[7] - z )
}
}
#else
__forceinline__ __device__ void shuffle_4bit_8
(
uint32_t* q,
int stride
)
{
}
__forceinline__ __device__ void dequant_4bit_8
(
const uint32_t q_0,
half2 (&dq)[4],
int stride
)
{
half dqh[8];
for (int i = 0; i < 8; i++) dqh[i] = dq_ns(exb(q_0, i * 4, 0x0f), 8);
for (int i = 0; i < 4; i++) dq[i] = __halves2half2(dqh[i * 2], dqh[i * 2 + 1]);
}
__forceinline__ __device__ void dequant_4bit_8_prep_zero_scale
(
const uint32_t zero,
const half scale,
half2 (&z1)[2],
half2 (&y1)[2]
)
{
half z = __int2half_rn(-((int)zero));
z = __hmul(z, scale);
z1[0] = __half2half2(z);
y1[0] = __half2half2(scale);
}
__forceinline__ __device__ void dequant_4bit_8_prep_zero
(
const uint32_t zero,
half2(&z1)[2],
half2(&y1)[2]
)
{
half z = __int2half_rn(-((int)zero));
z1[0] = __half2half2(z);
}
__forceinline__ __device__ void dequant_4bit_8_gptq
(
const uint32_t q_0,
half2 (&dq)[4],
half2 (&z1)[2],
half2 (&y1)[2],
int stride,
bool scaled
)
{
half2 dqh2[8];
uint32_t qa = q_0;
for (int i = 0; i < 4; i++)
{
half d0 = __int2half_rn(qa & 0x0f); qa >>= 4;
half d1 = __int2half_rn(qa & 0x0f); qa >>= 4;
dqh2[i] = __halves2half2(d0, d1);
}
if (scaled)
{
dq[0] = __hfma2(dqh2[0], y1[0], z1[0]);
dq[1] = __hfma2(dqh2[1], y1[0], z1[0]);
dq[2] = __hfma2(dqh2[2], y1[0], z1[0]);
dq[3] = __hfma2(dqh2[3], y1[0], z1[0]);
}
else
{
dq[0] = __hadd2(dqh2[0], z1[0]);
dq[1] = __hadd2(dqh2[1], z1[0]);
dq[2] = __hadd2(dqh2[2], z1[0]);
dq[3] = __hadd2(dqh2[3], z1[0]);
}
}
#endif
#endif
import gc
import torch
from torch import nn
import torch.nn.functional as F
import math
from exllamav2.ext import exllamav2_ext as ext_c, none_tensor
from exllamav2.util import list_live_tensors
class AdaptiveQuantizer:
norm: float = 3.5
max_p: float = 1.0
min_p: float = 0.75
p_grid: int = 48
bits: int
scale_bits: int
scale_range: float = 1.0
scale: torch.tensor
qscale: torch.tensor
qscale_max: float
maxq: float
scale_maxq: float
qzero: float
def __init__(self,
bits: int = 4,
scale_bits: int = 4):
self.bits = bits
self.scale_bits = scale_bits
self.maxq = 2 ** bits - 1
self.qzero = (self.maxq + 1) / 2
self.scale_maxq = 2 ** scale_bits - 1
self.scale_maxq = (2 ** self.scale_bits) - 1
def find_params(self, x):
xmax, _ = torch.max(torch.abs(x), dim = 0)
xmax += 1e-12
base_scale = xmax / (self.maxq / 2)
qscale_max_t = torch.max(base_scale) * self.scale_range
scale_tp = base_scale / qscale_max_t
scale_tp = torch.sqrt(scale_tp)
scale_tp *= (self.scale_maxq + 1)
qscale_t = torch.clamp(torch.round(scale_tp), 1, self.scale_maxq + 1)
qscale_tw = qscale_t / (self.scale_maxq + 1)
qscale_tw = qscale_tw ** 2
qscale_tw *= qscale_max_t
q = torch.zeros((self.p_grid + 1, 128), dtype = torch.float, device = x.device)
ext_c.quantize_err(x, q, qscale_tw, self.qzero, self.maxq, self.norm, self.min_p, self.max_p, self.p_grid)
q = torch.sum(q, dim = 1)
best_pi = torch.argmin(q)
best_pif = best_pi / self.p_grid
best_p = self.max_p * best_pif + self.min_p * (1 - best_pif)
# best_p = 1.0
self.qscale = qscale_t.to(torch.short)
self.scale = qscale_tw * best_p
self.qscale_max = qscale_max_t * best_p
class AdaptiveGPTQ:
percdamp: float = 0.07
layer: nn.Linear
device: torch.device
group_size: int
bits: list
bits_groups: list
scale_bits: int
hot_bits: int
columns: int
rows: int
hessian: torch.tensor
total_groups: int
perm: torch.tensor = None
invperm: torch.tensor = None
g_idx: torch.tensor = None
scale: torch.tensor = None
qscale: torch.tensor = None
qscale_max: torch.tensor = None
qweight: torch.tensor = None
qgroups: torch.tensor = None
quant: torch.tensor = None
weights: torch.tensor = None
hessian: torch.tensor = None
hessian_inv: torch.tensor = None
num_samples: int = 0
num_batches: int = 0
def __init__(self,
layer: nn.Linear):
self.layer = layer
self.device = layer.weight.device
self.rows = self.layer.weight.data.shape[1]
self.columns = self.layer.weight.data.shape[0]
self.weights = self.layer.weight.data.T.clone().float().contiguous()
self.hessian = None
self.num_samples = 0
self.num_batches = 0
def drop_buffers(self):
self.perm = None
self.invperm = None
self.g_idx = None
self.scale = None
self.qscale = None
self.qscale_max = None
self.qweight = None
self.qgroups = None
self.quant = None
self.weights = None
self.hessian = None
self.hessian_inv = None
gc.collect()
torch.cuda.empty_cache()
def configure(self,
group_size: dict,
bits = None,
bits_prop = None,
scale_bits: int = 4
):
self.group_size = group_size
self.scale_bits = scale_bits
self.bits = bits
assert isinstance(bits, list)
assert isinstance(bits_prop, list)
assert sum(bits_prop) == 1
groups = 0
remaining_rows = self.rows
self.bits_groups = []
for b, p in zip(self.bits, bits_prop):
assert p > 0
gsz = self.group_size[b]
g = math.ceil(min(self.rows * p, remaining_rows) / gsz)
groups += g
remaining_rows -= g * gsz
self.bits_groups.append(g)
assert remaining_rows <= 0
self.total_groups = groups
# if isinstance(bits, list):
#
# self.bits = bits
# g128 = (self.rows + 128 - 1) // 128
# self.bits_groups = [max(round(g128 * p), 1) * 128 // self.group_size for p in bits_prop]
# e = sum(self.bits_groups) - self.total_groups
# self.bits_groups[-1] -= e
#
# else:
#
# self.bits = [bits]
# self.bits_groups = [self.total_groups]
# def num_bits(self, subtract_columns = 0):
#
# gi = self.g_idx.numel() * 32
# qs = self.qscale.numel() * self.scale_bits
# qss = self.qscale_max.numel() * 16
#
# w = 0
# tr = self.rows
# for g, b in zip(self.bits_groups, self.bits):
#
# c = self.columns - subtract_columns
# r = self.group_size * g
# if r > tr: r = tr
# tr -= r
# w += r * c * b
#
# return w + gi + qs + qss
def add_batch(self, inputs):
with torch.inference_mode():
if self.hessian is None:
self.hessian = torch.zeros((self.rows, self.rows), device=self.device, dtype=torch.float)
self.num_batches += 1
num_samples = len(inputs)
inputs = torch.cat(inputs, dim = 0)
inputs = inputs.view((-1, inputs.shape[-1])).float().T.to("cuda:0")
inputs *= math.sqrt(2 / num_samples)
self.hessian += inputs.matmul(inputs.T)
def prepare(self):
with torch.inference_mode():
self.hessian /= self.num_batches
diagonal = torch.diag(self.hessian)
# Zero weights that have no impact. Disabling this since it feels a little drastic based on just the calibration
# data. It likely never triggers, anyway.
# dead = diagonal == 0.0
# self.hessian[dead, dead] = 1
# self.weights[dead, :] = 0
# Activation order
self.perm = torch.argsort(diagonal, descending = True)
self.weights = self.weights[self.perm, :]
hessian = self.hessian[self.perm][:, self.perm]
self.hessian = None
# In case numerical errors have caused some asymmetry in H, assume it's close to symmetrical and force it.
# (Doesn't seem to be needed)
# torch.cuda.empty_cache()
# hessian = (hessian + hessian.T) * 0.5
# torch.cuda.empty_cache()
# Damping
diagonal = torch.diag(hessian)
damp = torch.clamp(self.percdamp * torch.mean(diagonal), min = 1e-5)
# Inverse of H
attempts = 0
while True:
try:
d = torch.arange(self.rows, device = self.device)
hessian[d, d] += damp
# Dump condition number and smallest eigenvalue (should be positive)
# fro_norm_hessian = torch.norm(hessian, p = 'fro')
# fro_norm_inv = torch.norm(torch.linalg.inv(hessian), p = 'fro')
# cond_number = fro_norm_hessian * fro_norm_inv
# print(cond_number)
# eigenvalues = torch.linalg.eigvalsh(hessian)
# is_pd = torch.all(eigenvalues > 0)
# print(is_pd)
# print(torch.min(eigenvalues))
hessian_inv = torch.linalg.cholesky(hessian)
hessian_inv = torch.cholesky_inverse(hessian_inv)
# The Cholesky inverse will sometimes fail to compute due to accumulated rounding errors when H
# is very large (e.g. 70B MLP down proj) and a lot of calibration data is used (e.g. 100 rows of
# 4096 tokens). This won't always throw an exception and sometimes just results in a NaN tensor.
if torch.any(torch.isnan(hessian_inv)): raise RuntimeError
# Test inversion
# test = hessian_inv @ hessian
# test.sub_(torch.eye(test.size(0), device = test.device, dtype = test.dtype))
# test **= 2
# test = test.mean()
# print(test)
hessian_inv = torch.linalg.cholesky(hessian_inv, upper = True)
hessian_inv = hessian_inv.contiguous()
break
except RuntimeError:
# If inverting failed, assume there were non-positive eigenvalues, so apply more damping to shift
# the eigenvalues in a positive direction.
print(" !! Warning: Applied additional damping")
attempts += 1
if attempts == 10:
raise ValueError("Hessian is not invertible")
self.hessian_inv = hessian_inv
self.hessian = None
def reuse_h(self, other):
with torch.inference_mode():
self.hessian_inv = other.hessian_inv
self.hessian = None
self.perm = other.perm
self.weights = self.weights[self.perm, :]
def quantize(self, keep_qweight = False, apply = False, drop = False):
with torch.inference_mode():
if apply:
weights = self.weights
self.layer.weight.data = torch.zeros((1, 1), dtype = torch.float32, device = weights.device)
else:
weights = self.weights.clone()
self.quant = torch.zeros_like(self.weights)
if keep_qweight:
self.qweight = torch.zeros_like(weights, dtype = torch.short)
# Quantize groups
scale = []
qscale = []
qscale_max = []
qgroups = []
error = weights.clone()
group_idx = 0
group_idx_list = []
b = 0
for bits_idx, bits in enumerate(self.bits):
quantizer = AdaptiveQuantizer(bits = bits, scale_bits = self.scale_bits)
for group in range(self.bits_groups[bits_idx]):
a = b
b = min(a + self.group_size[bits], self.rows)
qgroups.append(bits)
qgroups.append(0)
quantizer.find_params(weights[a : b, :])
scale.append(quantizer.scale)
qscale.append(quantizer.qscale)
qscale_max.append(quantizer.qscale_max)
ext_c.quantize_range(self.quant,
quantizer.scale,
self.qweight if keep_qweight else none_tensor,
quantizer.qzero,
quantizer.maxq,
self.hessian_inv,
weights,
error,
a,
b)
group_idx_list += [group_idx] * (b - a)
group_idx += 1
# Create g_idx to store inverse activation order
self.g_idx = torch.tensor(group_idx_list, dtype = torch.int32, device = self.device)
self.invperm = torch.argsort(self.perm)
self.g_idx = self.g_idx[self.invperm]
# Store scales
self.scale = torch.stack(scale, dim = 0)
self.qscale = torch.stack(qscale, dim = 0)
self.qscale_max = torch.tensor(qscale_max, dtype = torch.float16, device = self.device)
self.qgroups = torch.tensor(qgroups, dtype = torch.short, device = self.device)
# Apply
if apply:
if drop:
weights = None
error = None
scale = None
qscale = None
qscale_max = None
qgroups = None
group_idx_list = None
gc.collect()
torch.cuda.empty_cache()
self.apply_quant()
def quant_error(self):
with torch.inference_mode():
q = self.quant[self.invperm, :]
diff = torch.abs(q - self.layer.weight.data.T)
mat_error_1 = (diff > 0.01).sum().item() / diff.numel()
mat_error_5 = (diff > 0.05).sum().item() / diff.numel()
mat_error_10 = (diff > 0.10).sum().item() / diff.numel()
return mat_error_1, mat_error_5, mat_error_10
def apply_quant(self):
qc = self.quant.cpu()
invperm = self.invperm.cpu()
q = qc[invperm, :].T
q = q.reshape(self.quant.T.shape)
q = q.to(self.quant.device)
self.layer.weight.data = q
def apply_temp(self):
q = self.quant[self.invperm, :].T
temp_layer = nn.Linear(self.layer.in_features, self.layer.out_features, False, device = "meta", dtype = torch.float16)
temp_layer.weight = nn.Parameter(q.reshape(self.layer.weight.shape).type_as(self.layer.weight.data))
return temp_layer
def pack(self, key, qparams):
assert qparams.scale_bits in [4]
# assert self.columns % 32 == 0
output = {}
output[key + ".q_invperm"] = self.invperm.to(torch.int)
output[key + ".q_scale_max"] = self.qscale_max
output[key + ".q_groups"] = self.qgroups
columns = self.columns
rem_rows = self.rows
padding = -columns % 32
if padding != 0:
print(f" !! Note: Padding quantized tensor {key}")
qst = F.pad(self.qscale, (0, padding)).contiguous()
qwt = F.pad(self.qweight, (0, padding)).contiguous()
else:
qst = self.qscale
qwt = self.qweight
qst_packed = torch.zeros((qst.shape[0], qst.shape[1] * qparams.scale_bits // 32), dtype = torch.int32, device = self.device)
if qparams.scale_bits == 4: ext_c.pack_rows_4(qst, qst_packed)
# if qparams.scale_bits == 6: ext_c.pack_rows_6(qst, qst_packed) # TODO:
output[key + ".q_scale"] = qst_packed
qwt_packed = []
i = 0
row = 0
out_row = 0
while i < self.qscale.shape[0]:
bits = self.qgroups[i * 2].item()
self.qgroups[i * 2 + 1] = out_row
i += 1
rows = min(self.group_size[bits], rem_rows)
wpqr = 32 / bits
qrows = rows / wpqr
assert i == self.qgroups.shape[-1] or qrows == int(qrows)
qrows = math.ceil(qrows)
g_qwt = qwt[row:row+rows, :].contiguous()
g_qwt_packed = torch.zeros((qrows, columns + padding), dtype = torch.int32, device = self.device)
if padding > 0: g_qwt[:, -padding:] = 2 ** (bits - 1)
ext_c.pack_columns(g_qwt, g_qwt_packed, bits)
qwt_packed.append(g_qwt_packed)
# print(row, rows, bits)
row += rows
out_row += qrows
rem_rows -= rows
qwt_packed = torch.cat(qwt_packed, dim = 0)
output[key + ".q_weight"] = qwt_packed
return output
This page shows examples of messages formatted using JSON (JavaScript Object Notation).
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
The same text expressed as XML:
<!DOCTYPE glossary PUBLIC "-//OASIS//DTD DocBook V3.1//EN">
<glossary><title>example glossary</title>
<GlossDiv><title>S</title>
<GlossList>
<GlossEntry ID="SGML" SortAs="SGML">
<GlossTerm>Standard Generalized Markup Language</GlossTerm>
<Acronym>SGML</Acronym>
<Abbrev>ISO 8879:1986</Abbrev>
<GlossDef>
<para>A meta-markup language, used to create markup
languages such as DocBook.</para>
<GlossSeeAlso OtherTerm="GML">
<GlossSeeAlso OtherTerm="XML">
</GlossDef>
<GlossSee OtherTerm="markup">
</GlossEntry>
</GlossList>
</GlossDiv>
</glossary>
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
The same text expressed as XML:
<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
The same text expressed as XML:
<widget>
<debug>on</debug>
<window title="Sample Konfabulator Widget">
<name>main_window</name>
<width>500</width>
<height>500</height>
</window>
<image src="Images/Sun.png" name="sun1">
<hOffset>250</hOffset>
<vOffset>250</vOffset>
<alignment>center</alignment>
</image>
<text data="Click Here" size="36" style="bold">
<name>text1</name>
<hOffset>250</hOffset>
<vOffset>100</vOffset>
<alignment>center</alignment>
<onMouseUp>
sun1.opacity = (sun1.opacity / 100) * 90;
</onMouseUp>
</text>
</widget>
{"web-app": {
"servlet": [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "[email protected]",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"cachePackageTagsTrack": 200,
"cachePackageTagsStore": 200,
"cachePackageTagsRefresh": 60,
"cacheTemplatesTrack": 100,
"cacheTemplatesStore": 50,
"cacheTemplatesRefresh": 15,
"cachePagesTrack": 200,
"cachePagesStore": 100,
"cachePagesRefresh": 10,
"cachePagesDirtyRead": 10,
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "debug",
"maxUrlLength": 500}},
{
"servlet-name": "cofaxEmail",
"servlet-class": "org.cofax.cds.EmailServlet",
"init-param": {
"mailHost": "mail1",
"mailHostOverride": "mail2"}},
{
"servlet-name": "cofaxAdmin",
"servlet-class": "org.cofax.cds.AdminServlet"},
{
"servlet-name": "fileServlet",
"servlet-class": "org.cofax.cds.FileServlet"},
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true}}],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"},
"taglib": {
"taglib-uri": "cofax.tld",
"taglib-location": "/WEB-INF/tlds/cofax.tld"}}}
The same file expressed as XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>
cofaxCDS
</servlet-name>
<servlet-class>
org.cofax.cds.CDSServlet
</servlet-class>
<init-param>
<param-name>configGlossary:installationAt</param-name>
<param-value>Philadelphia, PA</param-value>
</init-param>
<init-param>
<param-name>configGlossary:adminEmail</param-name>
<param-value>[email protected]</param-value>
</init-param>
<init-param>
<param-name>configGlossary:poweredBy</param-name>
<param-value>Cofax</param-value>
</init-param>
<init-param>
<param-name>configGlossary:poweredByIcon</param-name>
<param-value>/images/cofax.gif</param-value>
</init-param>
<init-param>
<param-name>configGlossary:staticPath</param-name>
<param-value>/content/static</param-value>
</init-param>
<init-param>
<param-name>templateProcessorClass</param-name>
<param-value>org.cofax.WysiwygTemplate</param-value>
</init-param>
<init-param>
<param-name>templateLoaderClass</param-name>
<param-value>org.cofax.FilesTemplateLoader</param-value>
</init-param>
<init-param>
<param-name>templatePath</param-name>
<param-value>templates</param-value>
</init-param>
<init-param>
<param-name>templateOverridePath</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>defaultListTemplate</param-name>
<param-value>listTemplate.htm</param-value>
</init-param>
<init-param>
<param-name>defaultFileTemplate</param-name>
<param-value>articleTemplate.htm</param-value>
</init-param>
<init-param>
<param-name>useJSP</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>jspListTemplate</param-name>
<param-value>listTemplate.jsp</param-value>
</init-param>
<init-param>
<param-name>jspFileTemplate</param-name>
<param-value>articleTemplate.jsp</param-value>
</init-param>
<init-param>
<param-name>cachePackageTagsTrack</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>cachePackageTagsStore</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>cachePackageTagsRefresh</param-name>
<param-value>60</param-value>
</init-param>
<init-param>
<param-name>cacheTemplatesTrack</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>cacheTemplatesStore</param-name>
<param-value>50</param-value>
</init-param>
<init-param>
<param-name>cacheTemplatesRefresh</param-name>
<param-value>15</param-value>
</init-param>
<init-param>
<param-name>cachePagesTrack</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>cachePagesStore</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>cachePagesRefresh</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>cachePagesDirtyRead</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>searchEngineListTemplate</param-name>
<param-value>forSearchEnginesList.htm</param-value>
</init-param>
<init-param>
<param-name>searchEngineFileTemplate</param-name>
<param-value>forSearchEngines.htm</param-value>
</init-param>
<init-param>
<param-name>searchEngineRobotsDb</param-name>
<param-value>WEB-INF/robots.db</param-value>
</init-param>
<init-param>
<param-name>useDataStore</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>dataStoreClass</param-name>
<param-value>org.cofax.SqlDataStore</param-value>
</init-param>
<init-param>
<param-name>redirectionClass</param-name>
<param-value>org.cofax.SqlRedirection</param-value>
</init-param>
<init-param>
<param-name>dataStoreName</param-name>
<param-value>cofax</param-value>
</init-param>
<init-param>
<param-name>dataStoreDriver</param-name>
<param-value>com.microsoft.jdbc.sqlserver.SQLServerDriver</param-value>
</init-param>
<init-param>
<param-name>dataStoreUrl</param-name>
<param-value>jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon</param-value>
</init-param>
<init-param>
<param-name>dataStoreUser</param-name>
<param-value>sa</param-value>
</init-param>
<init-param>
<param-name>dataStorePassword</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>dataStoreTestQuery</param-name>
<param-value>SET NOCOUNT ON;select test='test';</param-value>
</init-param>
<init-param>
<param-name>dataStoreLogFile</param-name>
<param-value>/usr/local/tomcat/logs/datastore.log</param-value>
</init-param>
<init-param>
<param-name>dataStoreInitConns</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>dataStoreMaxConns</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>dataStoreConnUsageLimit</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>dataStoreLogLevel</param-name>
<param-value>debug</param-value>
</init-param>
<init-param>
<param-name>maxUrlLength</param-name>
<param-value>500</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>
cofaxEmail
</servlet-name>
<servlet-class>
org.cofax.cds.EmailServlet
</servlet-class>
<init-param>
<param-name>mailHost</param-name>
<param-value>mail1</param-value>
</init-param>
<init-param>
<param-name>mailHostOverride</param-name>
<param-value>mail2</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>
cofaxAdmin
</servlet-name>
<servlet-class>
org.cofax.cds.AdminServlet
</servlet-class>
</servlet>
<servlet>
<servlet-name>
fileServlet
</servlet-name>
<servlet-class>
org.cofax.cds.FileServlet
</servlet-class>
</servlet>
<servlet>
<servlet-name>
cofaxTools
</servlet-name>
<servlet-class>
org.cofax.cms.CofaxToolsServlet
</servlet-class>
<init-param>
<param-name>templatePath</param-name>
<param-value>toolstemplates/</param-value>
</init-param>
<init-param>
<param-name>log</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<param-name>logLocation</param-name>
<param-value>/usr/local/tomcat/logs/CofaxTools.log</param-value>
</init-param>
<init-param>
<param-name>logMaxSize</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>dataLog</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<param-name>dataLogLocation</param-name>
<param-value>/usr/local/tomcat/logs/dataLog.log</param-value>
</init-param>
<init-param>
<param-name>dataLogMaxSize</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>removePageCache</param-name>
<param-value>/content/admin/remove?cache=pages&id=</param-value>
</init-param>
<init-param>
<param-name>removeTemplateCache</param-name>
<param-value>/content/admin/remove?cache=templates&id=</param-value>
</init-param>
<init-param>
<param-name>fileTransferFolder</param-name>
<param-value>/usr/local/tomcat/webapps/content/fileTransferFolder</param-value>
</init-param>
<init-param>
<param-name>lookInContext</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<param-name>adminGroupID</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>betaServer</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>
cofaxCDS
</servlet-name>
<url-pattern>
/
</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>
cofaxEmail
</servlet-name>
<url-pattern>
/cofaxutil/aemail/*
</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>
cofaxAdmin
</servlet-name>
<url-pattern>
/admin/*
</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>
fileServlet
</servlet-name>
<url-pattern>
/static/*
</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>
cofaxTools
</servlet-name>
<url-pattern>
/tools/*
</url-pattern>
</servlet-mapping>
<taglib>
<taglib-uri>cofax.tld</taglib-uri>
<taglib-location>/WEB-INF/tlds/cofax.tld</taglib-location>
</taglib>
</web-app>
The action and label values only need to be provided if they are not the same as the id.
{"menu": {
"header": "SVG Viewer",
"items": [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
null,
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "OriginalView", "label": "Original View"},
null,
{"id": "Quality"},
{"id": "Pause"},
{"id": "Mute"},
null,
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"},
{"id": "ViewSource", "label": "View Source"},
{"id": "SaveAs", "label": "Save As"},
null,
{"id": "Help"},
{"id": "About", "label": "About Adobe CVG Viewer..."}
]
}}
The same message expressed as XML:
<menu>
<header>Adobe SVG Viewer</header>
<item action="Open" id="Open">Open</item>
<item action="OpenNew" id="OpenNew">Open New</item>
<separator/>
<item action="ZoomIn" id="ZoomIn">Zoom In</item>
<item action="ZoomOut" id="ZoomOut">Zoom Out</item>
<item action="OriginalView" id="OriginalView">Original View</item>
<separator/>
<item action="Quality" id="Quality">Quality</item>
<item action="Pause" id="Pause">Pause</item>
<item action="Mute" id="Mute">Mute</item>
<separator/>
<item action="Find" id="Find">Find...</item>
<item action="FindAgain" id="FindAgain">Find Again</item>
<item action="Copy" id="Copy">Copy</item>
<item action="CopyAgain" id="CopyAgain">Copy Again</item>
<item action="CopySVG" id="CopySVG">Copy SVG</item>
<item action="ViewSVG" id="ViewSVG">View SVG</item>
<item action="ViewSource" id="ViewSource">View Source</item>
<item action="SaveAs" id="SaveAs">Save As</item>
<separator/>
<item action="Help" id="Help">Help</item>
<item action="About" id="About">About Adobe CVG Viewer...</item>
</menu>
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access)
It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The third parameter is optional and can be used in cases such as if we want to sort the elements lexicographically.
By default, the sort() function sorts the elements in ascending order.
Below is a simple program to show the working of sort().
// C++ program to demonstrate default behaviour of
// sort() in STL.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
sort(arr, arr + n);
cout << "\nArray after sorting using "
"default sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Output
Array after sorting using default sort is :
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
How to sort in descending order?
sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass the “greater()” function to sort in descending order. This function does a comparison in a way that puts greater elements before.
// C++ program to demonstrate descending order sort using
// greater<>().
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, greater<int>());
cout << "Array after sorting : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
Output
Array after sorting :
9 8 7 6 5 4 3 2 1 0
Time Complexity: O(N log N)
Auxiliary Space: O(1)
Sort the array only in the given range: To deal with such types of problems we just have to mention the range inside the sort function.
Below is the implementation of above case:
// C++ program to demonstrate sort()
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 0, 1, 5, 8, 9, 6, 7, 3, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Sort the elements which lies in the range of 2 to
// (n-1)
sort(arr + 2, arr + n);
cout << "Array after sorting : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
// This code is contributed by Suruchi Kumari
Output
Array after sorting :
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
How to sort in a particular order?
We can also write our own comparator function and pass it as a third parameter. This “comparator” function returns a value; convertible to bool, which basically tells us whether the passed “first” argument should be placed before the passed “second” argument or not.
For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as arguments in the “compareInterval” function(comparator function). Now as i1.first (=6) < i2.first (=1), so our function returns “false”, which tells us that “first” argument should not be placed before “second” argument and so sorting will be done in order like {1,9} first and then {6,8} as next.
// A C++ program to demonstrate
// STL sort() using
// our own comparator
#include <bits/stdc++.h>
using namespace std;
// An interval has a start
// time and end time
struct Interval {
int start, end;
};
// Compares two intervals
// according to starting times.
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}
int main()
{
Interval arr[]
= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
int n = sizeof(arr) / sizeof(arr[0]);
// sort the intervals in increasing order of
// start time
sort(arr, arr + n, compareInterval);
cout << "Intervals sorted by start time : \n";
for (int i = 0; i < n; i++)
cout << "[" << arr[i].start << "," << arr[i].end
<< "] ";
return 0;
}
Output
Intervals sorted by start time :
[1,9] [2,4] [4,7] [6,8]
The time complexity of std::sort() is:
Best Case – O(N log N)
Average Case – O(N log N)
Worst-Case – O(N log N)
Space Complexity: It may use O( log N) auxiliary space.
#include <algorithm>
#include <iostream>
using namespace std;
template <class T>
class Comparator { // we pass an object of this class as
// third arg to sort function...
public:
bool operator()(T x1, T x2)
{
return x1 < x2;
}
};
template <class T> bool funComparator(T x1, T x2)
{ // return type is bool
return x1 <= x2;
}
void show(int a[], int array_size)
{
for (int i = 0; i < array_size; i++) {
cout << a[i] << " ";
}
}
int main()
{
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int asize = sizeof(a) / sizeof(int);
cout << "The array before sorting is : ";
show(a, asize);
cout << endl << "The array after sorting is(asc) :";
sort(a, a + asize);
show(a, asize);
cout << endl << "The array after sorting is(desc) :";
sort(a, a + asize, greater<int>());
show(a, asize);
cout << endl
<< "The array after sorting is(asc but our "
"comparator class) :";
sort(a, a + asize, Comparator<int>());
show(a, asize);
cout << endl
<< "The array after sorting is(asc but our "
"comparator function) :";
sort(a, a + asize, funComparator<int>);
show(a, asize);
return 0;
}
Output
The array before sorting is : 1 5 8 9 6 7 3 4 2 0
The array after sorting is(asc) :0 1 2 3 4 5 6 7 8 9
The array after sorting is(desc) :9 8 7 6 5 4 3 2 1 0
The array after sorting is(asc but our comparator class) :0 1 2 3 4 5 6 7 8 9
The array after sorting is(asc but our comparator function) :0 1 2 3 4 5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
The following are different ways to construct or initialize a vector in C++ STL
1. Initializing by pushing values one by one:
// C++ program to create an empty
// vector and push values one
// by one.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create an empty vector
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
vect.push_back(30);
for (int x : vect)
cout << x << " ";
return 0;
}
Output
10 20 30
2. Specifying size and initializing all values:
// C++ program to create an empty
// vector and push values one
// by one.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 3;
// Create a vector of size n with
// all values as 10.
vector<int> vect(n, 10);
for (int x : vect)
cout << x << " ";
return 0;
}
Output
10 10 10
3. Initializing like arrays:
// C++ program to initialize
// a vector like an array.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vect{ 10, 20, 30 };
for (int x : vect)
cout << x << " ";
return 0;
}
Output
10 20 30
4. Initializing from an array:
// C++ program to initialize
// a vector from an array.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int arr[] = { 10, 20, 30 };
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> vect(arr, arr + n);
for (int x : vect)
cout << x << " ";
return 0;
}
Output
10 20 30
5. Initializing from another vector:
// C++ program to initialize a vector from
// another vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vect1{ 10, 20, 30 };
vector<int> vect2(vect1.begin(), vect1.end());
for (int x : vect2)
cout << x << " ";
return 0;
}
Output
10 20 30
6. Initializing all elements with a particular value:
// C++ Program to initialize vector using fill()
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// creating array with size 10
vector<int> vect1(10);
// initializing using fill() function
int value = 5;
fill(vect1.begin(), vect1.end(), value);
// printing vector
for (int x : vect1)
cout << x << " ";
return 0;
}
Output
5 5 5 5 5 5 5 5 5 5
7. Initialize an array with consecutive numbers using std::iota:
// C++ program to initialize a
// vector with consecutive
// numbers
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main()
{
// declaring a vector with size 5
vector<int> vec(5);
// initializing using iota()
iota(vec.begin(), vec.end(), 1);
// printing the vector
for (int i = 0; i < 5; i++) {
cout << vec[i] << " ";
}
return 0;
}
Output
1 2 3 4 5
Time complexity: O(N), where N is the size of the vector.
Auxiliary space: O(N).
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
How to Hide and Show a Console Window in C++?
Read
Discuss
Courses
Practice
The task is to hide and Show the console window of a C++ program. The program for the same is given below.
Note: The results of the following program can only be seen when it is executed on a console.
Example:
// C++ program to hide and show a console window
#include <iostream>
#include <windows.h>
using namespace std;
void countdown()
{
cout << "3" << endl;
Sleep(1000);
cout << "2" << endl;
Sleep(1000);
cout << "1" << endl;
Sleep(1000);
cout << "0" << endl;
}
int main()
{
countdown();
HWND window;
AllocConsole();
// You Can Find HANDLE of other windows too
window = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(window, 0);
countdown();
ShowWindow(window, 1);
}
Output:
Explanation: The above program counts from 3 to 1 before the Console Window disappears. After the window has disappeared, the ShowWindow helps the program so that the Console Window reappears again after counting from 3 to 1(executing the countdown function).
The execution of the program can be understood by understanding the key functions of the program.
#include<windows.h> – The windows.h header in C++ programming languages are specifically designed for windows and contain a very large number of windows specific functions.
AllocConsole()- AllocConsole initializes standard input, standard output, and standard error handles for the new console.
ShowWindow()- Sets the specified window’s show state.
FindWindowA()– Takes string parameters and checks whose class name and window name match the specified strings
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Last Updated : 27 Nov, 2022
Prerequisite: Templates in C++
Substitution Failure Is Not An Error (SFINAE) is a principle of the C++ programming language that states that a compiler should not fail to compile a program just because it cannot substitute a template parameter. This principle allows for the use of template metaprogramming and enables the compiler to make decisions based on the types of template arguments, which can be useful when dealing with complex code and difficult to reason about logic.
At its core, SFINAE is a way of allowing a compiler to decide which template to use in a given context. The decision is based on the types of template arguments and the compiler will choose the template that is most appropriate for the arguments.
Advantages of SFINAE:
SFINAE is useful in a variety of scenarios, including writing generic code and dealing with complex logic.
SFINAE allows the compiler to decide which template to use, it allows programmers to write code that can be reused in different contexts without needing to explicitly specify the types of template parameters.
SFINAE allows for better code reuse, as the same code can be used for different types of objects and parameters.
SFINAE also allows for better control over code complexity by allowing the compiler to make decisions based on the types of template parameters, it can reduce the amount of complex logic that needs to be written and understood.
SFINAE helps to make code more readable and maintainable, as it is easier to follow the logic of the program.
In conclusion, SFINAE is a powerful concept in C++ programming that allows for better code reuse, improved code readability, and better control over code complexity. It is a key component of template metaprogramming and is an essential tool for writing robust and efficient code.
Example:
// C++ Program to implement
// Substitution Failure Is Not An Error
#include <iostream>
#include <type_traits>
using namespace std;
// USing template to avoid errors
template <typename T>
void print_type(T t)
{
// For integer
if (is_integral<T>::value) {
cout << "T is an integral type" << endl;
}
// For floating number
else if (is_floating_point<T>::value) {
cout << "T is a floating point type" << endl;
}
// All other
else {
cout << "T is not an integral"
<< "or floating point type" << endl;
}
}
// Driver Code
int main()
{
// T is an integral type
print_type(10);
// T is a floating point type
print_type(10.5f);
// T is an integral type
print_type(true);
// T is an integral type
print_type('a');
// T is not an integral
// or floating point type
print_type("GFG");
return 0;
}
Output
T is an integral type
T is a floating point type
T is an integral type
T is an integral type
T is not an integralor floating point type
In this example, the print_type() function is a template function that takes a single argument of type T. Inside the function, there are if statements that use the is_integral and is_floating_point type traits to check the type of T. If T is of the expected type, the corresponding branch of the if statement is executed and the appropriate message is printed. If T is not of the expected type, the else branch is executed and the message “T is not an integral or floating point type” is printed.
SFINAE is used in this example because the if statement uses type traits to check the type of T, and if T is not of the expected type, the template substitution will fail. However, because SFINAE is in effect, this failure is not treated as a compile-time error, and the else branch is executed instead.
Disadvantages of SFINAE
Although SFINAE is very useful it comes with its own limitations, these are :
It can be difficult to debug and understand the underlying code, as it relies heavily on the templates and multiple overloads to work correctly.
SFINAE is not widely used and can be difficult to find documentation and tutorials for.
SFINAE can produce unexpected behavior, as it relies on the compiler to determine which template to use based on the given types. This can lead to unexpected results if the compiler chooses the wrong template.
SFINAE can also be slow, as it involves multiple checks in order to determine the correct template. This can lead to a performance hit if used in a critical section of code.
There are other methods to perform the same task one of which is enable_if
Enable_if (Syntax)
template<typename T>
enable_if_t<is_integral<T>, void> f(T x)
{
// code that only applies to integral tmodule jinvertertb;
reg a;
wire y;
//Design Instance
jinverter jinv(y,a);
initial
begin
$display ("RESULT\ta\ty");
a = 1; # 100; // Another value
if ( y == 0 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 0; # 100; // Initial value is set
if ( y == 1 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 1; # 50; // Another value
if ( y == 0 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 0; # 100; // Initial value is set
if ( y == 1 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
end
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
endmoduleypes goes here
}
module jinvertertb;
reg a;
wire y;
//Design Instance
jinverter jinv(y,a);
initial
begin
$display ("RESULT\ta\ty");
a = 1; # 100; // Another value
if ( y == 0 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 0; # 100; // Initial value is set
if ( y == 1 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 1; # 50; // Another value
if ( y == 0 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
a = 0; # 100; // Initial value is set
if ( y == 1 ) // Test for inversion
$display (" PASS \t%d\t%d",a,y);
else
$display (" FAIL \t%d\t%d",a,y);
end
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
endmodule
module jFIFOTb;
wire [7:0] DATAOUT;
wire full, empty;
reg clock, reset, wn, rn;
reg [7:0] DATAIN;
jFIFO jfifo(DATAOUT, full, empty, clock, reset, wn, rn, DATAIN);
//enabling the wave dump
initial begin
$dumpfile("dump.vcd"); $dumpvars;
end
initial
begin
clock = 0; DATAIN = 8'd0;
reset = 1; clock = 1; #5 ; clock = 0; #5;
reset = 0;
$display("Start testing");
// First write some data into the queue
wn = 1; rn = 0;
DATAIN = 8'd100;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd150;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd200;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd40;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd70;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd65;
clock = 1; #5 ; clock = 0; #5;
DATAIN = 8'd15;
clock = 1; #5 ; clock = 0; #5;
// Now start reading and checking the values
wn = 0; rn = 1;
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd100 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd150 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd200 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd40 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd70 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd65 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( DATAOUT === 8'd15 )
$display("PASS %p ", DATAOUT);
else
$display("FAIL %p ", DATAOUT);
clock = 1; #5 ; clock = 0; #5;
if ( empty === 1 )
$display("PASS %p ", empty);
else
$display("FAIL %p ", empty);
end
endmodule
To understand this example, you should have the knowledge of the following Java programming topics:
Java for Loop
Java while and do...while Loop
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
Example 1: Find Factorial of a number using for loop
public class Factorial {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
Output
Factorial of 10 = 3628800
In this program, we've used for loop to loop through all numbers between 1 and the given number num (10), and the product of each number till num is stored in a variable factorial.
We've used long instead of int to store large results of factorial. However, it's still not big enough to store the value of bigger numbers (say 100).
For results that cannot be stored in a long variable, we use BigInteger variable declared in java.math library.
Example 2: Find Factorial of a number using BigInteger
import java.math.BigInteger;
public class Factorial {
public static void main(String[] args) {
int num = 30;
BigInteger factorial = BigInteger.ONE;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
Output
Factorial of 30 = 265252859812191058636308480000000
Here, instead of long, we use BigInteger variable factorial.
Since, * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be casted to BigInteger for multiplication.
Likewise, we can also use a while loop to solve this problem.
Example 3: Find Factorial of a number using while loop
public class Factorial {
public static void main(String[] args) {
int num = 5, i = 1;
long factorial = 1;
while(i <= num)
{
factorial *= i;
i++;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}
Output
Factorial of 5 = 120
In the above program, unlike a for loop, we have to increment the value of i inside the body of the loop.
Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iteration (upto num) is known.
Visit this page to learn to find factorial of a number using recursion.
Java Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
To understand this example, you should have the knowledge of the following Java programming topics:
Java Methods
Java for Loop
Java if...else Statement
Example: Represent a number as Sum of Two Prime Numbers
public class Main {
public static void main(String[] args) {
int number = 34;
boolean flag = false;
for (int i = 2; i <= number / 2; ++i) {
// condition for i to be a prime number
if (checkPrime(i)) {
// condition for n-i to be a prime number
if (checkPrime(number - i)) {
// n = primeNumber1 + primeNumber2
System.out.printf("%d = %d + %d\n", number, i, number - i);
flag = true;
}
}
}
if (!flag)
System.out.println(number + " cannot be expressed as the sum of two prime numbers.");
}
// Function to check prime number
static boolean checkPrime(int num) {
boolean isPrime = true;
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
}
Run Code
Output
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
In the above example, we have created the checkPrime() method to find whether a number is prime or not. The method returns true if the passed number is prime.
Here, we have a number 34. The program tries to check if 34 can be represented as the sum of two prime numbers.
Working of Program
First, we run a for loop from i = 2 to number / 2.
Inside the for loop, we used two if statements. The first statement checks if i is prime or not.
If true, the second if statement checks if number - i is prime or not. This is because the sum of i and number - i is equal to number.
If the second statement is also true, then we can say the number 34 is a valid sum of two prime numbers.
// Java Program to Check if Given Integer is Odd or Even
// Using Brute Forcew Approach
// Importing required classes
import java.io.*;
import java.util.Scanner;
// Main class
class GFG {
// Main Driver Method
public static void main(String[] args)
{
// Declaring and initializing integer variable
int num = 10;
// Checking if number is even or odd number
// via remainder
if (num % 2 == 0) {
// If remainder is zero then this number is even
System.out.println("Entered Number is Even");
}
else {
// If remainder is not zero then this number is
// odd
System.out.println("Entered Number is Odd");
}
}
}
// Java Program to find even sum of
// fibonacci Series Till number N
import java.io.*;
class geeksforgeeks {
// Computing the value of first fibonacci series
// and storing the sum of even indexed numbers
static int Fib_Even_Sum(int N)
{
if (N <= 0)
return 0;
int fib[] = new int[2 * N + 1];
fib[0] = 0;
fib[1] = 1;
// Initializing the sum
int s = 0;
// Adding remaining numbers
for (int j = 2; j <= 2 * N; j++) {
fib[j] = fib[j - 1] + fib[j - 2];
// Only considering even indexes
if (j % 2 == 0)
s += fib[j];
}
return s;
}
// The Driver code
public static void main(String[] args)
{
int N = 11;
// Prints the sum of even-indexed numbers
System.out.println(
"Even sum of fibonacci series till number " + N
+ " is: " + +Fib_Even_Sum(N));
}
}
It can be clearly seen that the required sum can be obtained thus:
2 ( F2 + F4 + F6 +………+ F2n ) = (F1 + F2 + F3 + F4 +………+ F2n) – (F1 – F2 + F3 – F4 +………+ F2n)
Now the first term can be obtained if we put 2n instead of n in the formula given here.
Thus F1 + F2 + F3 + F4 +………+ F2n = F2n+2 – 1.
The second term can also be found if we put 2n instead of n in the formula given here
Thus, F1 – F2 + F3 – F4 +………- F2n = 1 + (-1)2n+1F2n-1 = 1 – F2n-1.
So, 2 ( F2 + F4 + F6 +………+ F2n)
= F2n+2 – 1 – 1 + F2n-1
= F2n+2 + F2n-1 – 2
= F2n + F2n+1 + F2n+1 – F2n – 2
= 2 ( F2n+1 -1)
Hence, ( F2 + F4 + F6 +………+ F2n) = F2n+1 -1 .
// Java Program to find even indexed
// Fibonacci Sum in O(Log n) time.
class GFG {
static int MAX = 1000;
// Create an array for memoization
static int f[] = new int[MAX];
// Returns n'th Fibonacci number
// using table f[]
static int fib(int n)
{
// Base cases
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return (f[n] = 1);
}
// If fib(n) is already computed
if (f[n] == 1) {
return f[n];
}
int k = (n % 2 == 1) ? (n + 1) / 2 : n / 2;
// Applying above formula [Note value n&1 is 1
// if n is odd, else 0].
f[n] = (n % 2 == 1)
? (fib(k) * fib(k)
+ fib(k - 1) * fib(k - 1))
: (2 * fib(k - 1) + fib(k)) * fib(k);
return f[n];
}
// Computes value of even-indexed Fibonacci Sum
static int calculateEvenSum(int n)
{
return (fib(2 * n + 1) - 1);
}
// Driver program to test above function
public static void main(String[] args)
{
// Get n
int n = 11;
// Find the alternating sum
System.out.println(
"Even indexed Fibonacci Sum upto " + n
+ " terms: " + calculateEvenSum(n));
}
}
SCREEN 13
z = 1 / 100
FOR i = 0 TO 255
PALETTE i, INT(i / 4) + INT(i / 4) * 256 + INT(i / 4) * 65536
NEXT
DO
y = 1
dy = 0
ox = 0: oy = 1
FOR x = 1 TO 430
IF y > 0 THEN dy = dy - 1 / 4000
IF y < 0 THEN dy = dy + z
y = y + dy
a = POINT(x, 100 + y * 50)
a = a + 1
IF a > 255 THEN a = 255
PSET (x, 100 + y * 50), a
NEXT
z = z - 1 / 10000
LOOP
DIM bodyx(70)
DIM bodyy(70)
DIM bodyvx(70)
DIM bodyvy(70)
DIM obodyx(70)
DIM obodyy(70)
RANDOMIZE TIMER
bodies = 30
FOR i = 1 TO bodies
bodyx(i) = 620 * RND + 10
bodyy(i) = 400 * RND + 30
bodyvx(i) = RND - .5
bodyvy(i) = RND - .5
NEXT
SCREEN 12
PRINT "...."
WHILE INKEY$ = "": WEND
CLS
DO
' apply gravity
FOR i = 1 TO bodies
bodyvy(i) = bodyvy(i) + .001
NEXT
' adjust distances
FOR i = 1 TO bodies
FOR j = 1 TO bodies
IF i <> j THEN
centx = (bodyx(i) + bodyx(j)) * .5
centy = (bodyy(i) + bodyy(j)) * .5
distx = (bodyx(i) - bodyx(j)) / 2
disty = (bodyy(i) - bodyy(j)) / 2
distf = SQR(distx * distx + disty * disty)
mx = distx / distf
my = disty / distf
bodyvx(i) = bodyvx(i) - mx * (distf - 50) / 100
bodyvy(i) = bodyvy(i) - my * (distf - 50) / 100
END IF
NEXT
NEXT
' collide with ground
FOR i = 1 TO bodies
IF bodyy(i) + bodyvy(i) > 440 OR bodyy(i) + bodyvy(i) < 5 THEN
bodyvy(i) = -bodyvy(i) * 0!
bodyvx(i) = bodyvx(i) * 0!
END IF
IF bodyx(i) + bodyvx(i) > 625 OR bodyx(i) + bodyvx(i) < 15 THEN
bodyvx(i) = -bodyvx(i) * 0!
bodyvy(i) = bodyvy(i) * 0!
END IF
NEXT
' move bodies
FOR i = 1 TO bodies
obodyx(i) = bodyx(i)
obodyy(i) = bodyy(i)
bodyx(i) = bodyx(i) + bodyvx(i)
bodyy(i) = bodyy(i) + bodyvy(i)
NEXT
' clear/draw
q = (q + 1) MOD 16
FOR i = 1 TO bodies
COLOR 0
CIRCLE (obodyx(i), obodyy(i)), 4
COLOR 15
CIRCLE (bodyx(i), bodyy(i)), 4
'COLOR q
'LINE (bodyx(i), bodyy(i))-(bodyx(i) + bodyvx(i) * 30, bodyy(i) + bodyvy(i) * 30)
NEXT
COLOR 2
LINE (obodyx(1), obodyy(1))-(bodyx(1), bodyy(1))
'FOR i = 1 TO bodies - 1
' FOR j = i + 1 TO bodies
' COLOR 0
' LINE (obodyx(i), obodyy(i))-(obodyx(j), obodyy(j))
' COLOR 2
' LINE (bodyx(i), bodyy(i))-(bodyx(j), bodyy(j))
' NEXT
'NEXT
LOOP
;---------------------------------------------------------------------------
; start
;---------------------------------------------------------------------------
start
desc
msg "It's a room."
objects
start/key
start/door
start/key
id "key"
desc
msg "It's a key."
actions
use door
ifn start/door.flags.locked
msg "The door isn't locked."
if start/door.flags.locked
msg "The lock on the door goes 'click'."
set start/door.flags.locked false
examine
msg "It is shiny."
start/door
id "door"
desc
msg "You see a door."
flags
locked true
open false
actions
open
if start/door.flags.locked
msg "It is locked."
ifn start/door.flags.locked
msg "The door opens."
close
ifn start/door.flags.open
msg "It is already closed."
if start/door.flags.open
msg "The door closes."
go
if start/door.flags.open
goto end
ifn start/door.flags.open
msg "The door is closed."
examine
msg "It looks just like a door."
;---------------------------------------------------------------------------
; end
;---------------------------------------------------------------------------
end
desc
"Congratimafations! Another room."
objects
start/door
macroScript ExportCamera category:"Cameras" toolTip:"Blech!" Icon:#("Cameras",2)
(
filename = maxFileName
flen = findString filename ".max"
filename = substring filename 1 (flen-1)
sname = filename
filename = maxFilePath + filename + ".piper3d"
deletefile filename
out_file = createfile filename
format ";------------------------------------------------------------\n" to:out_file
format "; Piper 3D scene file\n" to:out_file
format ";\n" to:out_file
format "; Scene: % \n" sname to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_begin\n" sname to:out_file
format "\n" to:out_file
animend = animationRange.end as string
animend = substring animend 1 (findString animend "f"-1)
format " dc.w % ; no. frames\n" animend to:out_file
format " dc.w % ; no. objects\n" objects.count to:out_file
faces = 0
vertices = 0
for o in objects do (
if classOf o == Editable_Mesh then (
faces += o.numfaces
vertices += o.numverts
)
)
format " dc.w % ; no. vertices\n" vertices to:out_file
format " dc.w % ; no. faces\n" faces to:out_file
format "\n" to:out_file
format " dc.w 0 ; current frame\n" to:out_file
format "\n" to:out_file
format " dc.l %_vtx ; begin vertices\n" sname sname to:out_file
format " dc.l %_fcs ; begin fæces\n" sname sname to:out_file
format " dc.l %_mtx ; begin matrices\n" sname sname to:out_file
format " dc.l 0 ; begin vertex normals\n" to:out_file
format "\n" to:out_file
format " dc.w 0 ; init flag\n" to:out_file
format "\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "; Vertex groups\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_vtx\n" sname to:out_file
format "\n" to:out_file
for i=1 to objects.count do (
format "; group %: %\n" (i-1) objects[i].name to:out_file
format "\n" to:out_file
if classOf objects[i] == Editable_Mesh then (
obimat = (inverse objects[i].transform)
themesh = snapshotAsMesh objects[i]
format " dc.w % ; no. vertices\n" themesh.numverts to:out_file
for j=1 to themesh.numverts do (
v = (getVert themesh j) * obimat
vxs = formatf v.x 6
vys = formatf v.y 6
vzs = formatf v.z 6
format " dc.s %,%,%\n" vxs vys vzs to:out_file
)
) else (
format " dc.w 0 ; not a mesh\n" to:out_file
)
format "\n" to:out_file
)
format ";------------------------------------------------------------\n" to:out_file
format "; Fæces\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_fcs\n" sname to:out_file
format "\n" to:out_file
voff = 0
for i=1 to objects.count do (
format "; group %: %\n" (i-1) objects[i].name to:out_file
format "\n" to:out_file
if classOf objects[i] == Editable_Mesh then (
themesh = snapshotAsMesh objects[i]
for j=1 to themesh.numfaces do (
f = getFace themesh j
format " dc.w %,%,%\n" (int (f.x-1+voff)) (int (f.y-1+voff)) (int (f.z-1+voff)) to:out_file
smat = objects[i].material
mattype = "0"
u1 = 0
v1 = 0
u2 = 0
v2 = 0
u3 = 0
v3 = 0
if smat == undefined then (
matname = "0"
) else (
if getNumSubMtls smat == 0 then (
mat = smat
) else (
matid = getFaceMatID themesh j
mat = smat.MaterialList[matid]
)
matname = (int mat.diffuse.r)*256*256 + (int mat.diffuse.g)*256 + (int mat.diffuse.b)
dmap = mat.diffuseMap
if dmap != undefined then (
mattype = "1"
matname = dmap.filename
fntokens = filterString matname "\\"
matname = fntokens[fntokens.count]
fntokens = filterString matname "."
matname = fntokens[1]
fntokens = filterString matname "-"
matname = ""
for k=1 to fntokens.count do (
matname = matname + fntokens[k]
if k < fntokens.count then matname=matname+"m"
)
matname = sname + "_" + matname + "+1024+14"
tverts = getTVFace theMesh j
u1 = (int (getTVert theMesh tverts[1] * 65535).x)
v1 = 65535 - (int (getTVert theMesh tverts[1] * 65535).y)
u2 = (int (getTVert theMesh tverts[2] * 65535).x)
v2 = 65536 - (int (getTVert theMesh tverts[2] * 65535).y)
macroScript ExportCamera category:"Cameras" toolTip:"Blech!" Icon:#("Cameras",2)
(
filename = maxFileName
flen = findString filename ".max"
filename = substring filename 1 (flen-1)
sname = filename
filename = maxFilePath + filename + ".piper3d"
deletefile filename
out_file = createfile filename
format ";------------------------------------------------------------\n" to:out_file
format "; Piper 3D scene file\n" to:out_file
format ";\n" to:out_file
format "; Scene: % \n" sname to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_begin\n" sname to:out_file
format "\n" to:out_file
animend = animationRange.end as string
animend = substring animend 1 (findString animend "f"-1)
format " dc.w % ; no. frames\n" animend to:out_file
format " dc.w % ; no. objects\n" objects.count to:out_file
faces = 0
vertices = 0
for o in objects do (
if classOf o == Editable_Mesh then (
faces += o.numfaces
vertices += o.numverts
)
)
format " dc.w % ; no. vertices\n" vertices to:out_file
format " dc.w % ; no. faces\n" faces to:out_file
format "\n" to:out_file
format " dc.w 0 ; current frame\n" to:out_file
format "\n" to:out_file
format " dc.l %_vtx ; begin vertices\n" sname sname to:out_file
format " dc.l %_fcs ; begin fæces\n" sname sname to:out_file
format " dc.l %_mtx ; begin matrices\n" sname sname to:out_file
format " dc.l 0 ; begin vertex normals\n" to:out_file
format "\n" to:out_file
format " dc.w 0 ; init flag\n" to:out_file
format "\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "; Vertex groups\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_vtx\n" sname to:out_file
format "\n" to:out_file
for i=1 to objects.count do (
format "; group %: %\n" (i-1) objects[i].name to:out_file
format "\n" to:out_file
if classOf objects[i] == Editable_Mesh then (
obimat = (inverse objects[i].transform)
themesh = snapshotAsMesh objects[i]
format " dc.w % ; no. vertices\n" themesh.numverts to:out_file
for j=1 to themesh.numverts do (
v = (getVert themesh j) * obimat
vxs = formatf v.x 6
vys = formatf v.y 6
vzs = formatf v.z 6
format " dc.s %,%,%\n" vxs vys vzs to:out_file
)
) else (
format " dc.w 0 ; not a mesh\n" to:out_file
)
format "\n" to:out_file
)
format ";------------------------------------------------------------\n" to:out_file
format "; Fæces\n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_fcs\n" sname to:out_file
format "\n" to:out_file
voff = 0
for i=1 to objects.count do (
format "; group %: %\n" (i-1) objects[i].name to:out_file
format "\n" to:out_file
if classOf objects[i] == Editable_Mesh then (
themesh = snapshotAsMesh objects[i]
for j=1 to themesh.numfaces do (
f = getFace themesh j
format " dc.w %,%,%\n" (int (f.x-1+voff)) (int (f.y-1+voff)) (int (f.z-1+voff)) to:out_file
smat = objects[i].material
mattype = "0"
u1 = 0
v1 = 0
u2 = 0
v2 = 0
u3 = 0
v3 = 0
if smat == undefined then (
matname = "0"
) else (
if getNumSubMtls smat == 0 then (
mat = smat
) else (
matid = getFaceMatID themesh j
mat = smat.MaterialList[matid]
)
matname = (int mat.diffuse.r)*256*256 + (int mat.diffuse.g)*256 + (int mat.diffuse.b)
dmap = mat.diffuseMap
if dmap != undefined then (
mattype = "1"
matname = dmap.filename
fntokens = filterString matname "\\"
matname = fntokens[fntokens.count]
fntokens = filterString matname "."
matname = fntokens[1]
fntokens = filterString matname "-"
matname = ""
for k=1 to fntokens.count do (
matname = matname + fntokens[k]
if k < fntokens.count then matname=matname+"m"
)
matname = sname + "_" + matname + "+1024+14"
tverts = getTVFace theMesh j
u1 = (int (getTVert theMesh tverts[1] * 65535).x)
v1 = 65535 - (int (getTVert theMesh tverts[1] * 65535).y)
u2 = (int (getTVert theMesh tverts[2] * 65535).x)
v2 = 65536 - (int (getTVert theMesh tverts[2] * 65535).y)
u3 = (int (getTVert theMesh tverts[3] * 65535).x)
v3 = 65536 - (int (getTVert theMesh tverts[3] * 65535).y)
if u1 > 65535 then u1 = 65535
if v1 > 65535 then v1 = 65535
if u2 > 65535 then u2 = 65535
if v2 > 65535 then v2 = 65535
if u3 > 65535 then u3 = 65535
if v3 > 65535 then v3 = 65535
/*
if u1 < 0 then u1 = 0
if v1 < 0 then v1 = 0
if u2 < 0 then u2 = 0
if v2 < 0 then v2 = 0
if u3 < 0 then u3 = 0
if v3 < 0 then v3 = 0
*/
if mat.opacityMap != undefined then (
mattype = "2"
)
)
)
format " dc.w %\n" mattype to:out_file
format " dc.l %\n" matname to:out_file
format " dc.w %,%,%,%,%,%\n" u1 v1 u2 v2 u3 v3 to:out_file
)
format "\n" to:out_file
voff += themesh.numverts
)
)
format ";------------------------------------------------------------\n" to:out_file
format "; \n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_mtx\n" sname to:out_file
format "\n" to:out_file
for i = animationRange.start to animationRange.end do (
sliderTime=i
format "; index %\n" i to:out_file
format "\n" to:out_file
for j = 1 to objects.count do (
o=objects[j]
vpm=getViewTM()
tm=o.transform*vpm
tm1=tm.row1
tm2=tm.row2
tm3=tm.row3
tm4=tm.row4
tm11=formatf tm1.x 6
tm12=formatf tm1.y 6
tm13=formatf tm1.z 6
tm21=formatf tm2.x 6
tm22=formatf tm2.y 6
tm23=formatf tm2.z 6
tm31=formatf tm3.x 6
tm32=formatf tm3.y 6
tm33=formatf tm3.z 6
tm41=formatf tm4.x 6
tm42=formatf tm4.y 6
tm43=formatf tm4.z 6
format " dc.s %,%,%\n" tm11 tm12 tm13 to:out_file
format " dc.s %,%,%\n" tm21 tm22 tm23 to:out_file
format " dc.s %,%,%\n" tm31 tm32 tm33 to:out_file
format " dc.s %,%,%\n" tm41 tm42 tm43 to:out_file
format "\n" to:out_file
)
)
close out_file
shelllaunch "notepad.exe" filename
)
-- theend u3 = (int (getTVert theMesh tverts[3] * 65535).x)
v3 = 65536 - (int (getTVert theMesh tverts[3] * 65535).y)
if u1 > 65535 then u1 = 65535
if v1 > 65535 then v1 = 65535
if u2 > 65535 then u2 = 65535
if v2 > 65535 then v2 = 65535
if u3 > 65535 then u3 = 65535
if v3 > 65535 then v3 = 65535
/*
if u1 < 0 then u1 = 0
if v1 < 0 then v1 = 0
if u2 < 0 then u2 = 0
if v2 < 0 then v2 = 0
if u3 < 0 then u3 = 0
if v3 < 0 then v3 = 0
*/
if mat.opacityMap != undefined then (
mattype = "2"
)
)
)
format " dc.w %\n" mattype to:out_file
format " dc.l %\n" matname to:out_file
format " dc.w %,%,%,%,%,%\n" u1 v1 u2 v2 u3 v3 to:out_file
)
format "\n" to:out_file
voff += themesh.numverts
)
)
format ";------------------------------------------------------------\n" to:out_file
format "; \n" to:out_file
format ";------------------------------------------------------------\n" to:out_file
format "\n" to:out_file
format "%_mtx\n" sname to:out_file
format "\n" to:out_file
for i = animationRange.start to animationRange.end do (
sliderTime=i
format "; index %\n" i to:out_file
format "\n" to:out_file
for j = 1 to objects.count do (
o=objects[j]
vpm=getViewTM()
tm=o.transform*vpm
tm1=tm.row1
tm2=tm.row2
tm3=tm.row3
tm4=tm.row4
tm11=formatf tm1.x 6
tm12=formatf tm1.y 6
tm13=formatf tm1.z 6
tm21=formatf tm2.x 6
tm22=formatf tm2.y 6
tm23=formatf tm2.z 6
tm31=formatf tm3.x 6
tm32=formatf tm3.y 6
tm33=formatf tm3.z 6
tm41=formatf tm4.x 6
tm42=formatf tm4.y 6
tm43=formatf tm4.z 6
format " dc.s %,%,%\n" tm11 tm12 tm13 to:out_file
format " dc.s %,%,%\n" tm21 tm22 tm23 to:out_file
format " dc.s %,%,%\n" tm31 tm32 tm33 to:out_file
format " dc.s %,%,%\n" tm41 tm42 tm43 to:out_file
format "\n" to:out_file
)
)
close out_file
shelllaunch "notepad.exe" filename
)
-- theend
void DS3231::setDateTime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second)
{
Wire.beginTransmission(DS3231_ADDRESS);
#if ARDUINO >= 100
Wire.write(DS3231_REG_TIME);
#else
Wire.send(DS3231_REG_TIME);
#endif
#if ARDUINO >= 100
Wire.write(dec2bcd(second));
Wire.write(dec2bcd(minute));
Wire.write(dec2bcd(hour));
Wire.write(dec2bcd(dow(year, month, day)));
Wire.write(dec2bcd(day));
Wire.write(dec2bcd(month));
Wire.write(dec2bcd(year-2000));
#else
Wire.send(dec2bcd(second));
Wire.send(dec2bcd(minute));
Wire.send(dec2bcd(hour));
Wire.send(dec2bcd(dow(year, month, day)));
Wire.send(dec2bcd(day));
Wire.send(dec2bcd(month));
Wire.send(dec2bcd(year-2000));
#endif
#if ARDUINO >= 100
Wire.write(DS3231_REG_TIME);
#else
Wire.send(DS3231_REG_TIME);
#endif
Wire.endTransmission();
}
void DS3231::setDateTime(uint32_t t)
{
t -= 946681200;
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
second = t % 60;
t /= 60;
minute = t % 60;
t /= 60;
hour = t % 24;
uint16_t days = t / 24;
uint8_t leap;
for (year = 0; ; ++year)
{
leap = year % 4 == 0;
if (days < 365 + leap)
{
break;
}
days -= 365 + leap;
}
for (month = 1; ; ++month)
{
uint8_t daysPerMonth = pgm_read_byte(daysArray + month - 1);
if (leap && month == 2)
{
++daysPerMonth;
}
if (days < daysPerMonth)
{
break;
}
days -= daysPerMonth;
}
day = days + 1;
setDateTime(year+2000, month, day, hour, minute, second);
}
void DS3231::setDateTime(const char* date, const char* time)
{
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
year = conv2d(date + 9);
switch (date[0])
{
case 'J': month = date[1] == 'a' ? 1 : month = date[2] == 'n' ? 6 : 7; break;
case 'F': month = 2; break;
case 'A': month = date[2] == 'r' ? 4 : 8; break;
case 'M': month = date[2] == 'r' ? 3 : 5; break;
case 'S': month = 9; break;
case 'O': month = 10; break;
case 'N': month = 11; break;
case 'D': month = 12; break;
}
day = conv2d(date + 4);
hour = conv2d(time);
minute = conv2d(time + 3);
second = conv2d(time + 6);
setDateTime(year+2000, month, day, hour, minute, second);
}
char* DS3231::dateFormat(const char* dateFormat, RTCDateTime dt)
{
char buffer[255];
buffer[0] = 0;
char helper[11];
while (*dateFormat != '\0')
{
switch (dateFormat[0])
{
// Day decoder
case 'd':
sprintf(helper, "%02d", dt.day);
strcat(buffer, (const char *)helper);
break;
case 'j':
sprintf(helper, "%d", dt.day);
strcat(buffer, (const char *)helper);
break;
case 'l':
strcat(buffer, (const char *)strDayOfWeek(dt.dayOfWeek));
break;
case 'D':
strncat(buffer, strDayOfWeek(dt.dayOfWeek), 3);
break;
case 'N':
sprintf(helper, "%d", dt.dayOfWeek);
strcat(buffer, (const char *)helper);
break;
case 'w':
sprintf(helper, "%d", (dt.dayOfWeek + 7) % 7);
strcat(buffer, (const char *)helper);
break;
case 'z':
sprintf(helper, "%d", dayInYear(dt.year, dt.month, dt.day)+1);
strcat(buffer, (const char *)helper);
break;
case 'S':
strcat(buffer, (const char *)strDaySufix(dt.day));
break;
// Month decoder
case 'm':
sprintf(helper, "%02d", dt.month);
strcat(buffer, (const char *)helper);
break;
case 'n':
sprintf(helper, "%d", dt.month);
strcat(buffer, (const char *)helper);
break;
case 'F':
strcat(buffer, (const char *)strMonth(dt.month));
break;
case 'M':
strncat(buffer, (const char *)strMonth(dt.month), 3);
break;
case 't':
sprintf(helper, "%d", daysInMonth(dt.year, dt.month));
strcat(buffer, (const char *)helper);
break;
// Year decoder
case 'Y':
sprintf(helper, "%d", dt.year);
strcat(buffer, (const char *)helper);
break;
case 'y': sprintf(helper, "%02d", dt.year-2000);
strcat(buffer, (const char *)helper);
break;
case 'L':
sprintf(helper, "%d", isLeapYear(dt.year));
strcat(buffer, (const char *)helper);
break;
// Hour decoder
case 'H':
sprintf(helper, "%02d", dt.hour);
strcat(buffer, (const char *)helper);
break;
case 'G':
sprintf(helper, "%d", dt.hour);
strcat(buffer, (const char *)helper);
break;
case 'h':
sprintf(helper, "%02d", hour12(dt.hour));
strcat(buffer, (const char *)helper);
break;
case 'g':
sprintf(helper, "%d", hour12(dt.hour));
strcat(buffer, (const char *)helper);
break;
case 'A':
strcat(buffer, (const char *)strAmPm(dt.hour, true));
break;
case 'a':
strcat(buffer, (const char *)strAmPm(dt.hour, false));
break;
// Minute decoder
case 'i':
sprintf(helper, "%02d", dt.minute);
strcat(buffer, (const char *)helper);
break;
// Second decoder
case 's':
sprintf(helper, "%02d", dt.second);
strcat(buffer, (const char *)helper);
break;
// Misc decoder
case 'U':
sprintf(helper, "%lu", dt.unixtime);
strcat(buffer, (const char *)helper);
break;
default:
strncat(buffer, dateFormat, 1);
break;
}
dateFormat++;
}
return buffer;
}
char* DS3231::dateFormat(const char* dateFormat, RTCAlarmTime dt)
{
char buffer[255];
buffer[0] = 0;
char helper[11];
while (*dateFormat != '\0')
{
switch (dateFormat[0])
{
// Day decoder
case 'd':
sprintf(helper, "%02d", dt.day);
strcat(buffer, (const char *)helper);
break;
case 'j':
sprintf(helper, "%d", dt.day);
strcat(buffer, (const char *)helper);
break;
case 'l':
strcat(buffer, (const char *)strDayOfWeek(dt.day));
break;
case 'D':
strncat(buffer, strDayOfWeek(dt.day), 3);
break;
case 'N':
sprintf(helper, "%d", dt.day);
strcat(buffer, (const char *)helper);
break;
case 'w':
sprintf(helper, "%d", (dt.day + 7) % 7);
strcat(buffer, (const char *)helper);
break;
case 'S':
strcat(buffer, (const char *)strDaySufix(dt.day));
break;
// Hour decoder
case 'H':
sprintf(helper, "%02d", dt.hour);
strcat(buffer, (const char *)helper);
break;
case 'G':
sprintf(helper, "%d", dt.hour);
strcat(buffer, (const char *)helper);
break;
case 'h':
sprintf(helper, "%02d", hour12(dt.hour));
strcat(buffer, (const char *)helper);
break;
case 'g':
sprintf(helper, "%d", hour12(dt.hour));
strcat(buffer, (const char *)helper);
break;
case 'A':
strcat(buffer, (const char *)strAmPm(dt.hour, true));
break;
case 'a':
strcat(buffer, (const char *)strAmPm(dt.hour, false));
break;
// Minute decoder
case 'i':
sprintf(helper, "%02d", dt.minute);
strcat(buffer, (const char *)helper);
break;
// Second decoder
case 's':
sprintf(helper, "%02d", dt.second);
strcat(buffer, (const char *)helper);
break;
default:
strncat(buffer, dateFormat, 1);
break;
}
dateFormat++;
}
return buffer;
}
RTCDateTime DS3231::getDateTime(void)
{
int values[7];
Wire.beginTransmission(DS3231_ADDRESS);
#if ARDUINO >= 100
Wire.write(DS3231_REG_TIME);
#else
Wire.send(DS3231_REG_TIME);
#endif
Wire.endTransmission();
Wire.requestFrom(DS3231_ADDRESS, 7);
while(!Wire.available()) {};
for (int i = 6; i >= 0; i--)
{
#if ARDUINO >= 100
values[i] = bcd2dec(Wire.read());
#else
values[i] = bcd2dec(Wire.receive());
#endif
}
Wire.endTransmission();
t.year = values[0] + 2000;
t.month = values[1];
t.day = values[2];
t.dayOfWeek = values[3];
t.hour = values[4];
t.minute = values[5];
t.second = values[6];
t.unixtime = unixtime();
return t;
}
uint8_t DS3231::isReady(void)
{
return true;
}
void DS3231::enableOutput(bool enabled)
{
uint8_t value;
value = readRegister8(DS3231_REG_CONTROL);
value &= 0b11111011;
value |= (!enabled << 2);
writeRegister8(DS3231_REG_CONTROL, value);
}
void DS3231::setBattery(bool timeBattery, bool squareBattery)
{
uint8_t value;
value = readRegister8(DS3231_REG_CONTROL);
if (squareBattery)
{
value |= 0b01000000;
} else
{
value &= 0b10111111;
}
if (timeBattery)
{
value &= 0b01111011;
} else
{
value |= 0b10000000;
}
writeRegister8(DS3231_REG_CONTROL, value);
}
bool DS3231::isOutput(void)
{
uint8_t value;
value = readRegister8(DS3231_REG_CONTROL);
value &= 0b00000100;
value >>= 2;
return !value;
}
void DS3231::setOutput(DS3231_sqw_t mode)
{
uint8_t value;
value = readRegister8(DS3231_REG_CONTROL);
value &= 0b11100111;
value |= (mode << 3);
writeRegister8(DS3231_REG_CONTROL, value);
}
DS3231_sqw_t DS3231::getOutput(void)
{
uint8_t value;
value = readRegister8(DS3231_REG_CONTROL);
value &= 0b00011000;
value >>= 3;
return (DS3231_sqw_t)value;
}
void DS3231::enable32kHz(bool enabled)
{
uint8_t value;
value = readRegister8(DS3231_REG_STATUS);
value &= 0b11110111;
value |= (enabled << 3);
writeRegister8(DS3231_REG_STATUS, value);
}
bool DS3231::is32kHz(void)
{
uint8_t value;
value = readRegister8(DS3231_REG_STATUS);
value &= 0b00001000;
value >>= 3;
return value;
}
#ifndef DS3231_h
#define DS3231_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define DS3231_ADDRESS (0x68)
#define DS3231_REG_TIME (0x00)
#define DS3231_REG_ALARM_1 (0x07)
#define DS3231_REG_ALARM_2 (0x0B)
#define DS3231_REG_CONTROL (0x0E)
#define DS3231_REG_STATUS (0x0F)
#define DS3231_REG_TEMPERATURE (0x11)
#ifndef RTCDATETIME_STRUCT_H
#define RTCDATETIME_STRUCT_H
struct RTCDateTime
{
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
uint8_t dayOfWeek;
uint32_t unixtime;
};
struct RTCAlarmTime
{
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
};
#endif
typedef enum
{
DS3231_1HZ = 0x00,
DS3231_4096HZ = 0x01,
DS3231_8192HZ = 0x02,
DS3231_32768HZ = 0x03
} DS3231_sqw_t;
typedef enum
{
DS3231_EVERY_SECOND = 0b00001111,
DS3231_MATCH_S = 0b00001110,
DS3231_MATCH_M_S = 0b00001100,
DS3231_MATCH_H_M_S = 0b00001000,
DS3231_MATCH_DT_H_M_S = 0b00000000,
DS3231_MATCH_DY_H_M_S = 0b00010000
} DS3231_alarm1_t;
typedef enum
{
DS3231_EVERY_MINUTE = 0b00001110,
DS3231_MATCH_M = 0b00001100,
DS3231_MATCH_H_M = 0b00001000,
DS3231_MATCH_DT_H_M = 0b00000000,
DS3231_MATCH_DY_H_M = 0b00010000
} DS3231_alarm2_t;
class DS3231
{
public:
bool begin(void);
void setDateTime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second);
void setDateTime(uint32_t t);
void setDateTime(const char* date, const char* time);
RTCDateTime getDateTime(void);
uint8_t isReady(void);
DS3231_sqw_t getOutput(void);
void setOutput(DS3231_sqw_t mode);
void enableOutput(bool enabled);
bool isOutput(void);
void enable32kHz(bool enabled);
bool is32kHz(void);
void forceConversion(void);
float readTemperature(void);
void setAlarm1(uint8_t dydw, uint8_t hour, uint8_t minute, uint8_t second, DS3231_alarm1_t mode, bool armed = true);
RTCAlarmTime getAlarm1(void);
DS3231_alarm1_t getAlarmType1(void);
bool isAlarm1(bool clear = true);
void armAlarm1(bool armed);
bool isArmed1(void);
void clearAlarm1(void);
void setAlarm2(uint8_t dydw, uint8_t hour, uint8_t minute, DS3231_alarm2_t mode, bool armed = true);
RTCAlarmTime getAlarm2(void);
DS3231_alarm2_t getAlarmType2(void);
bool isAlarm2(bool clear = true);
void armAlarm2(bool armed);
bool isArmed2(void);
void clearAlarm2(void);
void setBattery(bool timeBattery, bool squareBattery);
char* dateFormat(const char* dateFormat, RTCDateTime dt);
char* dateFormat(const char* dateFormat, RTCAlarmTime dt);
private:
RTCDateTime t;
char *strDayOfWeek(uint8_t dayOfWeek);
char *strMonth(uint8_t month);
char *strAmPm(uint8_t hour, bool uppercase);
char *strDaySufix(uint8_t day);
uint8_t hour12(uint8_t hour24);
uint8_t bcd2dec(uint8_t bcd);
uint8_t dec2bcd(uint8_t dec);
long time2long(uint16_t days, uint8_t hours, uint8_t minutes, uint8_t seconds);
uint16_t date2days(uint16_t year, uint8_t month, uint8_t day);
uint8_t daysInMonth(uint16_t year, uint8_t month);
uint16_t dayInYear(uint16_t year, uint8_t month, uint8_t day);
bool isLeapYear(uint16_t year);
uint8_t dow(uint16_t y, uint8_t m, uint8_t d);
uint32_t unixtime(void);
uint8_t conv2d(const char* p);
void writeRegister8(uint8_t reg, uint8_t value);
uint8_t readRegister8(uint8_t reg);
};
#endif
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <runner.cuh>
#include <vector>
#define cudaCheck(err) (cudaCheck(err, __FILE__, __LINE__))
const std::string errLogFile = "matrixValidationFailure.txt";
int main(int argc, char **argv) {
if (argc != 2) {
std::cerr << "Please select a kernel (range 0 - 12, 0 for NVIDIA cuBLAS)"
<< std::endl;
exit(EXIT_FAILURE);
}
// get kernel number
int kernel_num = std::stoi(argv[1]);
if (kernel_num < 0 || kernel_num > 12) {
std::cerr << "Please enter a valid kernel number (0-12)" << std::endl;
exit(EXIT_FAILURE);
}
// get environment variable for device
int deviceIdx = 0;
if (getenv("DEVICE") != NULL) {
deviceIdx = atoi(getenv("DEVICE"));
}
cudaCheck(cudaSetDevice(deviceIdx));
printf("Running kernel %d on device %d.\n", kernel_num, deviceIdx);
// print some device info
// CudaDeviceInfo();
// Declare the handle, create the handle, cublasCreate will return a value of
// type cublasStatus_t to determine whether the handle was created
// successfully (the value is 0)
cublasHandle_t handle;
if (cublasCreate(&handle)) {
std::cerr << "Create cublas handle error." << std::endl;
exit(EXIT_FAILURE);
};
// Using cudaEvent for gpu stream timing, cudaEvent is equivalent to
// publishing event tasks in the target stream
float elapsed_time;
cudaEvent_t beg, end;
cudaEventCreate(&beg);
cudaEventCreate(&end);
// cuBLAS FLOPs ceiling is reached at 8192
std::vector<int> SIZE = {128, 256, 512, 1024, 2048, 4096};
long m, n, k, max_size;
max_size = SIZE[SIZE.size() - 1];
std::cout << "Max size: " << max_size << std::endl;
float alpha = 0.5, beta = 3.0; // GEMM input parameters, C=α*AB+β*C
float *A = nullptr, *B = nullptr, *C = nullptr,
*C_ref = nullptr; // host matrices
float *dA = nullptr, *dB = nullptr, *dC = nullptr,
*dC_ref = nullptr; // device matrices
A = (float *)malloc(sizeof(float) * max_size * max_size);
B = (float *)malloc(sizeof(float) * max_size * max_size);
C = (float *)malloc(sizeof(float) * max_size * max_size);
C_ref = (float *)malloc(sizeof(float) * max_size * max_size);
randomize_matrix(A, max_size * max_size);
randomize_matrix(B, max_size * max_size);
randomize_matrix(C, max_size * max_size);
cudaCheck(cudaMalloc((void **)&dA, sizeof(float) * max_size * max_size));
cudaCheck(cudaMalloc((void **)&dB, sizeof(float) * max_size * max_size));
cudaCheck(cudaMalloc((void **)&dC, sizeof(float) * max_size * max_size));
cudaCheck(cudaMalloc((void **)&dC_ref, sizeof(float) * max_size * max_size));
cudaCheck(cudaMemcpy(dA, A, sizeof(float) * max_size * max_size,
cudaMemcpyHostToDevice));
cudaCheck(cudaMemcpy(dB, B, sizeof(float) * max_size * max_size,
cudaMemcpyHostToDevice));
cudaCheck(cudaMemcpy(dC, C, sizeof(float) * max_size * max_size,
cudaMemcpyHostToDevice));
cudaCheck(cudaMemcpy(dC_ref, C, sizeof(float) * max_size * max_size,
cudaMemcpyHostToDevice));
int repeat_times = 50;
for (int size : SIZE) {
m = 32;
n = k = size;
std::cout << "dimensions(m,n,k) " << m << "," << n << "," << k << ", alpha: " << alpha
<< ", beta: " << beta << std::endl;
// Verify the correctness of the calculation, and execute it once before the
// kernel function timing to avoid cold start errors
if (kernel_num != 0) {
run_kernel(0, m, n, k, alpha, dA, dB, beta, dC_ref,
handle); // cuBLAS
run_kernel(kernel_num, m, n, k, alpha, dA, dB, beta, dC,
handle); // Executes the kernel, modifies the result matrix
cudaCheck(cudaDeviceSynchronize());
cudaCheck(cudaGetLastError()); // Check for async errors during kernel run
cudaMemcpy(C, dC, sizeof(float) * m * n, cudaMemcpyDeviceToHost);
cudaMemcpy(C_ref, dC_ref, sizeof(float) * m * n, cudaMemcpyDeviceToHost);
if (!verify_matrix(C_ref, C, m * n)) {
std::cout
<< "Failed to pass the correctness verification against NVIDIA "
"cuBLAS."
<< std::endl;
if (m <= 128) {
std::cout << " Logging faulty output into " << errLogFile << "\n";
std::ofstream fs;
fs.open(errLogFile);
fs << "A:\n";
print_matrix(A, m, n, fs);
fs << "B:\n";
print_matrix(B, m, n, fs);
fs << "C:\n";
print_matrix(C, m, n, fs);
fs << "Should:\n";
print_matrix(C_ref, m, n, fs);
}
exit(EXIT_FAILURE);
}
}
cudaEventRecord(beg);
for (int j = 0; j < repeat_times; j++) {
// We don't reset dC between runs to save time
run_kernel(kernel_num, m, n, k, alpha, dA, dB, beta, dC, handle);
}
cudaEventRecord(end);
cudaEventSynchronize(beg);
cudaEventSynchronize(end);
cudaEventElapsedTime(&elapsed_time, beg, end);
elapsed_time /= 1000.; // Convert to seconds
long flops = 2 * m * n * k;
printf(
"Average elapsed time: (%7.6f) s, performance: (%7.1f) GFLOPS. size: "
"(%ld).\n",
elapsed_time / repeat_times,
(repeat_times * flops * 1e-9) / elapsed_time, m);
fflush(stdout);
// make dC and dC_ref equal again (we modified dC while calling our kernel
// for benchmarking)
cudaCheck(cudaMemcpy(dC, dC_ref, sizeof(float) * m * n,
cudaMemcpyDeviceToDevice));
}
// Free up CPU and GPU space
free(A);
free(B);
free(C);
free(C_ref);
cudaFree(dA);
cudaFree(dB);
cudaFree(dC);
cudaFree(dC_ref);
cublasDestroy(handle);
return 0;
};
#include <cuda_runtime.h>
#include <iostream>
#include <vector>
__global__ void kernel(uint *A, uint *B, int row) {
auto x = threadIdx.x / 4;
auto y = threadIdx.x % 4;
A[x * row + y] = x;
B[x * row + y] = y;
}
int main(int argc, char **argv) {
uint *Xs, *Ys;
uint *Xs_d, *Ys_d;
uint SIZE = 4;
Xs = (uint *)malloc(SIZE * SIZE * sizeof(uint));
Ys = (uint *)malloc(SIZE * SIZE * sizeof(uint));
cudaMalloc((void **)&Xs_d, SIZE * SIZE * sizeof(uint));
cudaMalloc((void **)&Ys_d, SIZE * SIZE * sizeof(uint));
dim3 grid_size(1, 1, 1);
dim3 block_size(4 * 4);
kernel<<<grid_size, block_size>>>(Xs_d, Ys_d, 4);
cudaMemcpy(Xs, Xs_d, SIZE * SIZE * sizeof(uint), cudaMemcpyDeviceToHost);
cudaMemcpy(Ys, Ys_d, SIZE * SIZE * sizeof(uint), cudaMemcpyDeviceToHost);
cudaDeviceSynchronize();
for (int row = 0; row < SIZE; ++row) {
for (int col = 0; col < SIZE; ++col) {
std::cout << "[" << Xs[row * SIZE + col] << "|" << Ys[row * SIZE + col]
<< "] ";
}
std::cout << "\n";
}
cudaFree(Xs_d);
cudaFree(Ys_d);
free(Xs);
free(Ys);
}
name: SGEMM_CUDA
channels:
- conda-forge
dependencies:
- python
- black
- cmake
- matplotlib
- seaborn
- tabulate
.PHONY: all build debug clean profile bench cuobjdump
CMAKE := cmake
BUILD_DIR := build
BENCHMARK_DIR := benchmark_results
all: build
build:
@mkdir -p $(BUILD_DIR)
@cd $(BUILD_DIR) && $(CMAKE) -DCMAKE_BUILD_TYPE=Release ..
@$(MAKE) -C $(BUILD_DIR)
debug:
@mkdir -p $(BUILD_DIR)
@cd $(BUILD_DIR) && $(CMAKE) -DCMAKE_BUILD_TYPE=Debug ..
@$(MAKE) -C $(BUILD_DIR)
clean:
@rm -rf $(BUILD_DIR)
FUNCTION := $$(cuobjdump -symbols build/sgemm | grep -i Warptiling | awk '{print $$NF}')
cuobjdump: build
@cuobjdump -arch sm_86 -sass -fun $(FUNCTION) build/sgemm | c++filt > build/cuobjdump.sass
@cuobjdump -arch sm_86 -ptx -fun $(FUNCTION) build/sgemm | c++filt > build/cuobjdump.ptx
# Usage: make profile KERNEL=<integer> PREFIX=<optional string>
profile: build
@ncu --set full --export $(BENCHMARK_DIR)/$(PREFIX)kernel_$(KERNEL) --force-overwrite $(BUILD_DIR)/sgemm $(KERNEL)
bench: build
@bash gen_benchmark_results.sh
[-0.01, 3.00, 3.01, -2.04, -1.02, -3.02, 0.02, 0.02, 4.02, 4.03, -3.01, -3.04, 0.02, 4.01, 4.02, -4.01, -3.03, 1.01, -4.00, -1.04, -0.02, 3.03, -0.03, -1.04, 3.04, 2.03, 3.03, -1.04, -3.01, -3.04, 4.01, -2.01, 3.02, 2.03, -3.03, 1.00, 0.03, -1.01, -2.00, 4.03, -3.04, 2.02, 1.00, -3.04, 2.02, 2.03, 0.00, -4.02, -3.01, -4.02, -2.03, 1.00, 1.03, -3.01, -2.03, 0.00, 3.03, -4.02, 1.02, -1.02, 4.01, 1.02, 3.00, 1.03, 4.01, -0.03, 1.03, -2.02, -1.01, 2.02, -3.01, -0.04, 4.02, 2.04, -3.03, -2.00, 2.01, 4.04, 1.02, -0.01, 3.00, -2.02, -3.04, 1.03, -3.01, 3.03, -2.03, -4.02, 0.03, 0.00, -4.03, -4.00, -1.00, 2.02, 3.02, -4.01, -0.00, 0.01, 1.03, 4.03, 4.00, -0.04, 4.02, -2.04, 0.02, -2.03, 0.04, -2.01, 2.03, -3.02, 4.03, 3.04, 3.00, -1.03, -0.03, -4.03, -4.00, 4.02, 2.02, -4.00, -4.04, 4.04, -0.00, 1.01, -3.03, -0.03, 1.04, -2.01, -0.00, 3.04, 1.03, 2.04, 4.04, -1.02, 2.03, 0.03, 1.01, -4.04, 1.01, -1.02, -2.03, 3.00, 0.04, -0.00, -0.04, -1.04, 0.02, 3.01, -4.03, 0.01, 3.03, 0.01, 1.03, 3.00, -3.00, 1.04, 0.04, -2.04, -1.00, 0.02, 0.01, -2.01, -4.02, 4.02, -2.01, 2.04, -1.01, 2.03, 2.01, 0.02, 1.02, 4.01, 2.00, 1.02, 3.04, -1.01, -2.04, 3.02, 1.01, 0.04, 1.00, -3.04, 3.03, -2.00, 3.00, -3.01, 4.01, 3.01, 1.02, 0.02, 3.00, -1.00, 4.03, -0.02, 1.03, 1.01, 4.02, 4.02, 1.01, 0.01, 4.04, 2.02, 4.01, 4.04, -1.02, 3.03, 4.04, 3.04, -1.00, -1.02, -3.02, 2.01, -0.02, -1.01, 4.02, 0.03, 4.04, -2.03, -2.04, -2.02, -4.00, -3.03, -0.00, -0.03, 4.02, 2.04, -3.00, 2.04, -1.02, 0.01, -0.00, 3.04, -4.01, -2.01, 2.02, -4.01, 3.01, -2.03, 4.04, 3.01, -4.02, -2.00, -4.01, 3.03, -0.01, 2.02, -4.00, 3.03, 1.04, 2.02, -3.03, 2.01, 2.02, -0.02, -4.02, -2.00;
-1.04, -1.04, -2.00, -0.04, -1.00, -0.04, 0.04, -2.04, -2.04, -2.01, 2.00, 1.01, -4.03, 4.00, -0.02, -3.02, 1.04, -4.01, -1.00, -1.04, 4.03, -2.00, 3.04, -2.00, 1.00, 1.01, 1.02, -2.04, 1.00, 2.03, 0.03, 1.02, 3.00, -3.03, 0.01, -0.04, -3.03, -1.00, 3.03, -2.03, 0.03, 2.02, -4.00, -0.00, 3.00, 2.02, -3.03, -2.04, -2.04, -3.01, 1.04, -2.01, -2.01, 0.03, 1.04, 4.03, 2.01, 0.01, 4.03, 0.03, -4.04, -4.03, -4.00, -0.03, -0.01, 4.00, -2.00, 2.00, 3.01, 0.01, -4.00, -2.02, 2.01, 1.03, -4.03, -1.04, -3.02, 2.01, 3.01, 0.01, -1.01, -1.03, -3.02, -4.04, 2.03, 1.02, 1.02, -0.01, -2.02, 4.02, -4.03, -1.01, 1.00, -3.01, -4.01, 4.02, 2.03, 2.01, -0.03, -4.04, 1.00, -3.02, -2.03, 0.03, -3.03, -1.04, -3.01, -2.00, -3.02, -1.01, -2.02, 0.02, -2.01, 4.02, -2.00, -3.01, 4.04, 3.01, 1.02, -2.03, -2.02, -2.02, 2.02, 4.01, 2.00, -3.03, -1.04, -4.03, 0.01, -0.03, -3.00, 4.00, -4.02, -0.01, 4.01, -2.04, 1.03, -3.02, -4.00, -2.00, 4.04, -0.03, 3.02, -1.02, -1.03, -2.01, -0.04, -0.02, 3.02, 0.04, -0.03, 2.00, 0.04, 4.02, -4.03, -0.02, -1.00, -4.00, -2.01, -3.01, 2.01, -4.03, 4.00, 0.02, -1.01, 1.04, 3.00, -0.01, -1.04, 4.04, -3.01, 1.03, 2.02, 1.04, -2.01, -1.04, -2.02, -4.04, -0.00, -0.01, -0.00, -1.01, 0.03, 2.02, 1.04, -4.00, -0.04, 2.03, -2.03, -1.00, -1.02, -3.03, -0.01, -1.03, -2.02, 3.03, -1.03, -3.00, -2.02, 1.00, 0.02, 0.00, 2.01, 0.02, -1.01, -4.02, -1.03, 0.01, -3.00, -3.02, 3.04, -3.04, 0.04, -4.04, -4.02, 1.01, -1.00, -2.02, -3.02, -3.00, -4.01, 2.04, 3.01, 4.01, 2.00, 2.02, 1.00, -3.04, -0.04, -0.03, 2.02, 0.02, -3.00, 4.01, -2.04, 4.03, 2.04, -0.04, -3.00, 0.00, -3.00, -2.00, -3.03, 0.00, 3.04, -3.03, -1.02, -1.02, -0.00, 1.03, 0.01, 2.01, -4.01, -0.01, 4.01, 4.04;
2.02, -3.03, 2.01, -3.02, -2.03, -0.02, -1.01, 3.03, 1.04, -4.00, 2.04, -0.03, 1.00, 4.01, 2.03, -4.00, -2.04, 0.04, 2.00, -4.01, 0.04, -4.01, -1.04, 1.00, 0.02, 0.04, -3.03, -3.03, -1.02, -3.04, 0.04, 4.03, 3.01, 3.04, -0.02, -1.02, 1.02, -3.01, 3.04, 3.02, 2.04, 0.04, -2.02, -3.02, -1.03, 4.01, -1.02, 1.02, -2.00, 0.00, -2.03, -0.03, -2.00, 1.00, -1.04, -0.03, 1.02, -4.03, -1.02, -1.04, -1.03, -0.04, 3.01, 2.04, 2.02, -2.02, -3.03, 1.00, 1.01, -3.04, -3.02, 3.02, 4.02, -1.00, 0.02, 0.00, -1.00, -2.02, -3.00, 3.01, 3.04, 2.02, -4.02, -3.00, 4.02, 2.02, 2.00, -3.04, 4.04, -1.03, -0.01, 1.03, 1.00, 4.00, 2.04, 3.03, -2.01, 0.01, -2.01, 2.04, 0.01, -0.02, -4.01, 0.00, 0.03, -2.03, 1.00, 4.03, -2.02, 0.01, 0.04, -1.04, 1.00, 2.02, -4.02, -3.04, -0.00, 0.01, -3.04, 1.04, -0.01, 0.03, -0.01, 1.00, -0.00, 1.00, -3.02, -0.04, -4.02, 0.03, -3.00, -0.01, 3.01, -3.00, -3.00, 2.03, -0.01, 0.03, 0.02, -0.03, -2.03, -3.04, 4.04, -3.03, 2.03, -4.01, 2.01, 3.02, -2.04, 1.01, -4.03, 4.01, -0.02, 2.02, -4.02, 3.03, -3.00, 0.00, 0.00, -4.01, 4.02, 4.01, 3.01, 1.01, 0.00, 2.00, 0.04, -1.01, 0.01, -4.02, -0.03, -0.02, 3.00, -2.04, 2.04, -1.01, 3.01, -0.02, 2.04, -4.04, -1.04, -1.01, -0.01, 0.04, 0.03, 0.00, 0.00, 2.00, -4.04, -0.00, -0.02, 3.00, 1.00, 2.02, 1.02, -2.02, -3.00, -3.02, 2.03, 0.00, 0.00, -4.01, -4.04, 3.03, -4.00, 1.02, -4.00, -3.03, -0.00, -1.03, 4.03, -0.02, -3.03, 1.02, 1.03, -4.04, 1.04, 3.04, -4.04, -3.02, 0.04, -3.01, 0.04, 0.02, -1.04, 1.03, 1.04, 1.04, 3.03, 1.03, -4.04, 0.04, 3.04, 2.02, -2.03, 4.04, -0.00, -4.03, -3.02, -4.00, -4.02, 1.02, -1.03, 0.00, -3.02, -1.04, 3.04, 2.00, 4.04, -0.00, -4.04, 4.02, 3.03, 3.00, 1.00, 1.01;
3.02, -1.04, 2.00, 4.00, -1.01, 1.00, -0.00, 2.01, -4.04, -2.02, -0.01, -3.04, 4.03, -4.02, -1.00, -2.01, -0.01, 3.00, 3.01, -4.04, -3.01, -4.01, -1.01, -1.00, 1.02, -3.01, 2.04, -1.04, 4.03, -2.04, 3.02, 4.01, -2.02, -0.00, -0.04, 3.02, -2.01, -4.02, -2.03, 2.03, -2.03, -4.03, -4.02, 3.03, 4.00, -2.03, 4.00, 2.02, -4.04, 0.03, 1.03, -2.02, 0.03, -1.01, -1.02, 0.04, -3.00, 2.02, 0.02, 4.04, -3.02, -1.04, 0.02, -0.00, 0.01, -3.03, 4.01, 2.00, 3.00, -3.02, 0.00, -4.03, -1.04, -2.01, -0.02, -1.02, 4.01, 2.00, 4.03, 1.03, 1.04, 4.03, 4.01, 2.03, 1.04, -2.02, -2.01, 4.00, -0.02, 0.03, 2.04, -1.01, 4.00, -1.04, 2.02, -1.00, -3.02, 2.01, 2.03, -1.00, -0.04, -3.01, -3.00, 2.04, -2.03, 1.04, -0.04, 2.02, -4.04, 4.00, -1.02, -0.02, 3.00, -0.03, 2.00, 3.04, -4.04, 2.01, -0.02, 2.01, -2.03, 1.00, 3.01, 0.01, -2.00, 3.00, 1.04, 4.01, -0.02, 4.01, 3.03, 4.01, 2.04, -3.00, -2.04, -2.04, -2.01, 4.02, 3.02, 0.04, -4.04, 2.00, 1.02, -3.03, 2.00, 3.04, 4.04, 0.00, 3.03, 1.01, 4.00, -0.04, 2.03, 3.01, -2.03, 4.01, 3.01, 3.01, 0.01, 4.03, 4.04, -3.04, 4.01, -0.02, -4.04, -3.00, 1.04, -3.02, -2.00, 1.04, 2.00, -2.03, -2.03, -2.00, -2.02, -4.00, 0.01, 2.01, 0.00, -4.01, -4.03, 3.03, 3.02, -2.00, 3.04, 3.03, -1.00, -2.02, 3.02, -1.02, -3.03, 1.03, -4.03, -2.01, 0.04, -1.00, -1.01, 0.00, -4.01, -4.02, 2.03, 3.04, -0.00, -4.02, -3.04, -3.00, 1.04, -4.04, -0.03, 1.04, 0.01, 3.02, 0.04, 3.00, 2.03, -3.03, -3.04, -2.00, -3.03, 0.04, -3.01, 3.04, 0.02, 3.00, -4.03, -0.03, -4.01, 1.00, -3.03, -2.00, 3.04, -0.04, 1.01, 3.04, -0.04, -2.01, -2.00, -1.02, 3.02, -2.04, -3.04, -3.02, -1.03, -2.04, 0.04, 3.02, 1.01, 3.00, 3.03, -2.02, -3.00, 0.00, 3.02, 2.01, 1.03, 4.03;
cmake_minimum_required(VERSION 3.19)
project(NVIDIA_SGEMM_PRACTICE LANGUAGES CXX CUDA)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(CUDA REQUIRED)
# ensure cuda is available
include(CheckLanguage)
check_language(CUDA)
set(CMAKE_CXX_STANDARD 20)
set(CUDA_COMPUTE_CAPABILITY 86)
# in debug mode, add debug symbols to device code
# this disables most optimizations and kills performance
add_compile_options("$<$<AND:$<CONFIG:Debug>,$<COMPILE_LANGUAGE:CUDA>>:-G;-src-in-ptx>")
# add_compile_options("--ptxas-options=-v")
# Configure header file search paths
include_directories(${CUDA_INCLUDE_DIRS})
include_directories(${PROJECT_SOURCE_DIR}/src)
# Configure the source file path to be compiled
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
# generate executable
add_executable(sgemm sgemm.cu ${SRC})
set_target_properties(sgemm PROPERTIES CUDA_ARCHITECTURES ${CUDA_COMPUTE_CAPABILITY})
target_link_libraries(sgemm ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES})
add_executable(cuBLAS_sgemm cuBLAS_sgemm.cu )
set_target_properties(sgemm PROPERTIES CUDA_ARCHITECTURES ${CUDA_COMPUTE_CAPABILITY})
target_link_libraries(cuBLAS_sgemm ${CUDA_LIBRARIES} ${CUDA_CUBLAS_LIBRARIES})
add_executable(simplest_kernel simplest_kernel.cu)
set_target_properties(sgemm PROPERTIES CUDA_ARCHITECTURES ${CUDA_COMPUTE_CAPABILITY})
target_link_libraries(simplest_kernel ${CUDA_LIBRARIES})
import gzip
import random
import tqdm
import numpy as np
import torch
from torch.optim import Adam
from torch.nn import functional as F
from torch.utils.data import DataLoader, Dataset
from simple_hierarchical_transformer import HierarchicalTransformer
# constants
NUM_BATCHES = int(1e5)
BATCH_SIZE = 2
GRADIENT_ACCUMULATE_EVERY = 8
LEARNING_RATE = 1e-4
VALIDATE_EVERY = 100
PRIME_LENGTH = 128
GENERATE_EVERY = 500
SEQ_LEN = 8192
GENERATE_LENGTH = 1024
# helpers
def cycle(loader):
while True:
for data in loader:
yield data
def decode_token(token):
return str(chr(max(32, token)))
def decode_tokens(tokens):
return "".join(list(map(decode_token, tokens)))
# instantiate transformer
model = HierarchicalTransformer(
num_tokens = 256,
dim = 1024,
depth = 8,
seq_len = SEQ_LEN,
use_flash_attn = True,
compress_factor = 32
).cuda()
# prepare enwik8 data
with gzip.open("./data/enwik8.gz") as file:
data = np.frombuffer(file.read(int(95e6)), dtype=np.uint8).copy()
np_train, np_valid = np.split(data, [int(90e6)])
data_train, data_val = torch.from_numpy(np_train), torch.from_numpy(np_valid)
class TextSamplerDataset(Dataset):
def __init__(self, data, seq_len):
super().__init__()
self.data = data
self.seq_len = seq_len
def __getitem__(self, index):
rand_start = torch.randint(0, self.data.size(0) - self.seq_len, (1,))
full_seq = self.data[rand_start : rand_start + self.seq_len + 1].long()
return full_seq.cuda()
def __len__(self):
return self.data.size(0) // self.seq_len
train_dataset = TextSamplerDataset(data_train, SEQ_LEN)
val_dataset = TextSamplerDataset(data_val, SEQ_LEN)
train_loader = cycle(DataLoader(train_dataset, batch_size=BATCH_SIZE))
val_loader = cycle(DataLoader(val_dataset, batch_size=BATCH_SIZE))
# optimizer
optim = Adam(model.parameters(), lr = LEARNING_RATE)
# training
for i in tqdm.tqdm(range(NUM_BATCHES), mininterval = 10.0, desc = "training"):
model.train()
for _ in range(GRADIENT_ACCUMULATE_EVERY):
loss, (ce_loss, recon_loss) = model(next(train_loader), return_loss = True)
loss.backward(loss / GRADIENT_ACCUMULATE_EVERY)
print(f"training loss: {ce_loss.item()}")
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optim.step()
optim.zero_grad()
if i % VALIDATE_EVERY == 0:
model.eval()
with torch.no_grad():
loss, (ce_loss, recon_loss) = model(next(val_loader), return_loss = True)
print(f"validation loss: {ce_loss.item()}")
if i % GENERATE_EVERY == 0:
model.eval()
inp = random.choice(val_dataset)[:PRIME_LENGTH]
prime = decode_tokens(inp)
print(f"%s \n\n %s", (prime, "*" * 100))
sample = model.generate(inp[None, ...], GENERATE_LENGTH)
output_str = decode_tokens(sample[0])
print(output_str, "\n")
{
"version": "1.0",
"truncation": null,
"padding": null,
"added_tokens": [
{
"id": 0,
"content": "<unk>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": true,
"special": true
},
{
"id": 1,
"content": "<s>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": true,
"special": true
},
{
"id": 2,
"content": "</s>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": true,
"special": true
}
],
"normalizer": {
"type": "Sequence",
"normalizers": [
{
"type": "Prepend",
"prepend": "▁"
},
{
"type": "Replace",
"pattern": {
"String": " "
},
"content": "▁"
}
]
},
"pre_tokenizer": null,
"post_processor": {
"type": "TemplateProcessing",
"single": [
{
"SpecialToken": {
"id": "<s>",
"type_id": 0
}
},
{
"Sequence": {
"id": "A",
"type_id": 0
}
}
],
"pair": [
{
"SpecialToken": {
"id": "<s>",
"type_id": 0
}
},
{
"Sequence": {
"id": "A",
"type_id": 0
}
},
{
"SpecialToken": {
"id": "<s>",
"type_id": 1
}
},
{
"Sequence": {
"id": "B",
"type_id": 1
}
}
],
"special_tokens": {
"<s>": {
"id": "<s>",
"ids": [
1
],
"tokens": [
"<s>"
]
}
}
},
"decoder": {
"type": "Sequence",
"decoders": [
{
"type": "Replace",
"pattern": {
"String": "▁"
},
"content": " "
},
{
"type": "ByteFallback"
},
{
"type": "Fuse"
},
{
"type": "Strip",
"content": " ",
"start": 1,
"stop": 0
}
]
}
}
#include "q_gemm.cuh"
#include "util.cuh"
#include "matrix_view.cuh"
#include "../config.h"
// #include <cuda/pipeline>
// #include <mma.h>
#define BLOCK_KN_SIZE 512
#define MAX_GROUPS_IN_BLOCK (BLOCK_KN_SIZE / 32)
#define MAX_COUNT_M 2
#define CLEAR_N_SIZE 256
//#define DEBUG
#include "q_gemm_dq.cuh"
typedef void (*fp_gemm_half_q_half_kernel)
(
const half*,
const uint32_t*,
const uint32_t*,
const half*,
const uint16_t*,
half*,
const int,
const int,
const int,
const int,
const int,
const uint16_t*,
const int,
const int,
const int,
const int,
const int,
const int
);
template <bool first_block, int m_count>
__global__ void gemm_half_q_half_kernel
(
const half* a,
const uint32_t* b_q_weight,
const uint32_t* b_q_scale,
const half* b_q_scale_max,
const uint16_t* b_q_groups,
half* c,
const int size_m,
const int size_n,
const int size_k,
const int groups,
const int groupsize,
const uint16_t* __restrict__ b_q_perm,
const int rows_8,
const int rows_6,
const int rows_5,
const int rows_4,
const int rows_3,
const int rows_2
)
{
MatrixView_half a_(a, size_m, size_k);
MatrixView_half_rw c_(c, size_m, size_n);
MatrixView_q4_row b_q_scale_(b_q_scale, groups, size_n);
int t = threadIdx.x;
// Block
int offset_n = blockIdx.x * BLOCK_KN_SIZE;
int offset_m = blockIdx.y * m_count;
int offset_k = blockIdx.z * BLOCK_KN_SIZE;
int end_n = min(offset_n + BLOCK_KN_SIZE, size_n);
int end_m = min(offset_m + m_count, size_m);
int end_k = min(offset_k + BLOCK_KN_SIZE, size_k);
int n = offset_n + t;
// Preload block_a
__shared__ half block_a[m_count][BLOCK_KN_SIZE];
if (offset_k + t < end_k)
{
for (int m = 0; m < m_count; ++m)
{
const half* a_ptr = a_.item_ptr(offset_m + m, 0);
half* block_a_ptr = block_a[m];
half a0 = a_ptr[b_q_perm[offset_k + t]];
block_a_ptr[t] = a0;
}
}
__syncthreads();
if (n >= size_n) return;
// for (int xs_n = 0; xs_n < size_n - BLOCK_KN_SIZE;
// Advance to subblock
// int sub_offset_k = SUBBLOCK_K_SIZE * threadIdx.y;
// offset_k += sub_offset_k;
// end_k = min(offset_k + SUBBLOCK_K_SIZE, size_k);
// if (threadIdx.y > 0) return;
// int sub_offset_k = 0;
// Find initial group
int group = offset_k / groupsize;
// Preload scales
half scales[MAX_GROUPS_IN_BLOCK];
int groups_in_block = DIVIDE((end_k - offset_k), groupsize);
for (int g = 0; g < groups_in_block; g++)
{
half s = dq_scale(b_q_scale_.item(group + g, n), b_q_scale_max[group + g]);
scales[g] = s;
}
// Find initial q row
int pre_rows_8 = min(rows_8, offset_k);
int pre_rows_6 = offset_k > rows_8 ? min(rows_6, offset_k) - rows_8 : 0;
int pre_rows_5 = offset_k > rows_6 ? min(rows_5, offset_k) - rows_6 : 0;
int pre_rows_4 = offset_k > rows_5 ? min(rows_4, offset_k) - rows_5 : 0;
int pre_rows_3 = offset_k > rows_4 ? min(rows_3, offset_k) - rows_4 : 0;
int pre_rows_2 = offset_k > rows_3 ? min(rows_2, offset_k) - rows_3 : 0;
int qk = 0;
qk += pre_rows_8 / 32 * 8;
qk += pre_rows_6 / 32 * 6;
qk += pre_rows_5 / 32 * 5;
qk += pre_rows_4 / 32 * 4;
qk += pre_rows_3 / 32 * 3;
qk += pre_rows_2 / 32 * 2;
const uint32_t* b_ptr = b_q_weight + qk * size_n + n;
const half* a_ptr = &block_a[0][0];
int a_stride = BLOCK_KN_SIZE;
// const half* a_ptr = a_.item_ptr(offset_m, 0);
// int a_stride = size_k;
half qs_h = scales[0];
int scales_idx = 0;
int nextgroup = offset_k + groupsize;
// Column result
half2 block_c[m_count] = {};
// Dot product over groups
int k = offset_k;
while (k < rows_8 && k < end_k)
{
int end_k_sg = min(min(k + 128, rows_6), end_k);
uint32_t q_0[8], q_1[8];
load_8(b_ptr, size_n, q_0);
qdot_8bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_8bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_8bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_8bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
while (k < rows_6 && k < end_k)
{
int end_k_sg = min(min(k + 128, rows_5), end_k);
uint32_t q_0[6], q_1[6];
load_6(b_ptr, size_n, q_0);
qdot_6bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_6bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_6bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_6bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
while (k < rows_5 && k < end_k)
{
int end_k_sg = min(min(k + 128, rows_4), end_k);
uint32_t q_0[5], q_1[5];
load_5(b_ptr, size_n, q_0);
qdot_5bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_5bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_5bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_5bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
// while (k + 128 < rows_4 && k + 128 < end_k)
// {
// uint32_t q_0[8], q_1[8];
// load_8(b_ptr, size_n, q_0);
// load_8(b_ptr, size_n, q_1);
// qdot_4bit_64<m_count>(k, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0);
// qdot_4bit_64<m_count>(k, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1);
// }
while (k < rows_4 && k < end_k)
{
int end_k_sg = min(min(k + 128, rows_3), end_k);
uint32_t q_0[4], q_1[4];
load_4(b_ptr, size_n, q_0);
qdot_4bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_4bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_4bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_4bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
// while (k + 128 < rows_3 && k + 128 < end_k)
// {
// uint32_t q_0[6], q_1[6];
// load_6(b_ptr, size_n, q_0);
// load_6(b_ptr, size_n, q_1);
// qdot_3bit_64<m_count>(k, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0);
// qdot_3bit_64<m_count>(k, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1);
// }
while (k < rows_3 && k < end_k)
{
int end_k_sg = min(min(k + 128, rows_2), end_k);
uint32_t q_0[3], q_1[3];
load_3(b_ptr, size_n, q_0);
qdot_3bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_3bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_3bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_3bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
// while (k + 128 < rows_2 && k + 128 < end_k)
// {
// uint32_t q_0[8];
// load_8(b_ptr, size_n, q_0);
// qdot_2bit_128<m_count>(k, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0);
// }
while (k < rows_2 && k < end_k)
{
int end_k_sg = min(k + 128, end_k);
uint32_t q_0[2], q_1[2];
load_2(b_ptr, size_n, q_0);
qdot_2bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_2bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
qdot_2bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_0, q_1);
qdot_2bit_32<m_count>(k, end_k_sg, group, nextgroup, groupsize, n, scales, scales_idx, qs_h, block_c, a_ptr, a_stride, b_ptr, size_n, q_1, q_0);
}
// Accumulate column sums in c
for (int m = 0; m < m_count; m++) atomicAdd(c_.item_ptr(offset_m + m, n), __hadd(block_c[m].x, block_c[m].y));
//for (int m = 0; m < m_count; m++) c_.set(offset_m + m, n, block_c[m]);
}
fp_gemm_half_q_half_kernel pick_gemm_half_q_half_kernel(bool first_block, const int m_count)
{
if (m_count == 1) return gemm_half_q_half_kernel<true, 1>;
if (m_count == 2) return gemm_half_q_half_kernel<true, 2>;
// if (m_count == 3) return gemm_half_q_half_kernel<true, 3>;
// if (m_count == 4) return gemm_half_q_half_kernel<true, 4>;
// if (m_count == 5) return gemm_half_q_half_kernel<true, 5>;
// if (m_count == 6) return gemm_half_q_half_kernel<true, 6>;
// if (m_count == 7) return gemm_half_q_half_kernel<true, 7>;
// if (m_count == 8) return gemm_half_q_half_kernel<true, 8>;
return NULL;
}
void gemm_half_q_half_cuda_part
(
const half* a,
QMatrix* b,
half* c,
int size_m,
int size_n,
int size_k,
int count_m
)
{
dim3 blockDim, gridDim;
blockDim.x = BLOCK_KN_SIZE;
blockDim.y = 1;
blockDim.z = 1;
gridDim.x = DIVIDE(size_n, BLOCK_KN_SIZE);
gridDim.y = DIVIDE(size_m, count_m);
gridDim.z = DIVIDE(size_k, BLOCK_KN_SIZE);
fp_gemm_half_q_half_kernel kernel = pick_gemm_half_q_half_kernel(true, count_m);
kernel<<<gridDim, blockDim>>>
(
a,
b->cuda_q_weight,
b->cuda_q_scale,
b->cuda_q_scale_max,
b->cuda_q_groups,
c,
size_m,
size_n,
size_k,
b->groups,
b->groupsize,
b->cuda_q_perm,
b->rows_8,
b->rows_6,
b->rows_5,
b->rows_4,
b->rows_3,
b->rows_2
);
}
void gemm_half_q_half_cuda
(
cublasHandle_t cublas_handle,
const half* a,
QMatrix* b,
half* c,
int size_m,
int size_n,
int size_k,
bool clear,
half* temp_dq
)
{
if (size_m >= MAX_Q_GEMM_ROWS)
{
// Reconstruct FP16 matrix, then cuBLAS
//DBGI3(size_m, size_n, size_k);
if (!temp_dq) temp_dq = b->temp_dq;
b->reconstruct(temp_dq);
cublasSetMathMode(cublas_handle, CUBLAS_TENSOR_OP_MATH);
//DBGI3(size_m, size_n, size_k);
const half alpha = __float2half(1.0f);
const half beta = clear ? __float2half(0.0f) : __float2half(1.0f);
cublasHgemm(cublas_handle,
CUBLAS_OP_N,
CUBLAS_OP_N,
size_n,
size_m,
size_k,
&alpha,
temp_dq,
size_n,
a,
size_k,
&beta,
c,
size_n);
// const float alpha = 1.0f;
// const float beta = clear ? 0.0f : 1.0f;
// cublasSgemmEx(cublas_handle,
// CUBLAS_OP_N,
// CUBLAS_OP_N,
// size_n,
// size_m,
// size_k,
// &alpha,
// temp_dq,
// CUDA_R_16F,
// size_n,
// a,
// CUDA_R_16F,
// size_k,
// &beta,
// c,
// CUDA_R_16F,
// size_n);
}
else
{
// Quantized matmul
if (clear) clear_tensor_cuda(c, size_m, size_n);
int max_chunks = size_m / MAX_COUNT_M;
int last_chunk = max_chunks * MAX_COUNT_M;
int last_chunk_size = size_m - last_chunk;
// DBGI3(size_m, size_n, size_k);
// DBGI3(max_chunks, last_chunk, last_chunk_size);
if (max_chunks)
gemm_half_q_half_cuda_part(a, b, c, last_chunk, size_n, size_k, MAX_COUNT_M);
if (last_chunk_size)
gemm_half_q_half_cuda_part(a + last_chunk * size_k, b, c + last_chunk * size_n, last_chunk_size, size_n, size_k, last_chunk_size);
}
}
__global__ void clear_kernel
(
half* __restrict__ c,
const int size_m,
const int size_n
)
{
int m = blockIdx.y;
int n = (blockIdx.x * CLEAR_N_SIZE + threadIdx.x) * 8;
if (n >= size_n) return;
int4* c_ptr = (int4*)(c + m * size_n + n);
*c_ptr = {};
}
void clear_tensor_cuda
(
half* c,
int size_m,
int size_n
)
{
dim3 blockDim, gridDim;
blockDim.x = CLEAR_N_SIZE;
blockDim.y = 1;
gridDim.x = DIVIDE(size_n / 8, CLEAR_N_SIZE);
gridDim.y = size_m;
clear_kernel<<<gridDim, blockDim>>>(c, size_m, size_n);
}
#!/usr/bin/env python3
import argparse
import torch
import torch.nn as nn
from datasets import load_dataset
from gptq_triton import load_quant
from tqdm import tqdm
from transformers import AutoTokenizer, LlamaForCausalLM
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, help='Path to model, either a HuggingFace model or a quantized model')
parser.add_argument('--quant', action='store_true', help='Whether the model is quantized')
parser.add_argument('--stride', type=int, default=512, help='Stride for calculating perplexity')
parser.add_argument('--context-length', type=int, default=2048, help='Length of context to use')
def main():
args = parser.parse_args()
if not args.quant:
model = get_llama(args.model)
model.eval()
model.to('cuda')
else:
model = load_quant(args.model)
model.eval()
model.to('cuda')
# NOTE: Setting use_fast=False for now, as the alternative was an order of magnitude slower on a recent `transformers` commit
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=False)
context_length = model.seqlen if args.context_length is None else args.context_length
for dataset in ['wikitext-2', 'ptb', 'c4']:
ppl = calculate_perplexity(model, tokenizer, dataset, max_length=context_length, stride=args.stride)
print(f"{dataset} perplexity: {ppl}")
def get_llama(model: str):
"""
Load a pretrained Llama model
"""
def skip(*args, **kwargs):
pass
# NOTE: This is a nasty hack, but it speeds up model building by a huge amount
old_inits = (torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_)
torch.nn.init.kaiming_uniform_ = skip
torch.nn.init.uniform_ = skip
torch.nn.init.normal_ = skip
model = LlamaForCausalLM.from_pretrained(model, torch_dtype='auto')
model.seqlen = 2048
# Restore the old initializers
torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_ = old_inits
return model
def get_dataset(dataset_name: str, tokenizer) -> torch.Tensor:
if dataset_name == "wikitext-2":
test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt").input_ids
elif dataset_name == 'ptb':
test = load_dataset("ptb_text_only", 'penn_treebank', split="validation")
encodings = tokenizer("\n\n".join(test["sentence"]), return_tensors="pt").input_ids
elif dataset_name == 'c4':
# WARNING: Many of the files in the allenai/c4 repo are marked as "Unsafe" by HuggingFace, possibly containing a virus. This particular file is not, and I doubt it's an issue, but worth noting.
test = load_dataset('allenai/c4', 'allenai--c4', data_files={'validation': 'en/c4-validation.00000-of-00008.json.gz'}, split='validation')
encodings = [tokenizer(x, return_tensors="pt").input_ids for x in test['text'][:1000]]
encodings = torch.cat(encodings, dim=1)
else:
raise ValueError(f"Unknown dataset {dataset_name}")
return encodings
def calculate_perplexity(model, tokenizer, dataset: str, max_length: int, stride: int = 512) -> float:
print("Loading dataset...")
encodings = get_dataset(dataset, tokenizer)
seq_len = encodings.size(1)
print("Calculating perplexity...")
print(f"Sequence length: {seq_len}")
print(f"Max length: {max_length}")
print(f"Stride: {stride}")
nlls = []
prev_end_loc = 0
for begin_loc in (pbar := tqdm(range(0, seq_len - 1, stride))):
end_loc = min(seq_len - 1, begin_loc + max_length)
trg_len = end_loc - prev_end_loc # How many tokens we want to predict
input_ids = encodings[:, begin_loc:end_loc+1].to('cuda') # +1 for the labels
with torch.no_grad():
# Ask the model for logits
# NOTE: Instead of calling HF's model wrapper, we call the model directly to hopefully cut down on some memory overhead
outputs = model.model(input_ids[:, :-1], use_cache=False)
logits = model.lm_head(outputs[0][..., -trg_len:, :])
# The last trg_len tokens are the labels
labels = input_ids[:, -trg_len:].contiguous()
# Compute the NLL for this batch using flattened logits and labels
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
nlls.append(loss.to('cpu').to(torch.float32))
ppl = torch.exp(torch.stack(nlls).mean())
pbar.set_description(f"Perplexity: {ppl:.2f}")
prev_end_loc = end_loc
if end_loc == (seq_len - 1):
break
ppl = torch.exp(torch.stack(nlls).mean())
return ppl
if __name__ == '__main__':
main()
[metadata]
name = gptq_triton
version = 0.0.3
author = fpgaminer
author_email = [email protected]
description = Fast GPTQ kernels written in Triton
long_description = file: README.md
long_description_content_type = text/markdown; charset=UTF-8
url = https://github.com/fpgaminer/GPTQ-triton
keywords = gptq, triton, torch, cuda, gpu, quantization, quantize, quantized, inference, deep learning, machine learning
license = Apache License 2.0
license_file = LICENSE
classifiers =
Development Status :: 3 - Alpha
License :: OSI Approved :: Apache Software License
Intended Audience :: Developers
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Topic :: Scientific/Engineering :: Artificial Intelligence
Topic :: Software Development :: Libraries :: Python Modules
[options]
zip_safe = False
include_package_data = False
package_dir =
= src
packages = find:
python_requires = >=3.6
install_requires =
triton >= 2.0.0
torch >= 2.0.0
transformers
[options.packages.find]
where = src
import random
from datasets import load_dataset
def get_dataset(dataset_name: str, tokenizer, nsamples: int, seed: int, seqlen: int):
if dataset_name == "wikitext-2":
return get_wikitext2(nsamples, seed, seqlen, tokenizer)
elif dataset_name == 'ptb':
return get_ptb(nsamples, seed, seqlen, tokenizer, jointext='\n\n')
elif dataset_name == 'ptb-new':
return get_ptb(nsamples, seed, seqlen, tokenizer, jointext=' ')
elif dataset_name == 'c4':
return get_c4(nsamples, seed, seqlen, tokenizer)
else:
raise ValueError(f"Unknown dataset {dataset_name}")
def get_wikitext2(nsamples: int, seed: int, seqlen: int, tokenizer, jointext: str = '\n\n'):
traindata = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')
trainenc = tokenizer(jointext.join(traindata['text']), return_tensors='pt')
rng = random.Random(seed)
trainloader = (rng.randint(0, trainenc.input_ids.shape[1] - seqlen - 1) for _ in range(nsamples))
trainloader = [trainenc.input_ids[:, i:i+seqlen] for i in trainloader]
return trainloader
def get_ptb(nsamples: int, seed: int, seqlen: int, tokenizer, jointext: str):
traindata = load_dataset('ptb_text_only', 'penn_treebank', split='train')
trainenc = tokenizer(jointext.join(traindata['sentence']), return_tensors='pt')
rng = random.Random(seed)
trainloader = (rng.randint(0, trainenc.input_ids.shape[1] - seqlen - 1) for _ in range(nsamples))
trainloader = [trainenc.input_ids[:, i:i+seqlen] for i in trainloader]
return trainloader
def get_c4(nsamples: int, seed: int, seqlen: int, tokenizer):
# WARNING: Many of the files in the allenai/c4 repo are marked as "Unsafe" by HuggingFace, possibly containing a virus. This particular file is not, and I doubt it's an issue, but worth noting.
traindata = load_dataset('allenai/c4', 'allenai--c4', data_files={'train': 'en/c4-train.00000-of-01024.json.gz'}, split='train')
rng = random.Random(seed)
trainloader = []
for _ in range(nsamples):
while True:
i = rng.randint(0, len(traindata) - 1)
trainenc = tokenizer(traindata[i]['text'], return_tensors='pt')
if trainenc.input_ids.shape[1] >= seqlen:
break
i = rng.randint(0, trainenc.input_ids.shape[1] - seqlen - 1)
inp = trainenc.input_ids[:, i:i + seqlen]
trainloader.append(inp)
return trainloader
#!/usr/bin/env python3
"""
Benchmarks the generation speed of a model. While Benchmark.ipynb provides nice detailed performance data, it measures the kernels in isolation.
This script measures "real world" performance by running the whole model in generation mode.
It tests a grid of prompt lengths and generation lengths, and saves the timing results to `results.json`.
"""
import argparse
import itertools
import json
import os
import random
import time
import original_quant
import torch
import transformers
from gptq_triton import load_quant
from transformers import AutoTokenizer, LlamaConfig, LlamaForCausalLM
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, help='Path to model, either a HuggingFace model or a quantized model')
parser.add_argument('--quant', action='store_true', help='Whether the model is quantized')
parser.add_argument('--cuda', type=str, help='Whether to use the old CUDA kernel and format; this must be set to the path to the CUDA quantized model, and --model must be set to a HF model')
parser.add_argument('--average', type=int, default=10, help='Number of times to run each test to get an average')
def main():
args = parser.parse_args()
if args.cuda:
model = load_cuda_quant(args.model, args.cuda, 4, -1)
model.eval()
model.to('cuda')
elif not args.quant:
model = get_llama(args.model)
model.eval()
model.to('cuda')
else:
model = load_quant(args.model)
model.eval()
model.to('cuda')
tokenizer = AutoTokenizer.from_pretrained(args.model, use_fast=False)
prompt_lengths = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
max_lengths = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
lengths = set(itertools.product(prompt_lengths, max_lengths))
# Remove lengths that we've already tested
if os.path.exists('results.jsonl'):
with open('results.jsonl', 'r') as f:
for line in f:
line = json.loads(line)
key = (line['prompt_length'], line['max_length'])
if key in lengths:
lengths.remove(key)
# Shuffle the lengths so that we don't always test in the same order and get caching effects
lengths = list(lengths)
random.shuffle(lengths)
# TODO: For some reason the first run is always slow, so we run it once before the benchmark to warm things up
encoded_prompt = tokenizer.encode("TODO", add_special_tokens=False, return_tensors='pt').to('cuda')
_ = model.generate(
input_ids=encoded_prompt,
max_length=8,
do_sample=True,
num_return_sequences=1,
suppress_tokens=[model.generation_config.eos_token_id],
)
# Run the remaining benchmarks
with open('results.jsonl', 'a') as f:
for prompt_length, max_length in lengths:
print(f'Prompt length: {prompt_length}, max length: {max_length}')
results = []
for _ in range(args.average):
# Generate a long random string
# We do this every time to avoid caching effects
prompt = ''.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,;:!?') for _ in range(2048 * 10))
# Encode and crop down
encoded_prompt = tokenizer.encode(prompt, add_special_tokens=False, return_tensors='pt')
encoded_prompt = encoded_prompt[:, :prompt_length]
encoded_prompt = encoded_prompt.to('cuda')
start_time = time.time()
_ = model.generate(
input_ids=encoded_prompt,
max_length=max_length + prompt_length,
do_sample=True,
num_return_sequences=1,
suppress_tokens=[model.generation_config.eos_token_id], # This prevents the sampler from ending early; it must generate max_length tokens
)
end_time = time.time()
gen_time = end_time - start_time
speed = max_length / gen_time
results.append((gen_time, speed))
# Compute the average
avg_time = sum(t for t, _ in results) / len(results)
avg_speed = (max_length * len(results)) / sum(t for t, _ in results)
print(f'Average generation time: {avg_time:.2f} seconds')
print(f'Average generation speed: {avg_speed:.2f} tokens per second')
print()
f.write(json.dumps({
'prompt_length': prompt_length,
'max_length': max_length,
'average_time': avg_time,
'average_speed': avg_speed,
'runs': results,
}))
f.write("\n")
f.flush()
def get_llama(model: str):
"""
Load a pretrained Llama model
"""
def skip(*args, **kwargs):
pass
# NOTE: This is a nasty hack, but it speeds up model building by a huge amount
old_inits = (torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_)
torch.nn.init.kaiming_uniform_ = skip
torch.nn.init.uniform_ = skip
torch.nn.init.normal_ = skip
model = LlamaForCausalLM.from_pretrained(model, torch_dtype='auto')
model.seqlen = 2048
# Restore the old initializers
torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_ = old_inits
return model
def load_cuda_quant(model, checkpoint, wbits, groupsize):
"""
Load a quantized model using the old CUDA kernel
"""
config = LlamaConfig.from_pretrained(model)
def noop(*args, **kwargs):
pass
original_inits = (torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_)
torch.nn.init.kaiming_uniform_ = noop
torch.nn.init.uniform_ = noop
torch.nn.init.normal_ = noop
torch.set_default_dtype(torch.half)
original_init_weights = transformers.modeling_utils._init_weights
transformers.modeling_utils._init_weights = False
torch.set_default_dtype(torch.half)
model = LlamaForCausalLM(config)
torch.set_default_dtype(torch.float)
transformers.modeling_utils._init_weights = original_init_weights
torch.nn.init.kaiming_uniform_, torch.nn.init.uniform_, torch.nn.init.normal_ = original_inits
model = model.eval()
layers = original_quant.find_layers(model)
for name in ['lm_head']:
if name in layers:
del layers[name]
original_quant.make_quant(model, layers, wbits, groupsize, faster=False)
del layers
print('Loading model ...')
if checkpoint.endswith('.safetensors'):
from safetensors.torch import load_file as safe_load
model.load_state_dict(safe_load(checkpoint))
else:
model.load_state_dict(torch.load(checkpoint))
model.seqlen = 2048
print('Done.')
return model
if __name__ == '__main__':
main()
VPS
Oct 12, 2023
Ignas R.
10min Read
25 Common Linux Bash Script Examples to Get You Started
Bash or Bourne-again shell is one of the most popular shells and command languages for Linux VPS enthusiasts. It was first released in 1989 and was used as the default shell for most Linux distributions ever since.
Bash scripting allows users and system administrators to automate processes and save hundreds of hours of manual work. It’s worth mentioning that Bash is also available for Windows and macOS.
This tutorial will introduce you to what bash scripting is. It features over twenty useful bash script examples to start your bash scripting journey.
What Is Bash Scripting Used For
25 Bash Scripts Examples
1. Hello World
2. Echo Command
3. Sleep Command
4. Wait Command
5. Comments
6. Get User Input
7. Loops
8. Create an Array
9. Conditional Statements
10. Functions
11. Display String Length
12. Extract String
13. Find and Replace String
14. Concatenate Strings
15. Check if a Number is Even or Odd
16. Generate Factorial of Number
17. Create Directories
18. Read Files
19. Print Files With Line Count
20. Delete Files
21. Test if File Exists
22. Check Inodes and Disk Usage
23. Send Email Example
24. Update Packages
25. Show Server Information
What Is Bash Scripting Used For
Before we move on to the topic of bash scripting use cases, we need to elaborate on what bash and bash scripting are.
Bash is a command-line interface interpreter that runs in a text window where users can manage and execute shell commands. Bash – or shell scripting – on the other hand is the process of writing a set of commands to be executed on a Linux system. A file that includes such instructions is called a bash script.
To put it simply, the bash interpreter reads the bash script and executes the commands at the same time. For example, a Linux user can execute hundreds of commands with a single click instead of inputting them one by one. For this reason, bash scripting is the go-to choice for increasing productivity, setting up automation, and eliminating repetitive tasks.
25 Bash Scripts Examples
The following section will cover 25 of the most popular bash scripting examples, including variable manipulation and echoing out various values. We will also cover functions, arrays, loops, and much more.
1. Hello World
Hello World is the most simple bash script to start with. We will create a new variable called learningbash and print out the words Hello World. First, open a new shell script file with a text editor of your choice:
nano hello.sh
Paste the following lines into it:
#!/bin/bash
#Creates a new variable with a value of "Hello World"
learningbash="Hello World"
echo $learningbash
The command-line window showcasing the output of the first bash script – Hello World
The first line (/bin/bash) is used in every bash script. It instructs the operating system to use a bash interpreter as a command interpreter.
2. Echo Command
The echo bash command can be used to print out text as well as values of variables. In the following example, we will showcase how quotation marks affect the echo command. We will start by opening a new bash script file:
nano echo.sh
This simple bash script example will create a new variable and print it out while using different quotation marks.
#!/bin/bash
provider="Hostinger"
echo 'The best hosting provider is $provider'
echo "The best hosting provider is $provider"
The command-line window shows the echo command
As you can see, if the echo bash command is used with double quotation marks ““, then the script will print out the actual value of a variable. Otherwise, if the single quotation marks ‘‘ are used, it will print out only the name of a variable.
3. Sleep Command
Sleep command halts all currently running bash scripts and puts the system to sleep. Start by creating a new bash script file:
nano sleep.sh
Then, paste in the following simple script:
#!/bin/bash
sleep 10 && echo “I’ve been sleeping for 10 seconds, I want more” && sleep 10 && echo “I’m done sleeping, thanks!”
A bash script with the sleep command. The basic idea is that it puts the system to a halt for a set amount of time
The above example starts with a simple sleep bash command that will put your system to sleep for 10 seconds. After that, we combine the previously learned echo command with sleep – this way system will sleep for 10 seconds, then print out some words, sleep again, print out some words again and end its operation.
Pro Tip
A bash script can always be terminated by clicking CTRL + C without waiting for it to finish its operation.
4. Wait Command
wait is a built-in Linux command that waits for completion of running process. The wait command is used with a particular process id or job id.
Here’s how to create a wait bash script. Begin by creating a new bash file:
nano wait.sh
Paste in the following:
#!/bin/bash
wait 1234
echo “Done”
Important! If no job ID is provided, the wait command waits until all child background jobs are completed.
5. Comments
Users can easily add comments to their bash scripts with the # symbol. It is extra useful if you’ve got a lengthy script that needs explaining on some lines.
Begin by creating a new bash script:
nano comments.sh
Then paste in the following:
#!/bin/bash
# Define a variable named Hostinger
provider="Hostinger"
# Print out the following text
echo 'The best hosting provider is $provider'
# Print out the following text with $provider variable value
echo "The best hosting provider is $provider"
The command-line window showing single line comment functionality. It's worth noting that bash comments are not displayed with the script output.
Keep in mind that bash comments are only visible on a text editor.
6. Get User Input
To take input from users, we’ll use the read bash command. First, create a new bash shell file:
nano read.sh
Then, fill it with the script below:
#!/bin/bash
echo "What is your age?"
read age
echo "Wow, you look younger than $age years old"
In the above example, an age value was entered by the user. The output was then printed via the echo command.
7. Loops
A loop is an essential tool in various programming languages. To put it simply, a bash loop is a set of instructions that are repeated until a user-specified condition is reached. Start by creating a loop bash program:
nano whileloop.sh
Then paste in the following:
#!/bin/bash
n=0
while :
do
echo Countdown: $n
((n++))
done
This will work as a countdown to infinity until you press CTRL + C to stop the script.
Now that we’ve tested the while loop, we can move on to the for loop. Create a bash file for it:
nano forloop.sh
It should contain the script below:
#!/bin/bash
for (( n=2; n<=10; n++ ))
do
echo "$n seconds"
done
A bash script showcasing the "for" loop
The script prints out numbers from 2 to 10 while adding the seconds keyword to it.
8. Create an Array
A bash array is a data structure designed to store information in an indexed way. It is extra useful if users need to store and retrieve thousands of pieces of data fast. What makes bash arrays special is that unlike any other programming language, they can store different types of elements. For example, you can use a bash array to store both strings and numbers.
Create a new file in the current directory:
nano array.sh
Combine the freshly learned for loop with a new indexed array:
#!/bin/bash
# Create an indexed array
IndexedArray=(egg burger milk)
#Iterate over the array to get all the values
for i in "${IndexedArray[@]}";do echo "$i";done
A bash script to create and print out an array
The script iterates over the IndexedArray and prints out all the values.
9. Conditional Statements
The most popular and widely used conditional statement is if. Even though the if statement is easy to write and understand, it can be used in advanced shell scripts as well.
Begin with a new bash file:
nano if.sh
Paste the code below in it:
#!/bin/bash
salary=1000
expenses=800
#Check if salary and expenses are equal
if [ $salary == $expenses ];
then
echo "Salary and expenses are equal"
#Check if salary and expenses are not equal
elif [ $salary != $expenses ];
then
echo "Salary and expenses are not equal"
fi
This script creates two new variables and compares whether they are equal or not.
10. Functions
A bash function is a set of commands that can be reused numerous times throughout a bash script. Create a new file:
nano function.sh
Then, paste in the following code – it creates a simple Hello World function.
#!/bin/bash
hello () {
echo 'Hello World!'
}
hello
11. Display String Length
There are a couple of ways of counting string length in bash. We’ll talk about the simplest. Create a file named stringlength.sh:
nano stringlength.sh
Fill it with the following:
#!/bin/bash
# Create a new string
mystring="lets count the length of this string"
i=${#mystring}
echo "Length: $i"
Here, the # operator is used to get the length of the string variable.
12. Extract String
If users need to remove unnecessary parts from strings, they can use the Bash string extraction tools. Start by creating a new bash script:
nano extractstring.sh
The following script has 4 values, 3 of them being strings. In our example, we will extract only the number value. This can be done via the cut command. First, we instruct the command that each variable is separated by a comma by using the -d flag. Then we ask the cut command to extract the 5th value.
#!/bin/bash
cut -d , -f 5 <<< "Website,Domain,DNS,SMTP,5005"
In another example, we have a string that is mixed with some numbers. We will use expr substr commands to extract only the Hostinger text value.
#!/bin/bash
expr substr "458449Hostinger4132" 7 9
13. Find and Replace String
Another useful bash script for strings is find and replace. Create a file named findreplace.sh:
nano findreplace.sh
Then paste in the following bash script:
#!/bin/bash
first="I drive a BMW and Volvo"
second="Audi"
echo "${first/BMW/"$second"}"
Find and replace script in bash
The find and replace functionality doesn’t require any special commands, it can all be done with string manipulation.
14. Concatenate Strings
Concatenation is the term used for appending one string to the end of another string. Start by creating concatenation.sh file.
nano concatenation.sh
The most simple example would be the following:
#!/bin/bash
firststring="The secret is..."
secondstring="Bash"
thirdstring="$firststring$secondstring"
echo "$thirdstring"
The above script will connect the values of firststring and secondstring variables creating a whole new thirdstring.
A more advanced example would look like this:
#!/bin/bash
firststring="The secret is..."
firststring+="Bash"
echo "$firststring"
The script uses the += operator to join the strings. With this method, you can concatenate strings with only one variable.
15. Check if a Number is Even or Odd
Odd and even numbers can be easily divided using the if statement and some simple math. Create a file named evenoddnumbers.sh:
nano evenoddnumbers.sh
The script uses the read command to read user input and divides it by 2. If the answer is 0, the number is even.
#!/bin/bash
read -p "Enter a number and I will check if its odd or even " mynumber
if [ $((mynumber%2)) -eq 0 ]
then
echo "Your number is even"
else
echo "Your number is odd."
fi
16. Generate Factorial of Number
The factorial of a number is the result of all positive descending integers. For example, the factorial of 5 would be 120:
5! = 5*4*3*2*1 = 120
Factorial scrips are very useful for users learning about recursion. Start by creating a .sh file executable:
factorial.sh
The following script will ask the user to enter a number they want to get the factorial of and use a for loop to calculate it.
#!/bin/bash
echo Enter the number you want to get factorial for
read mynumber
factorial=1
for ((i=1;i<=mynumber;i++))
do
factorial=$(($factorial*$i))
done
echo $factorial
The command-line window displaying shell script for getting factorial of a number
17. Create Directories
It is effortless to create directories in bash unless you need to create a lot of directories quickly. In the following example, we will use the bash script to create a set of directories with the same subdirectories in each.
First, create a file named directories.sh:
nano directories.sh
Then paste in the following code:
#!/bin/bash
mkdir -p {Math,English,Geography,Arts}/{notes,examresults,portfolio}
The script creates 4 main directories: Math, English, Geography, and Arts. The Notes, examresults, and portfolio subdirectories are also created inside each.
If you were to replace the / symbol in the middle with _, the script would look like this:
#!/bin/bash
mkdir -p {Math,English,Geography,Arts}_{notes,examresults,portfolio}
Here’s the output for it displaying a merge of the two directories:
A bash script to create a lot of directories quickly. The first bash case statement indicates which interpreter to use
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi
The following script will check to see if a file exists or not.
#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exist"
fi
The result:
$ ./filetesting.sh
File does not exist
$ touch file
$ ./filetesting.sh
File exists
Similarly for example we can use while loop to check if file does not exist. This script will sleep until file does exist. Note bash negator ! which negates the -e option.
#!/bin/bash
while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done
Bash Select
The select command allows us to prompt the user to make a selection.
#!/bin/bash
PS3='Choose one word: '
# bash select
select word in "linux" "bash" "scripting" "tutorial"
do
echo "The word you have selected is: $word"
# Break, otherwise endless loop
break
done
exit 0
The result:
$ ./select.sh
1) linux
2) bash
3) scripting
4) tutorial
Choose one word: 2
The word you have selected is: bash
Case statement conditional
The case statement makes it easy to have many different possibilities, whereas an if statement can get lengthy very quickly if you have more than a few possibilities to account for.
#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in
1) echo "You selected bash";;
2) echo "You selected perl";;
3) echo "You selected phyton";;
4) echo "You selected c++";;
5) exit
esac
The result:
$ ./case.sh
What is your preferred programming / scripting language
1) bash
2) perl
3) phyton
4) c++
5) I do not know !
3
You selected phyton
Bash quotes and quotations
Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.
Escaping Meta characters
Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash \ character. Example:
#!/bin/bash
#Declare bash string variable
BASH_VAR="Bash Script"
# echo variable BASH_VAR
echo $BASH_VAR
#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR
# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\"
Here’s what it looks like when we execute the script:
$ ./escape_meta.sh
Bash Script
$BASH_VAR
\
Single quotes
Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.
#!/bin/bash
# Declare bash string variable
BASH_VAR="Bash Script"
# echo variable BASH_VAR
echo $BASH_VAR
# meta characters special meaning in bash is suppressed when using single quotes
echo '$BASH_VAR "$BASH_VAR"'
The result:
$ ./single_quotes.sh
Bash Script
$BASH_VAR "$BASH_VAR"
Double quotes
Double quotes in bash will suppress special meaning of every meta characters except $, \ and `. Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with \. Example:
#!/bin/bash
#Declare bash string variable
BASH_VAR="Bash Script"
# echo variable BASH_VAR
echo $BASH_VAR
# meta characters and its special meaning in bash is
# suppressed when using double quotes except "$", "\" and "`"
echo "It's $BASH_VAR and \"$BASH_VAR\" using backticks: `date`"
The result:
$ ./double_quotes.sh
Bash Script
It's Bash Script and "Bash Script" using backticks: Thu 10 Feb 2022 10:24:15 PM EST
Bash quoting with ANSI-C style
There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with \ will gain special meaning according to the ANSI-C standard.
\a alert (bell) \b backspace
\e an escape character \f form feed
\n newline \r carriage return
\t horizontal tab \v vertical tab
\\ backslash \` single quote
\nnn octal value of characters ( see [http://www.asciitable.com/ ASCII table] ) \xnn hexadecimal value of characters ( see [http://www.asciitable.com/ ASCII table] )
// SPDX-License-Identifier: GPL-2.0
#include <linux/irq-entry-common.h>
#include <linux/resume_user_mode.h>
#include <linux/highmem.h>
#include <linux/jump_label.h>
#include <linux/kmsan.h>
#include <linux/livepatch.h>
#include <linux/tick.h>
/* Workaround to allow gradual conversion of architecture code */
void __weak arch_do_signal_or_restart(struct pt_regs *regs) { }
/**
* exit_to_user_mode_loop - do any pending work before leaving to user space
* @regs: Pointer to pt_regs on entry stack
* @ti_work: TIF work flags as read by the caller
*/
__always_inline unsigned long exit_to_user_mode_loop(struct pt_regs *regs,
unsigned long ti_work)
{
/*
* Before returning to user space ensure that all pending work
* items have been completed.
*/
while (ti_work & EXIT_TO_USER_MODE_WORK) {
local_irq_enable_exit_to_user(ti_work);
if (ti_work & (_TIF_NEED_RESCHED | _TIF_NEED_RESCHED_LAZY))
schedule();
if (ti_work & _TIF_UPROBE)
uprobe_notify_resume(regs);
if (ti_work & _TIF_PATCH_PENDING)
klp_update_patch_state(current);
if (ti_work & (_TIF_SIGPENDING | _TIF_NOTIFY_SIGNAL))
arch_do_signal_or_restart(regs);
if (ti_work & _TIF_NOTIFY_RESUME)
resume_user_mode_work(regs);
/* Architecture specific TIF work */
arch_exit_to_user_mode_work(regs, ti_work);
/*
* Disable interrupts and reevaluate the work flags as they
* might have changed while interrupts and preemption was
* enabled above.
*/
local_irq_disable_exit_to_user();
/* Check if any of the above work has queued a deferred wakeup */
tick_nohz_user_enter_prepare();
ti_work = read_thread_flags();
}
/* Return the latest work state for arch_exit_to_user_mode() */
return ti_work;
}
noinstr void irqentry_enter_from_user_mode(struct pt_regs *regs)
{
enter_from_user_mode(regs);
}
noinstr void irqentry_exit_to_user_mode(struct pt_regs *regs)
{
instrumentation_begin();
exit_to_user_mode_prepare(regs);
instrumentation_end();
exit_to_user_mode();
}
noinstr irqentry_state_t irqentry_enter(struct pt_regs *regs)
{
irqentry_state_t ret = {
.exit_rcu = false,
};
if (user_mode(regs)) {
irqentry_enter_from_user_mode(regs);
return ret;
}
/*
* If this entry hit the idle task invoke ct_irq_enter() whether
* RCU is watching or not.
*
* Interrupts can nest when the first interrupt invokes softirq
* processing on return which enables interrupts.
*
* Scheduler ticks in the idle task can mark quiescent state and
* terminate a grace period, if and only if the timer interrupt is
* not nested into another interrupt.
*
* Checking for rcu_is_watching() here would prevent the nesting
* interrupt to invoke ct_irq_enter(). If that nested interrupt is
* the tick then rcu_flavor_sched_clock_irq() would wrongfully
* assume that it is the first interrupt and eventually claim
* quiescent state and end grace periods prematurely.
*
* Unconditionally invoke ct_irq_enter() so RCU state stays
* consistent.
*
* TINY_RCU does not support EQS, so let the compiler eliminate
* this part when enabled.
*/
if (!IS_ENABLED(CONFIG_TINY_RCU) &&
(is_idle_task(current) || arch_in_rcu_eqs())) {
/*
* If RCU is not watching then the same careful
* sequence vs. lockdep and tracing is required
* as in irqentry_enter_from_user_mode().
*/
lockdep_hardirqs_off(CALLER_ADDR0);
ct_irq_enter();
instrumentation_begin();
kmsan_unpoison_entry_regs(regs);
trace_hardirqs_off_finish();
instrumentation_end();
ret.exit_rcu = true;
return ret;
}
/*
* If RCU is watching then RCU only wants to check whether it needs
* to restart the tick in NOHZ mode. rcu_irq_enter_check_tick()
* already contains a warning when RCU is not watching, so no point
* in having another one here.
*/
lockdep_hardirqs_off(CALLER_ADDR0);
instrumentation_begin();
kmsan_unpoison_entry_regs(regs);
rcu_irq_enter_check_tick();
trace_hardirqs_off_finish();
instrumentation_end();
return ret;
}
/**
* arch_irqentry_exit_need_resched - Architecture specific need resched function
*
* Invoked from raw_irqentry_exit_cond_resched() to check if resched is needed.
* Defaults return true.
*
* The main purpose is to permit arch to avoid preemption of a task from an IRQ.
*/
static inline bool arch_irqentry_exit_need_resched(void);
#ifndef arch_irqentry_exit_need_resched
static inline bool arch_irqentry_exit_need_resched(void) { return true; }
#endif
void raw_irqentry_exit_cond_resched(void)
{
if (!preempt_count()) {
/* Sanity check RCU and thread stack */
rcu_irq_exit_check_preempt();
if (IS_ENABLED(CONFIG_DEBUG_ENTRY))
WARN_ON_ONCE(!on_thread_stack());
if (need_resched() && arch_irqentry_exit_need_resched())
preempt_schedule_irq();
}
}
#ifdef CONFIG_PREEMPT_DYNAMIC
#if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL)
DEFINE_STATIC_CALL(irqentry_exit_cond_resched, raw_irqentry_exit_cond_resched);
#elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY)
DEFINE_STATIC_KEY_TRUE(sk_dynamic_irqentry_exit_cond_resched);
void dynamic_irqentry_exit_cond_resched(void)
{
if (!static_branch_unlikely(&sk_dynamic_irqentry_exit_cond_resched))
return;
raw_irqentry_exit_cond_resched();
}
#endif
#endif
noinstr void irqentry_exit(struct pt_regs *regs, irqentry_state_t state)
{
lockdep_assert_irqs_disabled();
/* Check whether this returns to user mode */
if (user_mode(regs)) {
irqentry_exit_to_user_mode(regs);
} else if (!regs_irqs_disabled(regs)) {
/*
* If RCU was not watching on entry this needs to be done
* carefully and needs the same ordering of lockdep/tracing
* and RCU as the return to user mode path.
*/
if (state.exit_rcu) {
instrumentation_begin();
/* Tell the tracer that IRET will enable interrupts */
trace_hardirqs_on_prepare();
lockdep_hardirqs_on_prepare();
instrumentation_end();
ct_irq_exit();
lockdep_hardirqs_on(CALLER_ADDR0);
return;
}
instrumentation_begin();
if (IS_ENABLED(CONFIG_PREEMPTION))
irqentry_exit_cond_resched();
/* Covers both tracing and lockdep */
trace_hardirqs_on();
instrumentation_end();
} else {
/*
* IRQ flags state is correct already. Just tell RCU if it
* was not watching on entry.
*/
if (state.exit_rcu)
ct_irq_exit();
}
}
irqentry_state_t noinstr irqentry_nmi_enter(struct pt_regs *regs)
{
irqentry_state_t irq_state;
irq_state.lockdep = lockdep_hardirqs_enabled();
__nmi_enter();
lockdep_hardirqs_off(CALLER_ADDR0);
lockdep_hardirq_enter();
ct_nmi_enter();
instrumentation_begin();
kmsan_unpoison_entry_regs(regs);
trace_hardirqs_off_finish();
ftrace_nmi_enter();
instrumentation_end();
return irq_state;
}
void noinstr irqentry_nmi_exit(struct pt_regs *regs, irqentry_state_t irq_state)
{
instrumentation_begin();
ftrace_nmi_exit();
if (irq_state.lockdep) {
trace_hardirqs_on_prepare();
lockdep_hardirqs_on_prepare();
}
instrumentation_end();
ct_nmi_exit();
lockdep_hardirq_exit();
if (irq_state.lockdep)
lockdep_hardirqs_on(CALLER_ADDR0);
__nmi_exit();
}
// SPDX-License-Identifier: GPL-2.0
/*
* Real-Time Scheduling Class (mapped to the SCHED_FIFO and SCHED_RR
* policies)
*/
#include "sched.h"
#include "pelt.h"
int sched_rr_timeslice = RR_TIMESLICE;
/* More than 4 hours if BW_SHIFT equals 20. */
static const u64 max_rt_runtime = MAX_BW;
/*
* period over which we measure -rt task CPU usage in us.
* default: 1s
*/
int sysctl_sched_rt_period = 1000000;
/*
* part of the period that we allow rt tasks to run in us.
* default: 0.95s
*/
int sysctl_sched_rt_runtime = 950000;
#ifdef CONFIG_SYSCTL
static int sysctl_sched_rr_timeslice = (MSEC_PER_SEC * RR_TIMESLICE) / HZ;
static int sched_rt_handler(const struct ctl_table *table, int write, void *buffer,
size_t *lenp, loff_t *ppos);
static int sched_rr_handler(const struct ctl_table *table, int write, void *buffer,
size_t *lenp, loff_t *ppos);
static const struct ctl_table sched_rt_sysctls[] = {
{
.procname = "sched_rt_period_us",
.data = &sysctl_sched_rt_period,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = sched_rt_handler,
.extra1 = SYSCTL_ONE,
.extra2 = SYSCTL_INT_MAX,
},
{
.procname = "sched_rt_runtime_us",
.data = &sysctl_sched_rt_runtime,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = sched_rt_handler,
.extra1 = SYSCTL_NEG_ONE,
.extra2 = (void *)&sysctl_sched_rt_period,
},
{
.procname = "sched_rr_timeslice_ms",
.data = &sysctl_sched_rr_timeslice,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = sched_rr_handler,
},
};
static int __init sched_rt_sysctl_init(void)
{
register_sysctl_init("kernel", sched_rt_sysctls);
return 0;
}
late_initcall(sched_rt_sysctl_init);
#endif /* CONFIG_SYSCTL */
void init_rt_rq(struct rt_rq *rt_rq)
{
struct rt_prio_array *array;
int i;
array = &rt_rq->active;
for (i = 0; i < MAX_RT_PRIO; i++) {
INIT_LIST_HEAD(array->queue + i);
__clear_bit(i, array->bitmap);
}
/* delimiter for bitsearch: */
__set_bit(MAX_RT_PRIO, array->bitmap);
rt_rq->highest_prio.curr = MAX_RT_PRIO-1;
rt_rq->highest_prio.next = MAX_RT_PRIO-1;
rt_rq->overloaded = 0;
plist_head_init(&rt_rq->pushable_tasks);
/* We start is dequeued state, because no RT tasks are queued */
rt_rq->rt_queued = 0;
#ifdef CONFIG_RT_GROUP_SCHED
rt_rq->rt_time = 0;
rt_rq->rt_throttled = 0;
rt_rq->rt_runtime = 0;
raw_spin_lock_init(&rt_rq->rt_runtime_lock);
rt_rq->tg = &root_task_group;
#endif
}
#ifdef CONFIG_RT_GROUP_SCHED
static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
{
struct rt_bandwidth *rt_b =
container_of(timer, struct rt_bandwidth, rt_period_timer);
int idle = 0;
int overrun;
raw_spin_lock(&rt_b->rt_runtime_lock);
for (;;) {
overrun = hrtimer_forward_now(timer, rt_b->rt_period);
if (!overrun)
break;
raw_spin_unlock(&rt_b->rt_runtime_lock);
idle = do_sched_rt_period_timer(rt_b, overrun);
raw_spin_lock(&rt_b->rt_runtime_lock);
}
if (idle)
rt_b->rt_period_active = 0;
raw_spin_unlock(&rt_b->rt_runtime_lock);
return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
}
void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
{
rt_b->rt_period = ns_to_ktime(period);
rt_b->rt_runtime = runtime;
raw_spin_lock_init(&rt_b->rt_runtime_lock);
hrtimer_setup(&rt_b->rt_period_timer, sched_rt_period_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL_HARD);
}
static inline void do_start_rt_bandwidth(struct rt_bandwidth *rt_b)
{
raw_spin_lock(&rt_b->rt_runtime_lock);
if (!rt_b->rt_period_active) {
rt_b->rt_period_active = 1;
/*
* SCHED_DEADLINE updates the bandwidth, as a run away
* RT task with a DL task could hog a CPU. But DL does
* not reset the period. If a deadline task was running
* without an RT task running, it can cause RT tasks to
* throttle when they start up. Kick the timer right away
* to update the period.
*/
hrtimer_forward_now(&rt_b->rt_period_timer, ns_to_ktime(0));
hrtimer_start_expires(&rt_b->rt_period_timer,
HRTIMER_MODE_ABS_PINNED_HARD);
}
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
{
if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
return;
do_start_rt_bandwidth(rt_b);
}
static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
{
hrtimer_cancel(&rt_b->rt_period_timer);
}
#define rt_entity_is_task(rt_se) (!(rt_se)->my_q)
static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
{
WARN_ON_ONCE(!rt_entity_is_task(rt_se));
return container_of(rt_se, struct task_struct, rt);
}
static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
{
/* Cannot fold with non-CONFIG_RT_GROUP_SCHED version, layout */
WARN_ON(!rt_group_sched_enabled() && rt_rq->tg != &root_task_group);
return rt_rq->rq;
}
static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
{
WARN_ON(!rt_group_sched_enabled() && rt_se->rt_rq->tg != &root_task_group);
return rt_se->rt_rq;
}
static inline struct rq *rq_of_rt_se(struct sched_rt_entity *rt_se)
{
struct rt_rq *rt_rq = rt_se->rt_rq;
WARN_ON(!rt_group_sched_enabled() && rt_rq->tg != &root_task_group);
return rt_rq->rq;
}
void unregister_rt_sched_group(struct task_group *tg)
{
if (!rt_group_sched_enabled())
return;
if (tg->rt_se)
destroy_rt_bandwidth(&tg->rt_bandwidth);
}
void free_rt_sched_group(struct task_group *tg)
{
int i;
if (!rt_group_sched_enabled())
return;
for_each_possible_cpu(i) {
if (tg->rt_rq)
kfree(tg->rt_rq[i]);
if (tg->rt_se)
kfree(tg->rt_se[i]);
}
kfree(tg->rt_rq);
kfree(tg->rt_se);
}
void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
struct sched_rt_entity *rt_se, int cpu,
struct sched_rt_entity *parent)
{
struct rq *rq = cpu_rq(cpu);
rt_rq->highest_prio.curr = MAX_RT_PRIO-1;
rt_rq->rt_nr_boosted = 0;
rt_rq->rq = rq;
rt_rq->tg = tg;
tg->rt_rq[cpu] = rt_rq;
tg->rt_se[cpu] = rt_se;
if (!rt_se)
return;
if (!parent)
rt_se->rt_rq = &rq->rt;
else
rt_se->rt_rq = parent->my_q;
rt_se->my_q = rt_rq;
rt_se->parent = parent;
INIT_LIST_HEAD(&rt_se->run_list);
}
int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
{
struct rt_rq *rt_rq;
struct sched_rt_entity *rt_se;
int i;
if (!rt_group_sched_enabled())
return 1;
tg->rt_rq = kcalloc(nr_cpu_ids, sizeof(rt_rq), GFP_KERNEL);
if (!tg->rt_rq)
goto err;
tg->rt_se = kcalloc(nr_cpu_ids, sizeof(rt_se), GFP_KERNEL);
if (!tg->rt_se)
goto err;
init_rt_bandwidth(&tg->rt_bandwidth, ktime_to_ns(global_rt_period()), 0);
for_each_possible_cpu(i) {
rt_rq = kzalloc_node(sizeof(struct rt_rq),
GFP_KERNEL, cpu_to_node(i));
if (!rt_rq)
goto err;
rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
GFP_KERNEL, cpu_to_node(i));
if (!rt_se)
goto err_free_rq;
init_rt_rq(rt_rq);
rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
}
return 1;
err_free_rq:
kfree(rt_rq);
err:
return 0;
}
#else /* !CONFIG_RT_GROUP_SCHED: */
#define rt_entity_is_task(rt_se) (1)
static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
{
return container_of(rt_se, struct task_struct, rt);
}
static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
{
return container_of(rt_rq, struct rq, rt);
}
static inline struct rq *rq_of_rt_se(struct sched_rt_entity *rt_se)
{
struct task_struct *p = rt_task_of(rt_se);
return task_rq(p);
}
static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
{
struct rq *rq = rq_of_rt_se(rt_se);
return &rq->rt;
}
void unregister_rt_sched_group(struct task_group *tg) { }
void free_rt_sched_group(struct task_group *tg) { }
int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
{
return 1;
}
#endif /* !CONFIG_RT_GROUP_SCHED */
static inline bool need_pull_rt_task(struct rq *rq, struct task_struct *prev)
{
/* Try to pull RT tasks here if we lower this rq's prio */
return rq->online && rq->rt.highest_prio.curr > prev->prio;
}
static inline int rt_overloaded(struct rq *rq)
{
return atomic_read(&rq->rd->rto_count);
}
static inline void rt_set_overload(struct rq *rq)
{
if (!rq->online)
return;
cpumask_set_cpu(rq->cpu, rq->rd->rto_mask);
/*
* Make sure the mask is visible before we set
* the overload count. That is checked to determine
* if we should look at the mask. It would be a shame
* if we looked at the mask, but the mask was not
* updated yet.
*
* Matched by the barrier in pull_rt_task().
*/
smp_wmb();
atomic_inc(&rq->rd->rto_count);
}
static inline void rt_clear_overload(struct rq *rq)
{
if (!rq->online)
return;
/* the order here really doesn't matter */
atomic_dec(&rq->rd->rto_count);
cpumask_clear_cpu(rq->cpu, rq->rd->rto_mask);
}
static inline int has_pushable_tasks(struct rq *rq)
{
return !plist_head_empty(&rq->rt.pushable_tasks);
}
static DEFINE_PER_CPU(struct balance_callback, rt_push_head);
static DEFINE_PER_CPU(struct balance_callback, rt_pull_head);
static void push_rt_tasks(struct rq *);
static void pull_rt_task(struct rq *);
static inline void rt_queue_push_tasks(struct rq *rq)
{
if (!has_pushable_tasks(rq))
return;
queue_balance_callback(rq, &per_cpu(rt_push_head, rq->cpu), push_rt_tasks);
}
static inline void rt_queue_pull_task(struct rq *rq)
{
queue_balance_callback(rq, &per_cpu(rt_pull_head, rq->cpu), pull_rt_task);
}
static void enqueue_pushable_task(struct rq *rq, struct task_struct *p)
{
plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
plist_node_init(&p->pushable_tasks, p->prio);
plist_add(&p->pushable_tasks, &rq->rt.pushable_tasks);
/* Update the highest prio pushable task */
if (p->prio < rq->rt.highest_prio.next)
rq->rt.highest_prio.next = p->prio;
if (!rq->rt.overloaded) {
rt_set_overload(rq);
rq->rt.overloaded = 1;
}
}
static void dequeue_pushable_task(struct rq *rq, struct task_struct *p)
{
plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
/* Update the new highest prio pushable task */
if (has_pushable_tasks(rq)) {
p = plist_first_entry(&rq->rt.pushable_tasks,
struct task_struct, pushable_tasks);
rq->rt.highest_prio.next = p->prio;
} else {
rq->rt.highest_prio.next = MAX_RT_PRIO-1;
if (rq->rt.overloaded) {
rt_clear_overload(rq);
rq->rt.overloaded = 0;
}
}
}
static void enqueue_top_rt_rq(struct rt_rq *rt_rq);
static void dequeue_top_rt_rq(struct rt_rq *rt_rq, unsigned int count);
static inline int on_rt_rq(struct sched_rt_entity *rt_se)
{
return rt_se->on_rq;
}
#ifdef CONFIG_UCLAMP_TASK
/*
* Verify the fitness of task @p to run on @cpu taking into account the uclamp
* settings.
*
* This check is only important for heterogeneous systems where uclamp_min value
* is higher than the capacity of a @cpu. For non-heterogeneous system this
* function will always return true.
*
* The function will return true if the capacity of the @cpu is >= the
* uclamp_min and false otherwise.
*
* Note that uclamp_min will be clamped to uclamp_max if uclamp_min
* > uclamp_max.
*/
static inline bool rt_task_fits_capacity(struct task_struct *p, int cpu)
{
unsigned int min_cap;
unsigned int max_cap;
unsigned int cpu_cap;
/* Only heterogeneous systems can benefit from this check */
if (!sched_asym_cpucap_active())
return true;
min_cap = uclamp_eff_value(p, UCLAMP_MIN);
max_cap = uclamp_eff_value(p, UCLAMP_MAX);
cpu_cap = arch_scale_cpu_capacity(cpu);
return cpu_cap >= min(min_cap, max_cap);
}
#else /* !CONFIG_UCLAMP_TASK: */
static inline bool rt_task_fits_capacity(struct task_struct *p, int cpu)
{
return true;
}
#endif /* !CONFIG_UCLAMP_TASK */
#ifdef CONFIG_RT_GROUP_SCHED
static inline u64 sched_rt_runtime(struct rt_rq *rt_rq)
{
return rt_rq->rt_runtime;
}
static inline u64 sched_rt_period(struct rt_rq *rt_rq)
{
return ktime_to_ns(rt_rq->tg->rt_bandwidth.rt_period);
}
typedef struct task_group *rt_rq_iter_t;
static inline struct task_group *next_task_group(struct task_group *tg)
{
if (!rt_group_sched_enabled()) {
WARN_ON(tg != &root_task_group);
return NULL;
}
do {
tg = list_entry_rcu(tg->list.next,
typeof(struct task_group), list);
} while (&tg->list != &task_groups && task_group_is_autogroup(tg));
if (&tg->list == &task_groups)
tg = NULL;
return tg;
}
#define for_each_rt_rq(rt_rq, iter, rq) \
for (iter = &root_task_group; \
iter && (rt_rq = iter->rt_rq[cpu_of(rq)]); \
iter = next_task_group(iter))
#define for_each_sched_rt_entity(rt_se) \
for (; rt_se; rt_se = rt_se->parent)
static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
{
return rt_se->my_q;
}
static void enqueue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags);
static void dequeue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags);
static void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
{
struct task_struct *donor = rq_of_rt_rq(rt_rq)->donor;
struct rq *rq = rq_of_rt_rq(rt_rq);
struct sched_rt_entity *rt_se;
int cpu = cpu_of(rq);
rt_se = rt_rq->tg->rt_se[cpu];
if (rt_rq->rt_nr_running) {
if (!rt_se)
enqueue_top_rt_rq(rt_rq);
else if (!on_rt_rq(rt_se))
enqueue_rt_entity(rt_se, 0);
if (rt_rq->highest_prio.curr < donor->prio)
resched_curr(rq);
}
}
static void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
{
struct sched_rt_entity *rt_se;
int cpu = cpu_of(rq_of_rt_rq(rt_rq));
rt_se = rt_rq->tg->rt_se[cpu];
if (!rt_se) {
dequeue_top_rt_rq(rt_rq, rt_rq->rt_nr_running);
/* Kick cpufreq (see the comment in kernel/sched/sched.h). */
cpufreq_update_util(rq_of_rt_rq(rt_rq), 0);
}
else if (on_rt_rq(rt_se))
dequeue_rt_entity(rt_se, 0);
}
static inline int rt_rq_throttled(struct rt_rq *rt_rq)
{
return rt_rq->rt_throttled && !rt_rq->rt_nr_boosted;
}
static int rt_se_boosted(struct sched_rt_entity *rt_se)
{
struct rt_rq *rt_rq = group_rt_rq(rt_se);
struct task_struct *p;
if (rt_rq)
return !!rt_rq->rt_nr_boosted;
p = rt_task_of(rt_se);
return p->prio != p->normal_prio;
}
static inline const struct cpumask *sched_rt_period_mask(void)
{
return this_rq()->rd->span;
}
static inline
struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
{
return container_of(rt_b, struct task_group, rt_bandwidth)->rt_rq[cpu];
}
static inline struct rt_bandwidth *sched_rt_bandwidth(struct rt_rq *rt_rq)
{
return &rt_rq->tg->rt_bandwidth;
}
bool sched_rt_bandwidth_account(struct rt_rq *rt_rq)
{
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
return (hrtimer_active(&rt_b->rt_period_timer) ||
rt_rq->rt_time < rt_b->rt_runtime);
}
/*
* We ran out of runtime, see if we can borrow some from our neighbours.
*/
static void do_balance_runtime(struct rt_rq *rt_rq)
{
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
struct root_domain *rd = rq_of_rt_rq(rt_rq)->rd;
int i, weight;
u64 rt_period;
weight = cpumask_weight(rd->span);
raw_spin_lock(&rt_b->rt_runtime_lock);
rt_period = ktime_to_ns(rt_b->rt_period);
for_each_cpu(i, rd->span) {
struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
s64 diff;
if (iter == rt_rq)
continue;
raw_spin_lock(&iter->rt_runtime_lock);
/*
* Either all rqs have inf runtime and there's nothing to steal
* or __disable_runtime() below sets a specific rq to inf to
* indicate its been disabled and disallow stealing.
*/
if (iter->rt_runtime == RUNTIME_INF)
goto next;
/*
* From runqueues with spare time, take 1/n part of their
* spare time, but no more than our period.
*/
diff = iter->rt_runtime - iter->rt_time;
if (diff > 0) {
diff = div_u64((u64)diff, weight);
if (rt_rq->rt_runtime + diff > rt_period)
diff = rt_period - rt_rq->rt_runtime;
iter->rt_runtime -= diff;
rt_rq->rt_runtime += diff;
if (rt_rq->rt_runtime == rt_period) {
raw_spin_unlock(&iter->rt_runtime_lock);
break;
}
}
next:
raw_spin_unlock(&iter->rt_runtime_lock);
}
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
/*
* Ensure this RQ takes back all the runtime it lend to its neighbours.
*/
static void __disable_runtime(struct rq *rq)
{
struct root_domain *rd = rq->rd;
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
if (unlikely(!scheduler_running))
return;
for_each_rt_rq(rt_rq, iter, rq) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
s64 want;
int i;
raw_spin_lock(&rt_b->rt_runtime_lock);
raw_spin_lock(&rt_rq->rt_runtime_lock);
/*
* Either we're all inf and nobody needs to borrow, or we're
* already disabled and thus have nothing to do, or we have
* exactly the right amount of runtime to take out.
*/
if (rt_rq->rt_runtime == RUNTIME_INF ||
rt_rq->rt_runtime == rt_b->rt_runtime)
goto balanced;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
/*
* Calculate the difference between what we started out with
* and what we current have, that's the amount of runtime
* we lend and now have to reclaim.
*/
want = rt_b->rt_runtime - rt_rq->rt_runtime;
/*
* Greedy reclaim, take back as much as we can.
*/
for_each_cpu(i, rd->span) {
struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
s64 diff;
/*
* Can't reclaim from ourselves or disabled runqueues.
*/
if (iter == rt_rq || iter->rt_runtime == RUNTIME_INF)
continue;
raw_spin_lock(&iter->rt_runtime_lock);
if (want > 0) {
diff = min_t(s64, iter->rt_runtime, want);
iter->rt_runtime -= diff;
want -= diff;
} else {
iter->rt_runtime -= want;
want -= want;
}
raw_spin_unlock(&iter->rt_runtime_lock);
if (!want)
break;
}
raw_spin_lock(&rt_rq->rt_runtime_lock);
/*
* We cannot be left wanting - that would mean some runtime
* leaked out of the system.
*/
WARN_ON_ONCE(want);
balanced:
/*
* Disable all the borrow logic by pretending we have inf
* runtime - in which case borrowing doesn't make sense.
*/
rt_rq->rt_runtime = RUNTIME_INF;
rt_rq->rt_throttled = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
raw_spin_unlock(&rt_b->rt_runtime_lock);
/* Make rt_rq available for pick_next_task() */
sched_rt_rq_enqueue(rt_rq);
}
}
static void __enable_runtime(struct rq *rq)
{
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
if (unlikely(!scheduler_running))
return;
/*
* Reset each runqueue's bandwidth settings
*/
for_each_rt_rq(rt_rq, iter, rq) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
raw_spin_lock(&rt_b->rt_runtime_lock);
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_b->rt_runtime;
rt_rq->rt_time = 0;
rt_rq->rt_throttled = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
raw_spin_unlock(&rt_b->rt_runtime_lock);
}
}
static void balance_runtime(struct rt_rq *rt_rq)
{
if (!sched_feat(RT_RUNTIME_SHARE))
return;
if (rt_rq->rt_time > rt_rq->rt_runtime) {
raw_spin_unlock(&rt_rq->rt_runtime_lock);
do_balance_runtime(rt_rq);
raw_spin_lock(&rt_rq->rt_runtime_lock);
}
}
static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun)
{
int i, idle = 1, throttled = 0;
const struct cpumask *span;
span = sched_rt_period_mask();
/*
* FIXME: isolated CPUs should really leave the root task group,
* whether they are isolcpus or were isolated via cpusets, lest
* the timer run on a CPU which does not service all runqueues,
* potentially leaving other CPUs indefinitely throttled. If
* isolation is really required, the user will turn the throttle
* off to kill the perturbations it causes anyway. Meanwhile,
* this maintains functionality for boot and/or troubleshooting.
*/
if (rt_b == &root_task_group.rt_bandwidth)
span = cpu_online_mask;
for_each_cpu(i, span) {
int enqueue = 0;
struct rt_rq *rt_rq = sched_rt_period_rt_rq(rt_b, i);
struct rq *rq = rq_of_rt_rq(rt_rq);
struct rq_flags rf;
int skip;
/*
* When span == cpu_online_mask, taking each rq->lock
* can be time-consuming. Try to avoid it when possible.
*/
raw_spin_lock(&rt_rq->rt_runtime_lock);
if (!sched_feat(RT_RUNTIME_SHARE) && rt_rq->rt_runtime != RUNTIME_INF)
rt_rq->rt_runtime = rt_b->rt_runtime;
skip = !rt_rq->rt_time && !rt_rq->rt_nr_running;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
if (skip)
continue;
rq_lock(rq, &rf);
update_rq_clock(rq);
if (rt_rq->rt_time) {
u64 runtime;
raw_spin_lock(&rt_rq->rt_runtime_lock);
if (rt_rq->rt_throttled)
balance_runtime(rt_rq);
runtime = rt_rq->rt_runtime;
rt_rq->rt_time -= min(rt_rq->rt_time, overrun*runtime);
if (rt_rq->rt_throttled && rt_rq->rt_time < runtime) {
rt_rq->rt_throttled = 0;
enqueue = 1;
/*
* When we're idle and a woken (rt) task is
* throttled wakeup_preempt() will set
* skip_update and the time between the wakeup
* and this unthrottle will get accounted as
* 'runtime'.
*/
if (rt_rq->rt_nr_running && rq->curr == rq->idle)
rq_clock_cancel_skipupdate(rq);
}
if (rt_rq->rt_time || rt_rq->rt_nr_running)
idle = 0;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
} else if (rt_rq->rt_nr_running) {
idle = 0;
if (!rt_rq_throttled(rt_rq))
enqueue = 1;
}
if (rt_rq->rt_throttled)
throttled = 1;
if (enqueue)
sched_rt_rq_enqueue(rt_rq);
rq_unlock(rq, &rf);
}
if (!throttled && (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF))
return 1;
return idle;
}
static int sched_rt_runtime_exceeded(struct rt_rq *rt_rq)
{
u64 runtime = sched_rt_runtime(rt_rq);
if (rt_rq->rt_throttled)
return rt_rq_throttled(rt_rq);
if (runtime >= sched_rt_period(rt_rq))
return 0;
balance_runtime(rt_rq);
runtime = sched_rt_runtime(rt_rq);
if (runtime == RUNTIME_INF)
return 0;
if (rt_rq->rt_time > runtime) {
struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
/*
* Don't actually throttle groups that have no runtime assigned
* but accrue some time due to boosting.
*/
if (likely(rt_b->rt_runtime)) {
rt_rq->rt_throttled = 1;
printk_deferred_once("sched: RT throttling activated\n");
} else {
/*
* In case we did anyway, make it go away,
* replenishment is a joke, since it will replenish us
* with exactly 0 ns.
*/
rt_rq->rt_time = 0;
}
if (rt_rq_throttled(rt_rq)) {
sched_rt_rq_dequeue(rt_rq);
return 1;
}
}
return 0;
}
#else /* !CONFIG_RT_GROUP_SCHED: */
typedef struct rt_rq *rt_rq_iter_t;
#define for_each_rt_rq(rt_rq, iter, rq) \
for ((void) iter, rt_rq = &rq->rt; rt_rq; rt_rq = NULL)
#define for_each_sched_rt_entity(rt_se) \
for (; rt_se; rt_se = NULL)
static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
{
return NULL;
}
static inline void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
if (!rt_rq->rt_nr_running)
return;
enqueue_top_rt_rq(rt_rq);
resched_curr(rq);
}
static inline void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
{
dequeue_top_rt_rq(rt_rq, rt_rq->rt_nr_running);
}
static inline int rt_rq_throttled(struct rt_rq *rt_rq)
{
return false;
}
static inline const struct cpumask *sched_rt_period_mask(void)
{
return cpu_online_mask;
}
static inline
struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
{
return &cpu_rq(cpu)->rt;
}
static void __enable_runtime(struct rq *rq) { }
static void __disable_runtime(struct rq *rq) { }
#endif /* !CONFIG_RT_GROUP_SCHED */
static inline int rt_se_prio(struct sched_rt_entity *rt_se)
{
#ifdef CONFIG_RT_GROUP_SCHED
struct rt_rq *rt_rq = group_rt_rq(rt_se);
if (rt_rq)
return rt_rq->highest_prio.curr;
#endif
return rt_task_of(rt_se)->prio;
}
/*
* Update the current task's runtime statistics. Skip current tasks that
* are not in our scheduling class.
*/
static void update_curr_rt(struct rq *rq)
{
struct task_struct *donor = rq->donor;
s64 delta_exec;
if (donor->sched_class != &rt_sched_class)
return;
delta_exec = update_curr_common(rq);
if (unlikely(delta_exec <= 0))
return;
#ifdef CONFIG_RT_GROUP_SCHED
struct sched_rt_entity *rt_se = &donor->rt;
if (!rt_bandwidth_enabled())
return;
for_each_sched_rt_entity(rt_se) {
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
int exceeded;
if (sched_rt_runtime(rt_rq) != RUNTIME_INF) {
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_time += delta_exec;
exceeded = sched_rt_runtime_exceeded(rt_rq);
if (exceeded)
resched_curr(rq);
raw_spin_unlock(&rt_rq->rt_runtime_lock);
if (exceeded)
do_start_rt_bandwidth(sched_rt_bandwidth(rt_rq));
}
}
#endif /* CONFIG_RT_GROUP_SCHED */
}
static void
dequeue_top_rt_rq(struct rt_rq *rt_rq, unsigned int count)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
BUG_ON(&rq->rt != rt_rq);
if (!rt_rq->rt_queued)
return;
BUG_ON(!rq->nr_running);
sub_nr_running(rq, count);
rt_rq->rt_queued = 0;
}
static void
enqueue_top_rt_rq(struct rt_rq *rt_rq)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
BUG_ON(&rq->rt != rt_rq);
if (rt_rq->rt_queued)
return;
if (rt_rq_throttled(rt_rq))
return;
if (rt_rq->rt_nr_running) {
add_nr_running(rq, rt_rq->rt_nr_running);
rt_rq->rt_queued = 1;
}
/* Kick cpufreq (see the comment in kernel/sched/sched.h). */
cpufreq_update_util(rq, 0);
}
static void
inc_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
/*
* Change rq's cpupri only if rt_rq is the top queue.
*/
if (IS_ENABLED(CONFIG_RT_GROUP_SCHED) && &rq->rt != rt_rq)
return;
if (rq->online && prio < prev_prio)
cpupri_set(&rq->rd->cpupri, rq->cpu, prio);
}
static void
dec_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
{
struct rq *rq = rq_of_rt_rq(rt_rq);
/*
* Change rq's cpupri only if rt_rq is the top queue.
*/
if (IS_ENABLED(CONFIG_RT_GROUP_SCHED) && &rq->rt != rt_rq)
return;
if (rq->online && rt_rq->highest_prio.curr != prev_prio)
cpupri_set(&rq->rd->cpupri, rq->cpu, rt_rq->highest_prio.curr);
}
static void
inc_rt_prio(struct rt_rq *rt_rq, int prio)
{
int prev_prio = rt_rq->highest_prio.curr;
if (prio < prev_prio)
rt_rq->highest_prio.curr = prio;
inc_rt_prio_smp(rt_rq, prio, prev_prio);
}
static void
dec_rt_prio(struct rt_rq *rt_rq, int prio)
{
int prev_prio = rt_rq->highest_prio.curr;
if (rt_rq->rt_nr_running) {
WARN_ON(prio < prev_prio);
/*
* This may have been our highest task, and therefore
* we may have some re-computation to do
*/
if (prio == prev_prio) {
struct rt_prio_array *array = &rt_rq->active;
rt_rq->highest_prio.curr =
sched_find_first_bit(array->bitmap);
}
} else {
rt_rq->highest_prio.curr = MAX_RT_PRIO-1;
}
dec_rt_prio_smp(rt_rq, prio, prev_prio);
}
#ifdef CONFIG_RT_GROUP_SCHED
static void
inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
if (rt_se_boosted(rt_se))
rt_rq->rt_nr_boosted++;
start_rt_bandwidth(&rt_rq->tg->rt_bandwidth);
}
static void
dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
if (rt_se_boosted(rt_se))
rt_rq->rt_nr_boosted--;
WARN_ON(!rt_rq->rt_nr_running && rt_rq->rt_nr_boosted);
}
#else /* !CONFIG_RT_GROUP_SCHED: */
static void
inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
}
static inline
void dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq) {}
#endif /* !CONFIG_RT_GROUP_SCHED */
static inline
unsigned int rt_se_nr_running(struct sched_rt_entity *rt_se)
{
struct rt_rq *group_rq = group_rt_rq(rt_se);
if (group_rq)
return group_rq->rt_nr_running;
else
return 1;
}
static inline
unsigned int rt_se_rr_nr_running(struct sched_rt_entity *rt_se)
{
struct rt_rq *group_rq = group_rt_rq(rt_se);
struct task_struct *tsk;
if (group_rq)
return group_rq->rr_nr_running;
tsk = rt_task_of(rt_se);
return (tsk->policy == SCHED_RR) ? 1 : 0;
}
static inline
void inc_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
int prio = rt_se_prio(rt_se);
WARN_ON(!rt_prio(prio));
rt_rq->rt_nr_running += rt_se_nr_running(rt_se);
rt_rq->rr_nr_running += rt_se_rr_nr_running(rt_se);
inc_rt_prio(rt_rq, prio);
inc_rt_group(rt_se, rt_rq);
}
static inline
void dec_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
{
WARN_ON(!rt_prio(rt_se_prio(rt_se)));
WARN_ON(!rt_rq->rt_nr_running);
rt_rq->rt_nr_running -= rt_se_nr_running(rt_se);
rt_rq->rr_nr_running -= rt_se_rr_nr_running(rt_se);
dec_rt_prio(rt_rq, rt_se_prio(rt_se));
dec_rt_group(rt_se, rt_rq);
}
/*
* Change rt_se->run_list location unless SAVE && !MOVE
*
* assumes ENQUEUE/DEQUEUE flags match
*/
static inline bool move_entity(unsigned int flags)
{
if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) == DEQUEUE_SAVE)
return false;
return true;
}
static void __delist_rt_entity(struct sched_rt_entity *rt_se, struct rt_prio_array *array)
{
list_del_init(&rt_se->run_list);
if (list_empty(array->queue + rt_se_prio(rt_se)))
__clear_bit(rt_se_prio(rt_se), array->bitmap);
rt_se->on_list = 0;
}
static inline struct sched_statistics *
__schedstats_from_rt_se(struct sched_rt_entity *rt_se)
{
/* schedstats is not supported for rt group. */
if (!rt_entity_is_task(rt_se))
return NULL;
return &rt_task_of(rt_se)->stats;
}
static inline void
update_stats_wait_start_rt(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se)
{
struct sched_statistics *stats;
struct task_struct *p = NULL;
if (!schedstat_enabled())
return;
if (rt_entity_is_task(rt_se))
p = rt_task_of(rt_se);
stats = __schedstats_from_rt_se(rt_se);
if (!stats)
return;
__update_stats_wait_start(rq_of_rt_rq(rt_rq), p, stats);
}
static inline void
update_stats_enqueue_sleeper_rt(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se)
{
struct sched_statistics *stats;
struct task_struct *p = NULL;
if (!schedstat_enabled())
return;
if (rt_entity_is_task(rt_se))
p = rt_task_of(rt_se);
stats = __schedstats_from_rt_se(rt_se);
if (!stats)
return;
__update_stats_enqueue_sleeper(rq_of_rt_rq(rt_rq), p, stats);
}
static inline void
update_stats_enqueue_rt(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
int flags)
{
if (!schedstat_enabled())
return;
if (flags & ENQUEUE_WAKEUP)
update_stats_enqueue_sleeper_rt(rt_rq, rt_se);
}
static inline void
update_stats_wait_end_rt(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se)
{
struct sched_statistics *stats;
struct task_struct *p = NULL;
if (!schedstat_enabled())
return;
if (rt_entity_is_task(rt_se))
p = rt_task_of(rt_se);
stats = __schedstats_from_rt_se(rt_se);
if (!stats)
return;
__update_stats_wait_end(rq_of_rt_rq(rt_rq), p, stats);
}
static inline void
update_stats_dequeue_rt(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
int flags)
{
struct task_struct *p = NULL;
if (!schedstat_enabled())
return;
if (rt_entity_is_task(rt_se))
p = rt_task_of(rt_se);
if ((flags & DEQUEUE_SLEEP) && p) {
unsigned int state;
state = READ_ONCE(p->__state);
if (state & TASK_INTERRUPTIBLE)
__schedstat_set(p->stats.sleep_start,
rq_clock(rq_of_rt_rq(rt_rq)));
if (state & TASK_UNINTERRUPTIBLE)
__schedstat_set(p->stats.block_start,
rq_clock(rq_of_rt_rq(rt_rq)));
}
}
static void __enqueue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags)
{
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
struct rt_prio_array *array = &rt_rq->active;
struct rt_rq *group_rq = group_rt_rq(rt_se);
struct list_head *queue = array->queue + rt_se_prio(rt_se);
/*
* Don't enqueue the group if its throttled, or when empty.
* The latter is a consequence of the former when a child group
* get throttled and the current group doesn't have any other
* active members.
*/
if (group_rq && (rt_rq_throttled(group_rq) || !group_rq->rt_nr_running)) {
if (rt_se->on_list)
__delist_rt_entity(rt_se, array);
return;
}
if (move_entity(flags)) {
WARN_ON_ONCE(rt_se->on_list);
if (flags & ENQUEUE_HEAD)
list_add(&rt_se->run_list, queue);
else
list_add_tail(&rt_se->run_list, queue);
__set_bit(rt_se_prio(rt_se), array->bitmap);
rt_se->on_list = 1;
}
rt_se->on_rq = 1;
inc_rt_tasks(rt_se, rt_rq);
}
static void __dequeue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags)
{
struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
struct rt_prio_array *array = &rt_rq->active;
if (move_entity(flags)) {
WARN_ON_ONCE(!rt_se->on_list);
__delist_rt_entity(rt_se, array);
}
rt_se->on_rq = 0;
dec_rt_tasks(rt_se, rt_rq);
}
/*
* Because the prio of an upper entry depends on the lower
* entries, we must remove entries top - down.
*/
static void dequeue_rt_stack(struct sched_rt_entity *rt_se, unsigned int flags)
{
struct sched_rt_entity *back = NULL;
unsigned int rt_nr_running;
for_each_sched_rt_entity(rt_se) {
rt_se->back = back;
back = rt_se;
}
rt_nr_running = rt_rq_of_se(back)->rt_nr_running;
for (rt_se = back; rt_se; rt_se = rt_se->back) {
if (on_rt_rq(rt_se))
__dequeue_rt_entity(rt_se, flags);
}
dequeue_top_rt_rq(rt_rq_of_se(back), rt_nr_running);
}
static void enqueue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags)
{
struct rq *rq = rq_of_rt_se(rt_se);
update_stats_enqueue_rt(rt_rq_of_se(rt_se), rt_se, flags);
dequeue_rt_stack(rt_se, flags);
for_each_sched_rt_entity(rt_se)
__enqueue_rt_entity(rt_se, flags);
enqueue_top_rt_rq(&rq->rt);
}
static void dequeue_rt_entity(struct sched_rt_entity *rt_se, unsigned int flags)
{
struct rq *rq = rq_of_rt_se(rt_se);
update_stats_dequeue_rt(rt_rq_of_se(rt_se), rt_se, flags);
dequeue_rt_stack(rt_se, flags);
for_each_sched_rt_entity(rt_se) {
struct rt_rq *rt_rq = group_rt_rq(rt_se);
if (rt_rq && rt_rq->rt_nr_running)
__enqueue_rt_entity(rt_se, flags);
}
enqueue_top_rt_rq(&rq->rt);
}
/*
* Adding/removing a task to/from a priority array:
*/
static void
enqueue_task_rt(struct rq *rq, struct task_struct *p, int flags)
{
struct sched_rt_entity *rt_se = &p->rt;
if (flags & ENQUEUE_WAKEUP)
rt_se->timeout = 0;
check_schedstat_required();
update_stats_wait_start_rt(rt_rq_of_se(rt_se), rt_se);
enqueue_rt_entity(rt_se, flags);
if (task_is_blocked(p))
return;
if (!task_current(rq, p) && p->nr_cpus_allowed > 1)
enqueue_pushable_task(rq, p);
}
static bool dequeue_task_rt(struct rq *rq, struct task_struct *p, int flags)
{
struct sched_rt_entity *rt_se = &p->rt;
update_curr_rt(rq);
dequeue_rt_entity(rt_se, flags);
dequeue_pushable_task(rq, p);
return true;
}
/*
* Put task to the head or the end of the run list without the overhead of
* dequeue followed by enqueue.
*/
static void
requeue_rt_entity(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se, int head)
{
if (on_rt_rq(rt_se)) {
struct rt_prio_array *array = &rt_rq->active;
struct list_head *queue = array->queue + rt_se_prio(rt_se);
if (head)
list_move(&rt_se->run_list, queue);
else
list_move_tail(&rt_se->run_list, queue);
}
}
static void requeue_task_rt(struct rq *rq, struct task_struct *p, int head)
{
struct sched_rt_entity *rt_se = &p->rt;
struct rt_rq *rt_rq;
for_each_sched_rt_entity(rt_se) {
rt_rq = rt_rq_of_se(rt_se);
requeue_rt_entity(rt_rq, rt_se, head);
}
}
static void yield_task_rt(struct rq *rq)
{
requeue_task_rt(rq, rq->curr, 0);
}
static int find_lowest_rq(struct task_struct *task);
static int
select_task_rq_rt(struct task_struct *p, int cpu, int flags)
{
struct task_struct *curr, *donor;
struct rq *rq;
bool test;
/* For anything but wake ups, just return the task_cpu */
if (!(flags & (WF_TTWU | WF_FORK)))
goto out;
rq = cpu_rq(cpu);
rcu_read_lock();
curr = READ_ONCE(rq->curr); /* unlocked access */
donor = READ_ONCE(rq->donor);
/*
* If the current task on @p's runqueue is an RT task, then
* try to see if we can wake this RT task up on another
* runqueue. Otherwise simply start this RT task
* on its current runqueue.
*
* We want to avoid overloading runqueues. If the woken
* task is a higher priority, then it will stay on this CPU
* and the lower prio task should be moved to another CPU.
* Even though this will probably make the lower prio task
* lose its cache, we do not want to bounce a higher task
* around just because it gave up its CPU, perhaps for a
* lock?
*
* For equal prio tasks, we just let the scheduler sort it out.
*
* Otherwise, just let it ride on the affine RQ and the
* post-schedule router will push the preempted task away
*
* This test is optimistic, if we get it wrong the load-balancer
* will have to sort it out.
*
* We take into account the capacity of the CPU to ensure it fits the
* requirement of the task - which is only important on heterogeneous
* systems like big.LITTLE.
*/
test = curr &&
unlikely(rt_task(donor)) &&
(curr->nr_cpus_allowed < 2 || donor->prio <= p->prio);
if (test || !rt_task_fits_capacity(p, cpu)) {
int target = find_lowest_rq(p);
/*
* Bail out if we were forcing a migration to find a better
* fitting CPU but our search failed.
*/
if (!test && target != -1 && !rt_task_fits_capacity(p, target))
goto out_unlock;
/*
* Don't bother moving it if the destination CPU is
* not running a lower priority task.
*/
if (target != -1 &&
p->prio < cpu_rq(target)->rt.highest_prio.curr)
cpu = target;
}
out_unlock:
rcu_read_unlock();
out:
return cpu;
}
static void check_preempt_equal_prio(struct rq *rq, struct task_struct *p)
{
if (rq->curr->nr_cpus_allowed == 1 ||
!cpupri_find(&rq->rd->cpupri, rq->donor, NULL))
return;
/*
* p is migratable, so let's not schedule it and
* see if it is pushed or pulled somewhere else.
*/
if (p->nr_cpus_allowed != 1 &&
cpupri_find(&rq->rd->cpupri, p, NULL))
return;
/*
* There appear to be other CPUs that can accept
* the current task but none can run 'p', so lets reschedule
* to try and push the current task away:
*/
requeue_task_rt(rq, p, 1);
resched_curr(rq);
}
static int balance_rt(struct rq *rq, struct task_struct *p, struct rq_flags *rf)
{
if (!on_rt_rq(&p->rt) && need_pull_rt_task(rq, p)) {
/*
* This is OK, because current is on_cpu, which avoids it being
* picked for load-balance and preemption/IRQs are still
* disabled avoiding further scheduler activity on it and we've
* not yet started the picking loop.
*/
rq_unpin_lock(rq, rf);
pull_rt_task(rq);
rq_repin_lock(rq, rf);
}
return sched_stop_runnable(rq) || sched_dl_runnable(rq) || sched_rt_runnable(rq);
}
/*
* Preempt the current task with a newly woken task if needed:
*/
static void wakeup_preempt_rt(struct rq *rq, struct task_struct *p, int flags)
{
struct task_struct *donor = rq->donor;
if (p->prio < donor->prio) {
resched_curr(rq);
return;
}
/*
* If:
*
* - the newly woken task is of equal priority to the current task
* - the newly woken task is non-migratable while current is migratable
* - current will be preempted on the next reschedule
*
* we should check to see if current can readily move to a different
* cpu. If so, we will reschedule to allow the push logic to try
* to move current somewhere else, making room for our non-migratable
* task.
*/
if (p->prio == donor->prio && !test_tsk_need_resched(rq->curr))
check_preempt_equal_prio(rq, p);
}
static inline void set_next_task_rt(struct rq *rq, struct task_struct *p, bool first)
{
struct sched_rt_entity *rt_se = &p->rt;
struct rt_rq *rt_rq = &rq->rt;
p->se.exec_start = rq_clock_task(rq);
if (on_rt_rq(&p->rt))
update_stats_wait_end_rt(rt_rq, rt_se);
/* The running task is never eligible for pushing */
dequeue_pushable_task(rq, p);
if (!first)
return;
/*
* If prev task was rt, put_prev_task() has already updated the
* utilization. We only care of the case where we start to schedule a
* rt task
*/
if (rq->donor->sched_class != &rt_sched_class)
update_rt_rq_load_avg(rq_clock_pelt(rq), rq, 0);
rt_queue_push_tasks(rq);
}
static struct sched_rt_entity *pick_next_rt_entity(struct rt_rq *rt_rq)
{
struct rt_prio_array *array = &rt_rq->active;
struct sched_rt_entity *next = NULL;
struct list_head *queue;
int idx;
idx = sched_find_first_bit(array->bitmap);
BUG_ON(idx >= MAX_RT_PRIO);
queue = array->queue + idx;
if (WARN_ON_ONCE(list_empty(queue)))
return NULL;
next = list_entry(queue->next, struct sched_rt_entity, run_list);
return next;
}
static struct task_struct *_pick_next_task_rt(struct rq *rq)
{
struct sched_rt_entity *rt_se;
struct rt_rq *rt_rq = &rq->rt;
do {
rt_se = pick_next_rt_entity(rt_rq);
if (unlikely(!rt_se))
return NULL;
rt_rq = group_rt_rq(rt_se);
} while (rt_rq);
return rt_task_of(rt_se);
}
static struct task_struct *pick_task_rt(struct rq *rq)
{
struct task_struct *p;
if (!sched_rt_runnable(rq))
return NULL;
p = _pick_next_task_rt(rq);
return p;
}
static void put_prev_task_rt(struct rq *rq, struct task_struct *p, struct task_struct *next)
{
struct sched_rt_entity *rt_se = &p->rt;
struct rt_rq *rt_rq = &rq->rt;
if (on_rt_rq(&p->rt))
update_stats_wait_start_rt(rt_rq, rt_se);
update_curr_rt(rq);
update_rt_rq_load_avg(rq_clock_pelt(rq), rq, 1);
if (task_is_blocked(p))
return;
/*
* The previous task needs to be made eligible for pushing
* if it is still active
*/
if (on_rt_rq(&p->rt) && p->nr_cpus_allowed > 1)
enqueue_pushable_task(rq, p);
}
/* Only try algorithms three times */
#define RT_MAX_TRIES 3
/*
* Return the highest pushable rq's task, which is suitable to be executed
* on the CPU, NULL otherwise
*/
static struct task_struct *pick_highest_pushable_task(struct rq *rq, int cpu)
{
struct plist_head *head = &rq->rt.pushable_tasks;
struct task_struct *p;
if (!has_pushable_tasks(rq))
return NULL;
plist_for_each_entry(p, head, pushable_tasks) {
if (task_is_pushable(rq, p, cpu))
return p;
}
return NULL;
}
static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask);
static int find_lowest_rq(struct task_struct *task)
{
struct sched_domain *sd;
struct cpumask *lowest_mask = this_cpu_cpumask_var_ptr(local_cpu_mask);
int this_cpu = smp_processor_id();
int cpu = task_cpu(task);
int ret;
/* Make sure the mask is initialized first */
if (unlikely(!lowest_mask))
return -1;
if (task->nr_cpus_allowed == 1)
return -1; /* No other targets possible */
/*
* If we're on asym system ensure we consider the different capacities
* of the CPUs when searching for the lowest_mask.
*/
if (sched_asym_cpucap_active()) {
ret = cpupri_find_fitness(&task_rq(task)->rd->cpupri,
task, lowest_mask,
rt_task_fits_capacity);
} else {
ret = cpupri_find(&task_rq(task)->rd->cpupri,
task, lowest_mask);
}
if (!ret)
return -1; /* No targets found */
/*
* At this point we have built a mask of CPUs representing the
* lowest priority tasks in the system. Now we want to elect
* the best one based on our affinity and topology.
*
* We prioritize the last CPU that the task executed on since
* it is most likely cache-hot in that location.
*/
if (cpumask_test_cpu(cpu, lowest_mask))
return cpu;
/*
* Otherwise, we consult the sched_domains span maps to figure
* out which CPU is logically closest to our hot cache data.
*/
if (!cpumask_test_cpu(this_cpu, lowest_mask))
this_cpu = -1; /* Skip this_cpu opt if not among lowest */
rcu_read_lock();
for_each_domain(cpu, sd) {
if (sd->flags & SD_WAKE_AFFINE) {
int best_cpu;
/*
* "this_cpu" is cheaper to preempt than a
* remote processor.
*/
if (this_cpu != -1 &&
cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
rcu_read_unlock();
return this_cpu;
}
best_cpu = cpumask_any_and_distribute(lowest_mask,
sched_domain_span(sd));
if (best_cpu < nr_cpu_ids) {
rcu_read_unlock();
return best_cpu;
}
}
}
rcu_read_unlock();
/*
* And finally, if there were no matches within the domains
* just give the caller *something* to work with from the compatible
* locations.
*/
if (this_cpu != -1)
return this_cpu;
cpu = cpumask_any_distribute(lowest_mask);
if (cpu < nr_cpu_ids)
return cpu;
return -1;
}
static struct task_struct *pick_next_pushable_task(struct rq *rq)
{
struct task_struct *p;
if (!has_pushable_tasks(rq))
return NULL;
p = plist_first_entry(&rq->rt.pushable_tasks,
struct task_struct, pushable_tasks);
BUG_ON(rq->cpu != task_cpu(p));
BUG_ON(task_current(rq, p));
BUG_ON(task_current_donor(rq, p));
BUG_ON(p->nr_cpus_allowed <= 1);
BUG_ON(!task_on_rq_queued(p));
BUG_ON(!rt_task(p));
return p;
}
/* Will lock the rq it finds */
static struct rq *find_lock_lowest_rq(struct task_struct *task, struct rq *rq)
{
struct rq *lowest_rq = NULL;
int tries;
int cpu;
for (tries = 0; tries < RT_MAX_TRIES; tries++) {
cpu = find_lowest_rq(task);
if ((cpu == -1) || (cpu == rq->cpu))
break;
lowest_rq = cpu_rq(cpu);
if (lowest_rq->rt.highest_prio.curr <= task->prio) {
/*
* Target rq has tasks of equal or higher priority,
* retrying does not release any lock and is unlikely
* to yield a different result.
*/
lowest_rq = NULL;
break;
}
/* if the prio of this runqueue changed, try again */
if (double_lock_balance(rq, lowest_rq)) {
/*
* We had to unlock the run queue. In
* the mean time, task could have
* migrated already or had its affinity changed,
* therefore check if the task is still at the
* head of the pushable tasks list.
* It is possible the task was scheduled, set
* "migrate_disabled" and then got preempted, so we must
* check the task migration disable flag here too.
*/
if (unlikely(is_migration_disabled(task) ||
!cpumask_test_cpu(lowest_rq->cpu, &task->cpus_mask) ||
task != pick_next_pushable_task(rq))) {
double_unlock_balance(rq, lowest_rq);
lowest_rq = NULL;
break;
}
}
/* If this rq is still suitable use it. */
if (lowest_rq->rt.highest_prio.curr > task->prio)
break;
/* try again */
double_unlock_balance(rq, lowest_rq);
lowest_rq = NULL;
}
return lowest_rq;
}
/*
* If the current CPU has more than one RT task, see if the non
* running task can migrate over to a CPU that is running a task
* of lesser priority.
*/
static int push_rt_task(struct rq *rq, bool pull)
{
struct task_struct *next_task;
struct rq *lowest_rq;
int ret = 0;
if (!rq->rt.overloaded)
return 0;
next_task = pick_next_pushable_task(rq);
if (!next_task)
return 0;
retry:
/*
* It's possible that the next_task slipped in of
* higher priority than current. If that's the case
* just reschedule current.
*/
if (unlikely(next_task->prio < rq->donor->prio)) {
resched_curr(rq);
return 0;
}
if (is_migration_disabled(next_task)) {
struct task_struct *push_task = NULL;
int cpu;
if (!pull || rq->push_busy)
return 0;
/*
* Invoking find_lowest_rq() on anything but an RT task doesn't
* make sense. Per the above priority check, curr has to
* be of higher priority than next_task, so no need to
* reschedule when bailing out.
*
* Note that the stoppers are masqueraded as SCHED_FIFO
* (cf. sched_set_stop_task()), so we can't rely on rt_task().
*/
if (rq->donor->sched_class != &rt_sched_class)
return 0;
cpu = find_lowest_rq(rq->curr);
if (cpu == -1 || cpu == rq->cpu)
return 0;
/*
* Given we found a CPU with lower priority than @next_task,
* therefore it should be running. However we cannot migrate it
* to this other CPU, instead attempt to push the current
* running task on this CPU away.
*/
push_task = get_push_task(rq);
if (push_task) {
preempt_disable();
raw_spin_rq_unlock(rq);
stop_one_cpu_nowait(rq->cpu, push_cpu_stop,
push_task, &rq->push_work);
preempt_enable();
raw_spin_rq_lock(rq);
}
return 0;
}
if (WARN_ON(next_task == rq->curr))
return 0;
/* We might release rq lock */
get_task_struct(next_task);
/* find_lock_lowest_rq locks the rq if found */
lowest_rq = find_lock_lowest_rq(next_task, rq);
if (!lowest_rq) {
struct task_struct *task;
/*
* find_lock_lowest_rq releases rq->lock
* so it is possible that next_task has migrated.
*
* We need to make sure that the task is still on the same
* run-queue and is also still the next task eligible for
* pushing.
*/
task = pick_next_pushable_task(rq);
if (task == next_task) {
/*
* The task hasn't migrated, and is still the next
* eligible task, but we failed to find a run-queue
* to push it to. Do not retry in this case, since
* other CPUs will pull from us when ready.
*/
goto out;
}
if (!task)
/* No more tasks, just exit */
goto out;
/*
* Something has shifted, try again.
*/
put_task_struct(next_task);
next_task = task;
goto retry;
}
move_queued_task_locked(rq, lowest_rq, next_task);
resched_curr(lowest_rq);
ret = 1;
double_unlock_balance(rq, lowest_rq);
out:
put_task_struct(next_task);
return ret;
}
static void push_rt_tasks(struct rq *rq)
{
/* push_rt_task will return true if it moved an RT */
while (push_rt_task(rq, false))
;
}
#ifdef HAVE_RT_PUSH_IPI
/*
* When a high priority task schedules out from a CPU and a lower priority
* task is scheduled in, a check is made to see if there's any RT tasks
* on other CPUs that are waiting to run because a higher priority RT task
* is currently running on its CPU. In this case, the CPU with multiple RT
* tasks queued on it (overloaded) needs to be notified that a CPU has opened
* up that may be able to run one of its non-running queued RT tasks.
*
* All CPUs with overloaded RT tasks need to be notified as there is currently
* no way to know which of these CPUs have the highest priority task waiting
* to run. Instead of trying to take a spinlock on each of these CPUs,
* which has shown to cause large latency when done on machines with many
* CPUs, sending an IPI to the CPUs to have them push off the overloaded
* RT tasks waiting to run.
*
* Just sending an IPI to each of the CPUs is also an issue, as on large
* count CPU machines, this can cause an IPI storm on a CPU, especially
* if its the only CPU with multiple RT tasks queued, and a large number
* of CPUs scheduling a lower priority task at the same time.
*
* Each root domain has its own IRQ work function that can iterate over
* all CPUs with RT overloaded tasks. Since all CPUs with overloaded RT
* task must be checked if there's one or many CPUs that are lowering
* their priority, there's a single IRQ work iterator that will try to
* push off RT tasks that are waiting to run.
*
* When a CPU schedules a lower priority task, it will kick off the
* IRQ work iterator that will jump to each CPU with overloaded RT tasks.
* As it only takes the first CPU that schedules a lower priority task
* to start the process, the rto_start variable is incremented and if
* the atomic result is one, then that CPU will try to take the rto_lock.
* This prevents high contention on the lock as the process handles all
* CPUs scheduling lower priority tasks.
*
* All CPUs that are scheduling a lower priority task will increment the
* rt_loop_next variable. This will make sure that the IRQ work iterator
* checks all RT overloaded CPUs whenever a CPU schedules a new lower
* priority task, even if the iterator is in the middle of a scan. Incrementing
* the rt_loop_next will cause the iterator to perform another scan.
*
*/
static int rto_next_cpu(struct root_domain *rd)
{
int next;
int cpu;
/*
* When starting the IPI RT pushing, the rto_cpu is set to -1,
* rt_next_cpu() will simply return the first CPU found in
* the rto_mask.
*
* If rto_next_cpu() is called with rto_cpu is a valid CPU, it
* will return the next CPU found in the rto_mask.
*
* If there are no more CPUs left in the rto_mask, then a check is made
* against rto_loop and rto_loop_next. rto_loop is only updated with
* the rto_lock held, but any CPU may increment the rto_loop_next
* without any locking.
*/
for (;;) {
/* When rto_cpu is -1 this acts like cpumask_first() */
cpu = cpumask_next(rd->rto_cpu, rd->rto_mask);
rd->rto_cpu = cpu;
if (cpu < nr_cpu_ids)
return cpu;
rd->rto_cpu = -1;
/*
* ACQUIRE ensures we see the @rto_mask changes
* made prior to the @next value observed.
*
* Matches WMB in rt_set_overload().
*/
next = atomic_read_acquire(&rd->rto_loop_next);
if (rd->rto_loop == next)
break;
rd->rto_loop = next;
}
return -1;
}
static inline bool rto_start_trylock(atomic_t *v)
{
return !atomic_cmpxchg_acquire(v, 0, 1);
}
static inline void rto_start_unlock(atomic_t *v)
{
atomic_set_release(v, 0);
}
static void tell_cpu_to_push(struct rq *rq)
{
int cpu = -1;
/* Keep the loop going if the IPI is currently active */
atomic_inc(&rq->rd->rto_loop_next);
/* Only one CPU can initiate a loop at a time */
if (!rto_start_trylock(&rq->rd->rto_loop_start))
return;
raw_spin_lock(&rq->rd->rto_lock);
/*
* The rto_cpu is updated under the lock, if it has a valid CPU
* then the IPI is still running and will continue due to the
* update to loop_next, and nothing needs to be done here.
* Otherwise it is finishing up and an IPI needs to be sent.
*/
if (rq->rd->rto_cpu < 0)
cpu = rto_next_cpu(rq->rd);
raw_spin_unlock(&rq->rd->rto_lock);
rto_start_unlock(&rq->rd->rto_loop_start);
if (cpu >= 0) {
/* Make sure the rd does not get freed while pushing */
sched_get_rd(rq->rd);
irq_work_queue_on(&rq->rd->rto_push_work, cpu);
}
}
/* Called from hardirq context */
void rto_push_irq_work_func(struct irq_work *work)
{
struct root_domain *rd =
container_of(work, struct root_domain, rto_push_work);
struct rq *rq;
int cpu;
rq = this_rq();
/*
* We do not need to grab the lock to check for has_pushable_tasks.
* When it gets updated, a check is made if a push is possible.
*/
if (has_pushable_tasks(rq)) {
raw_spin_rq_lock(rq);
while (push_rt_task(rq, true))
;
raw_spin_rq_unlock(rq);
}
raw_spin_lock(&rd->rto_lock);
/* Pass the IPI to the next rt overloaded queue */
cpu = rto_next_cpu(rd);
raw_spin_unlock(&rd->rto_lock);
if (cpu < 0) {
sched_put_rd(rd);
return;
}
/* Try the next RT overloaded CPU */
irq_work_queue_on(&rd->rto_push_work, cpu);
}
#endif /* HAVE_RT_PUSH_IPI */
static void pull_rt_task(struct rq *this_rq)
{
int this_cpu = this_rq->cpu, cpu;
bool resched = false;
struct task_struct *p, *push_task;
struct rq *src_rq;
int rt_overload_count = rt_overloaded(this_rq);
if (likely(!rt_overload_count))
return;
/*
* Match the barrier from rt_set_overloaded; this guarantees that if we
* see overloaded we must also see the rto_mask bit.
*/
smp_rmb();
/* If we are the only overloaded CPU do nothing */
if (rt_overload_count == 1 &&
cpumask_test_cpu(this_rq->cpu, this_rq->rd->rto_mask))
return;
#ifdef HAVE_RT_PUSH_IPI
if (sched_feat(RT_PUSH_IPI)) {
tell_cpu_to_push(this_rq);
return;
}
#endif
for_each_cpu(cpu, this_rq->rd->rto_mask) {
if (this_cpu == cpu)
continue;
src_rq = cpu_rq(cpu);
/*
* Don't bother taking the src_rq->lock if the next highest
* task is known to be lower-priority than our current task.
* This may look racy, but if this value is about to go
* logically higher, the src_rq will push this task away.
* And if its going logically lower, we do not care
*/
if (src_rq->rt.highest_prio.next >=
this_rq->rt.highest_prio.curr)
continue;
/*
* We can potentially drop this_rq's lock in
* double_lock_balance, and another CPU could
* alter this_rq
*/
push_task = NULL;
double_lock_balance(this_rq, src_rq);
/*
* We can pull only a task, which is pushable
* on its rq, and no others.
*/
p = pick_highest_pushable_task(src_rq, this_cpu);
/*
* Do we have an RT task that preempts
* the to-be-scheduled task?
*/
if (p && (p->prio < this_rq->rt.highest_prio.curr)) {
WARN_ON(p == src_rq->curr);
WARN_ON(!task_on_rq_queued(p));
/*
* There's a chance that p is higher in priority
* than what's currently running on its CPU.
* This is just that p is waking up and hasn't
* had a chance to schedule. We only pull
* p if it is lower in priority than the
* current task on the run queue
*/
if (p->prio < src_rq->donor->prio)
goto skip;
if (is_migration_disabled(p)) {
push_task = get_push_task(src_rq);
} else {
move_queued_task_locked(src_rq, this_rq, p);
resched = true;
}
/*
* We continue with the search, just in
* case there's an even higher prio task
* in another runqueue. (low likelihood
* but possible)
*/
}
skip:
double_unlock_balance(this_rq, src_rq);
if (push_task) {
preempt_disable();
raw_spin_rq_unlock(this_rq);
stop_one_cpu_nowait(src_rq->cpu, push_cpu_stop,
push_task, &src_rq->push_work);
preempt_enable();
raw_spin_rq_lock(this_rq);
}
}
if (resched)
resched_curr(this_rq);
}
/*
* If we are not running and we are not going to reschedule soon, we should
* try to push tasks away now
*/
static void task_woken_rt(struct rq *rq, struct task_struct *p)
{
bool need_to_push = !task_on_cpu(rq, p) &&
!test_tsk_need_resched(rq->curr) &&
p->nr_cpus_allowed > 1 &&
(dl_task(rq->donor) || rt_task(rq->donor)) &&
(rq->curr->nr_cpus_allowed < 2 ||
rq->donor->prio <= p->prio);
if (need_to_push)
push_rt_tasks(rq);
}
/* Assumes rq->lock is held */
static void rq_online_rt(struct rq *rq)
{
if (rq->rt.overloaded)
rt_set_overload(rq);
__enable_runtime(rq);
cpupri_set(&rq->rd->cpupri, rq->cpu, rq->rt.highest_prio.curr);
}
/* Assumes rq->lock is held */
static void rq_offline_rt(struct rq *rq)
{
if (rq->rt.overloaded)
rt_clear_overload(rq);
__disable_runtime(rq);
cpupri_set(&rq->rd->cpupri, rq->cpu, CPUPRI_INVALID);
}
/*
* When switch from the rt queue, we bring ourselves to a position
* that we might want to pull RT tasks from other runqueues.
*/
static void switched_from_rt(struct rq *rq, struct task_struct *p)
{
/*
* If there are other RT tasks then we will reschedule
* and the scheduling of the other RT tasks will handle
* the balancing. But if we are the last RT task
* we may need to handle the pulling of RT tasks
* now.
*/
if (!task_on_rq_queued(p) || rq->rt.rt_nr_running)
return;
rt_queue_pull_task(rq);
}
void __init init_sched_rt_class(void)
{
unsigned int i;
for_each_possible_cpu(i) {
zalloc_cpumask_var_node(&per_cpu(local_cpu_mask, i),
GFP_KERNEL, cpu_to_node(i));
}
}
/*
* When switching a task to RT, we may overload the runqueue
* with RT tasks. In this case we try to push them off to
* other runqueues.
*/
static void switched_to_rt(struct rq *rq, struct task_struct *p)
{
/*
* If we are running, update the avg_rt tracking, as the running time
* will now on be accounted into the latter.
*/
if (task_current(rq, p)) {
update_rt_rq_load_avg(rq_clock_pelt(rq), rq, 0);
return;
}
/*
* If we are not running we may need to preempt the current
* running task. If that current running task is also an RT task
* then see if we can move to another run queue.
*/
if (task_on_rq_queued(p)) {
if (p->nr_cpus_allowed > 1 && rq->rt.overloaded)
rt_queue_push_tasks(rq);
if (p->prio < rq->donor->prio && cpu_online(cpu_of(rq)))
resched_curr(rq);
}
}
/*
* Priority of the task has changed. This may cause
* us to initiate a push or pull.
*/
static void
prio_changed_rt(struct rq *rq, struct task_struct *p, int oldprio)
{
if (!task_on_rq_queued(p))
return;
if (task_current_donor(rq, p)) {
/*
* If our priority decreases while running, we
* may need to pull tasks to this runqueue.
*/
if (oldprio < p->prio)
rt_queue_pull_task(rq);
/*
* If there's a higher priority task waiting to run
* then reschedule.
*/
if (p->prio > rq->rt.highest_prio.curr)
resched_curr(rq);
} else {
/*
* This task is not running, but if it is
* greater than the current running task
* then reschedule.
*/
if (p->prio < rq->donor->prio)
resched_curr(rq);
}
}
#ifdef CONFIG_POSIX_TIMERS
static void watchdog(struct rq *rq, struct task_struct *p)
{
unsigned long soft, hard;
/* max may change after cur was read, this will be fixed next tick */
soft = task_rlimit(p, RLIMIT_RTTIME);
hard = task_rlimit_max(p, RLIMIT_RTTIME);
if (soft != RLIM_INFINITY) {
unsigned long next;
if (p->rt.watchdog_stamp != jiffies) {
p->rt.timeout++;
p->rt.watchdog_stamp = jiffies;
}
next = DIV_ROUND_UP(min(soft, hard), USEC_PER_SEC/HZ);
if (p->rt.timeout > next) {
posix_cputimers_rt_watchdog(&p->posix_cputimers,
p->se.sum_exec_runtime);
}
}
}
#else /* !CONFIG_POSIX_TIMERS: */
static inline void watchdog(struct rq *rq, struct task_struct *p) { }
#endif /* !CONFIG_POSIX_TIMERS */
/*
* scheduler tick hitting a task of our scheduling class.
*
* NOTE: This function can be called remotely by the tick offload that
* goes along full dynticks. Therefore no local assumption can be made
* and everything must be accessed through the @rq and @curr passed in
* parameters.
*/
static void task_tick_rt(struct rq *rq, struct task_struct *p, int queued)
{
struct sched_rt_entity *rt_se = &p->rt;
update_curr_rt(rq);
update_rt_rq_load_avg(rq_clock_pelt(rq), rq, 1);
watchdog(rq, p);
/*
* RR tasks need a special form of time-slice management.
* FIFO tasks have no timeslices.
*/
if (p->policy != SCHED_RR)
return;
if (--p->rt.time_slice)
return;
p->rt.time_slice = sched_rr_timeslice;
/*
* Requeue to the end of queue if we (and all of our ancestors) are not
* the only element on the queue
*/
for_each_sched_rt_entity(rt_se) {
if (rt_se->run_list.prev != rt_se->run_list.next) {
requeue_task_rt(rq, p, 0);
resched_curr(rq);
return;
}
}
}
static unsigned int get_rr_interval_rt(struct rq *rq, struct task_struct *task)
{
/*
* Time slice is 0 for SCHED_FIFO tasks
*/
if (task->policy == SCHED_RR)
return sched_rr_timeslice;
else
return 0;
}
#ifdef CONFIG_SCHED_CORE
static int task_is_throttled_rt(struct task_struct *p, int cpu)
{
struct rt_rq *rt_rq;
#ifdef CONFIG_RT_GROUP_SCHED // XXX maybe add task_rt_rq(), see also sched_rt_period_rt_rq
rt_rq = task_group(p)->rt_rq[cpu];
WARN_ON(!rt_group_sched_enabled() && rt_rq->tg != &root_task_group);
#else
rt_rq = &cpu_rq(cpu)->rt;
#endif
return rt_rq_throttled(rt_rq);
}
#endif /* CONFIG_SCHED_CORE */
DEFINE_SCHED_CLASS(rt) = {
.enqueue_task = enqueue_task_rt,
.dequeue_task = dequeue_task_rt,
.yield_task = yield_task_rt,
.wakeup_preempt = wakeup_preempt_rt,
.pick_task = pick_task_rt,
.put_prev_task = put_prev_task_rt,
.set_next_task = set_next_task_rt,
.balance = balance_rt,
.select_task_rq = select_task_rq_rt,
.set_cpus_allowed = set_cpus_allowed_common,
.rq_online = rq_online_rt,
.rq_offline = rq_offline_rt,
.task_woken = task_woken_rt,
.switched_from = switched_from_rt,
.find_lock_rq = find_lock_lowest_rq,
.task_tick = task_tick_rt,
.get_rr_interval = get_rr_interval_rt,
.prio_changed = prio_changed_rt,
.switched_to = switched_to_rt,
.update_curr = update_curr_rt,
#ifdef CONFIG_SCHED_CORE
.task_is_throttled = task_is_throttled_rt,
#endif
#ifdef CONFIG_UCLAMP_TASK
.uclamp_enabled = 1,
#endif
};
#ifdef CONFIG_RT_GROUP_SCHED
/*
* Ensure that the real time constraints are schedulable.
*/
static DEFINE_MUTEX(rt_constraints_mutex);
static inline int tg_has_rt_tasks(struct task_group *tg)
{
struct task_struct *task;
struct css_task_iter it;
int ret = 0;
/*
* Autogroups do not have RT tasks; see autogroup_create().
*/
if (task_group_is_autogroup(tg))
return 0;
css_task_iter_start(&tg->css, 0, &it);
while (!ret && (task = css_task_iter_next(&it)))
ret |= rt_task(task);
css_task_iter_end(&it);
return ret;
}
struct rt_schedulable_data {
struct task_group *tg;
u64 rt_period;
u64 rt_runtime;
};
static int tg_rt_schedulable(struct task_group *tg, void *data)
{
struct rt_schedulable_data *d = data;
struct task_group *child;
unsigned long total, sum = 0;
u64 period, runtime;
period = ktime_to_ns(tg->rt_bandwidth.rt_period);
runtime = tg->rt_bandwidth.rt_runtime;
if (tg == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
/*
* Cannot have more runtime than the period.
*/
if (runtime > period && runtime != RUNTIME_INF)
return -EINVAL;
/*
* Ensure we don't starve existing RT tasks if runtime turns zero.
*/
if (rt_bandwidth_enabled() && !runtime &&
tg->rt_bandwidth.rt_runtime && tg_has_rt_tasks(tg))
return -EBUSY;
if (WARN_ON(!rt_group_sched_enabled() && tg != &root_task_group))
return -EBUSY;
total = to_ratio(period, runtime);
/*
* Nobody can have more than the global setting allows.
*/
if (total > to_ratio(global_rt_period(), global_rt_runtime()))
return -EINVAL;
/*
* The sum of our children's runtime should not exceed our own.
*/
list_for_each_entry_rcu(child, &tg->children, siblings) {
period = ktime_to_ns(child->rt_bandwidth.rt_period);
runtime = child->rt_bandwidth.rt_runtime;
if (child == d->tg) {
period = d->rt_period;
runtime = d->rt_runtime;
}
sum += to_ratio(period, runtime);
}
if (sum > total)
return -EINVAL;
return 0;
}
static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
{
int ret;
struct rt_schedulable_data data = {
.tg = tg,
.rt_period = period,
.rt_runtime = runtime,
};
rcu_read_lock();
ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
rcu_read_unlock();
return ret;
}
static int tg_set_rt_bandwidth(struct task_group *tg,
u64 rt_period, u64 rt_runtime)
{
int i, err = 0;
/*
* Disallowing the root group RT runtime is BAD, it would disallow the
* kernel creating (and or operating) RT threads.
*/
if (tg == &root_task_group && rt_runtime == 0)
return -EINVAL;
/* No period doesn't make any sense. */
if (rt_period == 0)
return -EINVAL;
/*
* Bound quota to defend quota against overflow during bandwidth shift.
*/
if (rt_runtime != RUNTIME_INF && rt_runtime > max_rt_runtime)
return -EINVAL;
mutex_lock(&rt_constraints_mutex);
err = __rt_schedulable(tg, rt_period, rt_runtime);
if (err)
goto unlock;
raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
tg->rt_bandwidth.rt_runtime = rt_runtime;
for_each_possible_cpu(i) {
struct rt_rq *rt_rq = tg->rt_rq[i];
raw_spin_lock(&rt_rq->rt_runtime_lock);
rt_rq->rt_runtime = rt_runtime;
raw_spin_unlock(&rt_rq->rt_runtime_lock);
}
raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
unlock:
mutex_unlock(&rt_constraints_mutex);
return err;
}
int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
{
u64 rt_runtime, rt_period;
rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
if (rt_runtime_us < 0)
rt_runtime = RUNTIME_INF;
else if ((u64)rt_runtime_us > U64_MAX / NSEC_PER_USEC)
return -EINVAL;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
long sched_group_rt_runtime(struct task_group *tg)
{
u64 rt_runtime_us;
if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
return -1;
rt_runtime_us = tg->rt_bandwidth.rt_runtime;
do_div(rt_runtime_us, NSEC_PER_USEC);
return rt_runtime_us;
}
int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
{
u64 rt_runtime, rt_period;
if (rt_period_us > U64_MAX / NSEC_PER_USEC)
return -EINVAL;
rt_period = rt_period_us * NSEC_PER_USEC;
rt_runtime = tg->rt_bandwidth.rt_runtime;
return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
}
long sched_group_rt_period(struct task_group *tg)
{
u64 rt_period_us;
rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
do_div(rt_period_us, NSEC_PER_USEC);
return rt_period_us;
}
#ifdef CONFIG_SYSCTL
static int sched_rt_global_constraints(void)
{
int ret = 0;
mutex_lock(&rt_constraints_mutex);
ret = __rt_schedulable(NULL, 0, 0);
mutex_unlock(&rt_constraints_mutex);
return ret;
}
#endif /* CONFIG_SYSCTL */
int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
{
/* Don't accept real-time tasks when there is no way for them to run */
if (rt_group_sched_enabled() && rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
return 0;
return 1;
}
#else /* !CONFIG_RT_GROUP_SCHED: */
#ifdef CONFIG_SYSCTL
static int sched_rt_global_constraints(void)
{
return 0;
}
#endif /* CONFIG_SYSCTL */
#endif /* !CONFIG_RT_GROUP_SCHED */
#ifdef CONFIG_SYSCTL
static int sched_rt_global_validate(void)
{
if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
((sysctl_sched_rt_runtime > sysctl_sched_rt_period) ||
((u64)sysctl_sched_rt_runtime *
NSEC_PER_USEC > max_rt_runtime)))
return -EINVAL;
return 0;
}
static void sched_rt_do_global(void)
{
}
static int sched_rt_handler(const struct ctl_table *table, int write, void *buffer,
size_t *lenp, loff_t *ppos)
{
int old_period, old_runtime;
static DEFINE_MUTEX(mutex);
int ret;
mutex_lock(&mutex);
sched_domains_mutex_lock();
old_period = sysctl_sched_rt_period;
old_runtime = sysctl_sched_rt_runtime;
ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
if (!ret && write) {
ret = sched_rt_global_validate();
if (ret)
goto undo;
ret = sched_dl_global_validate();
if (ret)
goto undo;
ret = sched_rt_global_constraints();
if (ret)
goto undo;
sched_rt_do_global();
sched_dl_do_global();
}
if (0) {
undo:
sysctl_sched_rt_period = old_period;
sysctl_sched_rt_runtime = old_runtime;
}
sched_domains_mutex_unlock();
mutex_unlock(&mutex);
/*
* After changing maximum available bandwidth for DEADLINE, we need to
* recompute per root domain and per cpus variables accordingly.
*/
rebuild_sched_domains();
return ret;
}
static int sched_rr_handler(const struct ctl_table *table, int write, void *buffer,
size_t *lenp, loff_t *ppos)
{
int ret;
static DEFINE_MUTEX(mutex);
mutex_lock(&mutex);
ret = proc_dointvec(table, write, buffer, lenp, ppos);
/*
* Make sure that internally we keep jiffies.
* Also, writing zero resets the time-slice to default:
*/
if (!ret && write) {
sched_rr_timeslice =
sysctl_sched_rr_timeslice <= 0 ? RR_TIMESLICE :
msecs_to_jiffies(sysctl_sched_rr_timeslice);
if (sysctl_sched_rr_timeslice <= 0)
sysctl_sched_rr_timeslice = jiffies_to_msecs(RR_TIMESLICE);
}
mutex_unlock(&mutex);
return ret;
}
#endif /* CONFIG_SYSCTL */
void print_rt_stats(struct seq_file *m, int cpu)
{
rt_rq_iter_t iter;
struct rt_rq *rt_rq;
rcu_read_lock();
for_each_rt_rq(rt_rq, iter, cpu_rq(cpu))
print_rt_rq(m, cpu, rt_rq);
rcu_read_unlock();
}
// Create alphabet array: ['a', 'b', 'c', ..., 'z'].
const englishAlphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
/**
* Generates a cipher map out of the alphabet.
* Example with a shift 3: {'a': 'd', 'b': 'e', 'c': 'f', ...}
*
* @param {string[]} alphabet - i.e. ['a', 'b', 'c', ... , 'z']
* @param {number} shift - i.e. 3
* @return {Object} - i.e. {'a': 'd', 'b': 'e', 'c': 'f', ..., 'z': 'c'}
*/
const getCipherMap = (alphabet, shift) => {
return alphabet
.reduce((charsMap, currentChar, charIndex) => {
const charsMapClone = { ...charsMap };
// Making the shift to be cyclic (i.e. with a shift of 1 - 'z' would be mapped to 'a').
let encryptedCharIndex = (charIndex + shift) % alphabet.length;
// Support negative shifts for creating a map for decryption
// (i.e. with shift -1 - 'a' would be mapped to 'z').
if (encryptedCharIndex < 0) {
encryptedCharIndex += alphabet.length;
}
charsMapClone[currentChar] = alphabet[encryptedCharIndex];
return charsMapClone;
}, {});
};
/**
* @param {string} str
* @param {number} shift
* @param {string[]} alphabet
* @return {string}
*/
export const caesarCipherEncrypt = (str, shift, alphabet = englishAlphabet) => {
// Create a cipher map:
const cipherMap = getCipherMap(alphabet, shift);
return str
.toLowerCase()
.split('')
.map((char) => cipherMap[char] || char)
.join('');
};
/**
* @param {string} str
* @param {number} shift
* @param {string[]} alphabet
* @return {string}
*/
export const caesarCipherDecrypt = (str, shift, alphabet = englishAlphabet) => {
// Create a cipher map:
const cipherMap = getCipherMap(alphabet, -shift);
return str
.toLowerCase()
.split('')
.map((char) => cipherMap[char] || char)
.join('');
};
/**
* @typedef {string[]} Rail
* @typedef {Rail[]} Fence
* @typedef {number} Direction
*/
/**
* @constant DIRECTIONS
* @type {object}
* @property {Direction} UP
* @property {Direction} DOWN
*/
const DIRECTIONS = { UP: -1, DOWN: 1 };
/**
* Builds a fence with a specific number of rows.
*
* @param {number} rowsNum
* @returns {Fence}
*/
const buildFence = (rowsNum) => Array(rowsNum)
.fill(null)
.map(() => []);
/**
* Get next direction to move (based on the current one) while traversing the fence.
*
* @param {object} params
* @param {number} params.railCount - Number of rows in the fence
* @param {number} params.currentRail - Current row that we're visiting
* @param {Direction} params.direction - Current direction
* @returns {Direction} - The next direction to take
*/
const getNextDirection = ({ railCount, currentRail, direction }) => {
switch (currentRail) {
case 0:
// Go down if we're on top of the fence.
return DIRECTIONS.DOWN;
case railCount - 1:
// Go up if we're at the bottom of the fence.
return DIRECTIONS.UP;
default:
// Continue with the same direction if we're in the middle of the fence.
return direction;
}
};
/**
* @param {number} targetRailIndex
* @param {string} letter
* @returns {Function}
*/
const addCharToRail = (targetRailIndex, letter) => {
/**
* Given a rail, adds a char to it if it matches a targetIndex.
*
* @param {Rail} rail
* @param {number} currentRail
* @returns {Rail}
*/
function onEachRail(rail, currentRail) {
return currentRail === targetRailIndex
? [...rail, letter]
: rail;
}
return onEachRail;
};
/**
* Hangs the characters on the fence.
*
* @param {object} params
* @param {Fence} params.fence
* @param {number} params.currentRail
* @param {Direction} params.direction
* @param {string[]} params.chars
* @returns {Fence}
*/
const fillEncodeFence = ({
fence,
currentRail,
direction,
chars,
}) => {
if (chars.length === 0) {
// All chars have been placed on a fence.
return fence;
}
const railCount = fence.length;
// Getting the next character to place on a fence.
const [letter, ...nextChars] = chars;
const nextDirection = getNextDirection({
railCount,
currentRail,
direction,
});
return fillEncodeFence({
fence: fence.map(addCharToRail(currentRail, letter)),
currentRail: currentRail + nextDirection,
direction: nextDirection,
chars: nextChars,
});
};
/**
* @param {object} params
* @param {number} params.strLen
* @param {string[]} params.chars
* @param {Fence} params.fence
* @param {number} params.targetRail
* @param {Direction} params.direction
* @param {number[]} params.coords
* @returns {Fence}
*/
const fillDecodeFence = (params) => {
const {
strLen, chars, fence, targetRail, direction, coords,
} = params;
const railCount = fence.length;
if (chars.length === 0) {
return fence;
}
const [currentRail, currentColumn] = coords;
const shouldGoNextRail = currentColumn === strLen - 1;
const nextDirection = shouldGoNextRail
? DIRECTIONS.DOWN
: getNextDirection(
{ railCount, currentRail, direction },
);
const nextRail = shouldGoNextRail ? targetRail + 1 : targetRail;
const nextCoords = [
shouldGoNextRail ? 0 : currentRail + nextDirection,
shouldGoNextRail ? 0 : currentColumn + 1,
];
const shouldAddChar = currentRail === targetRail;
const [currentChar, ...remainderChars] = chars;
const nextString = shouldAddChar ? remainderChars : chars;
const nextFence = shouldAddChar ? fence.map(addCharToRail(currentRail, currentChar)) : fence;
return fillDecodeFence({
strLen,
chars: nextString,
fence: nextFence,
targetRail: nextRail,
direction: nextDirection,
coords: nextCoords,
});
};
/**
* @param {object} params
* @param {number} params.strLen
* @param {Fence} params.fence
* @param {number} params.currentRail
* @param {Direction} params.direction
* @param {number[]} params.code
* @returns {string}
*/
const decodeFence = (params) => {
const {
strLen,
fence,
currentRail,
direction,
code,
} = params;
if (code.length === strLen) {
return code.join('');
}
const railCount = fence.length;
const [currentChar, ...nextRail] = fence[currentRail];
const nextDirection = getNextDirection(
{ railCount, currentRail, direction },
);
return decodeFence({
railCount,
strLen,
currentRail: currentRail + nextDirection,
direction: nextDirection,
code: [...code, currentChar],
fence: fence.map((rail, idx) => (idx === currentRail ? nextRail : rail)),
});
};
/**
* Encodes the message using Rail Fence Cipher.
*
* @param {string} string - The string to be encoded
* @param {number} railCount - The number of rails in a fence
* @returns {string} - Encoded string
*/
export const encodeRailFenceCipher = (string, railCount) => {
const fence = buildFence(railCount);
const filledFence = fillEncodeFence({
fence,
currentRail: 0,
direction: DIRECTIONS.DOWN,
chars: string.split(''),
});
return filledFence.flat().join('');
};
/**
* Decodes the message using Rail Fence Cipher.
*
* @param {string} string - Encoded string
* @param {number} railCount - The number of rows in a fence
* @returns {string} - Decoded string.
*/
export const decodeRailFenceCipher = (string, railCount) => {
const strLen = string.length;
const emptyFence = buildFence(railCount);
const filledFence = fillDecodeFence({
strLen,
chars: string.split(''),
fence: emptyFence,
targetRail: 0,
direction: DIRECTIONS.DOWN,
coords: [0, 0],
});
return decodeFence({
strLen,
fence: filledFence,
currentRail: 0,
direction: DIRECTIONS.DOWN,
code: [],
});
};
import { getPixel, setPixel } from '../utils/imageData';
/**
* The seam is a sequence of pixels (coordinates).
* @typedef {PixelCoordinate[]} Seam
*/
/**
* Energy map is a 2D array that has the same width and height
* as the image the map is being calculated for.
* @typedef {number[][]} EnergyMap
*/
/**
* The metadata for the pixels in the seam.
* @typedef {Object} SeamPixelMeta
* @property {number} energy - the energy of the pixel.
* @property {PixelCoordinate} coordinate - the coordinate of the pixel.
* @property {?PixelCoordinate} previous - the previous pixel in a seam.
*/
/**
* Type that describes the image size (width and height)
* @typedef {Object} ImageSize
* @property {number} w - image width.
* @property {number} h - image height.
*/
/**
* @typedef {Object} ResizeImageWidthArgs
* @property {ImageData} img - image data we want to resize.
* @property {number} toWidth - final image width we want the image to shrink to.
*/
/**
* @typedef {Object} ResizeImageWidthResult
* @property {ImageData} img - resized image data.
* @property {ImageSize} size - resized image size.
*/
/**
* Helper function that creates a matrix (2D array) of specific
* size (w x h) and fills it with specified value.
* @param {number} w
* @param {number} h
* @param {?(number | SeamPixelMeta)} filler
* @returns {?(number | SeamPixelMeta)[][]}
*/
const matrix = (w, h, filler) => {
return new Array(h)
.fill(null)
.map(() => {
return new Array(w).fill(filler);
});
};
/**
* Calculates the energy of a pixel.
* @param {?PixelColor} left
* @param {PixelColor} middle
* @param {?PixelColor} right
* @returns {number}
*/
const getPixelEnergy = (left, middle, right) => {
// Middle pixel is the pixel we're calculating the energy for.
const [mR, mG, mB] = middle;
// Energy from the left pixel (if it exists).
let lEnergy = 0;
if (left) {
const [lR, lG, lB] = left;
lEnergy = (lR - mR) ** 2 + (lG - mG) ** 2 + (lB - mB) ** 2;
}
// Energy from the right pixel (if it exists).
let rEnergy = 0;
if (right) {
const [rR, rG, rB] = right;
rEnergy = (rR - mR) ** 2 + (rG - mG) ** 2 + (rB - mB) ** 2;
}
// Resulting pixel energy.
return Math.sqrt(lEnergy + rEnergy);
};
/**
* Calculates the energy of each pixel of the image.
* @param {ImageData} img
* @param {ImageSize} size
* @returns {EnergyMap}
*/
const calculateEnergyMap = (img, { w, h }) => {
// Create an empty energy map where each pixel has infinitely high energy.
// We will update the energy of each pixel.
const energyMap = matrix(w, h, Infinity);
for (let y = 0; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Left pixel might not exist if we're on the very left edge of the image.
const left = (x - 1) >= 0 ? getPixel(img, { x: x - 1, y }) : null;
// The color of the middle pixel that we're calculating the energy for.
const middle = getPixel(img, { x, y });
// Right pixel might not exist if we're on the very right edge of the image.
const right = (x + 1) < w ? getPixel(img, { x: x + 1, y }) : null;
energyMap[y][x] = getPixelEnergy(left, middle, right);
}
}
return energyMap;
};
/**
* Finds the seam (the sequence of pixels from top to bottom) that has the
* lowest resulting energy using the Dynamic Programming approach.
* @param {EnergyMap} energyMap
* @param {ImageSize} size
* @returns {Seam}
*/
const findLowEnergySeam = (energyMap, { w, h }) => {
// The 2D array of the size of w and h, where each pixel contains the
// seam metadata (pixel energy, pixel coordinate and previous pixel from
// the lowest energy seam at this point).
const seamPixelsMap = matrix(w, h, null);
// Populate the first row of the map by just copying the energies
// from the energy map.
for (let x = 0; x < w; x += 1) {
const y = 0;
seamPixelsMap[y][x] = {
energy: energyMap[y][x],
coordinate: { x, y },
previous: null,
};
}
// Populate the rest of the rows.
for (let y = 1; y < h; y += 1) {
for (let x = 0; x < w; x += 1) {
// Find the top adjacent cell with minimum energy.
// This cell would be the tail of a seam with lowest energy at this point.
// It doesn't mean that this seam (path) has lowest energy globally.
// Instead, it means that we found a path with the lowest energy that may lead
// us to the current pixel with the coordinates x and y.
let minPrevEnergy = Infinity;
let minPrevX = x;
for (let i = (x - 1); i <= (x + 1); i += 1) {
if (i >= 0 && i < w && seamPixelsMap[y - 1][i].energy < minPrevEnergy) {
minPrevEnergy = seamPixelsMap[y - 1][i].energy;
minPrevX = i;
}
}
// Update the current cell.
seamPixelsMap[y][x] = {
energy: minPrevEnergy + energyMap[y][x],
coordinate: { x, y },
previous: { x: minPrevX, y: y - 1 },
};
}
}
// Find where the minimum energy seam ends.
// We need to find the tail of the lowest energy seam to start
// traversing it from its tail to its head (from the bottom to the top).
let lastMinCoordinate = null;
let minSeamEnergy = Infinity;
for (let x = 0; x < w; x += 1) {
const y = h - 1;
if (seamPixelsMap[y][x].energy < minSeamEnergy) {
minSeamEnergy = seamPixelsMap[y][x].energy;
lastMinCoordinate = { x, y };
}
}
// Find the lowest energy energy seam.
// Once we know where the tail is we may traverse and assemble the lowest
// energy seam based on the "previous" value of the seam pixel metadata.
const seam = [];
const { x: lastMinX, y: lastMinY } = lastMinCoordinate;
// Adding new pixel to the seam path one by one until we reach the top.
let currentSeam = seamPixelsMap[lastMinY][lastMinX];
while (currentSeam) {
seam.push(currentSeam.coordinate);
const prevMinCoordinates = currentSeam.previous;
if (!prevMinCoordinates) {
currentSeam = null;
} else {
const { x: prevMinX, y: prevMinY } = prevMinCoordinates;
currentSeam = seamPixelsMap[prevMinY][prevMinX];
}
}
return seam;
};
/**
* Deletes the seam from the image data.
* We delete the pixel in each row and then shift the rest of the row pixels to the left.
* @param {ImageData} img
* @param {Seam} seam
* @param {ImageSize} size
*/
const deleteSeam = (img, seam, { w }) => {
seam.forEach(({ x: seamX, y: seamY }) => {
for (let x = seamX; x < (w - 1); x += 1) {
const nextPixel = getPixel(img, { x: x + 1, y: seamY });
setPixel(img, { x, y: seamY }, nextPixel);
}
});
};
/**
* Performs the content-aware image width resizing using the seam carving method.
* @param {ResizeImageWidthArgs} args
* @returns {ResizeImageWidthResult}
*/
const resizeImageWidth = ({ img, toWidth }) => {
/**
* For performance reasons we want to avoid changing the img data array size.
* Instead we'll just keep the record of the resized image width and height separately.
* @type {ImageSize}
*/
const size = { w: img.width, h: img.height };
// Calculating the number of pixels to remove.
const pxToRemove = img.width - toWidth;
let energyMap = null;
let seam = null;
// Removing the lowest energy seams one by one.
for (let i = 0; i < pxToRemove; i += 1) {
// 1. Calculate the energy map for the current version of the image.
energyMap = calculateEnergyMap(img, size);
// 2. Find the seam with the lowest energy based on the energy map.
seam = findLowEnergySeam(energyMap, size);
// 3. Delete the seam with the lowest energy seam from the image.
deleteSeam(img, seam, size);
// Reduce the image width, and continue iterations.
size.w -= 1;
}
// Returning the resized image and its final size.
// The img is actually a reference to the ImageData, so technically
// the caller of the function already has this pointer. But let's
// still return it for better code readability.
return { img, size };
};
export default resizeImageWidth;
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class Person:
def __init__(self, name, age, address, phone):
self.name = name
self.age = age
self.address = address
self.phone = phone
def greet(self):
print('Hello I am', self.name)
def is_adult(self):
if self.age > 18:
return True
else:
return False
def contact_details(self):
print(self.address, self.phone)
class Employee(Person):
def __init__(self, name, age, address, phone, salary, office_address, office_phone):
super().__init__(name, age, address, phone)
self.salary = salary
self.office_address = office_address
self.office_phone = office_phone
def calculate_tax(self):
if self.salary < 5000:
return 0
else:
return self.salary * 0.05
def contact_details(self):
super().contact_details()
print(self.office_address, self.office_phone)
emp = Employee('Jack', 30, 'D4, XYZ Street', '994477291', 8000, 'ABC Street', '384923993')
emp.contact_details()
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class Employee:
def __init__(self,first_name, last_name, birth_year,salary):
self.first_name = first_name
self.last_name = last_name
self.birth_year = birth_year
self.salary = salary
def show(self):
print(f'I am {self.first_name} {self.last_name} born in {self.birth_year}')
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(self.name,self.age)
@property
def age(self):
return self._age
@age.setter
def age(self, new_age):
if 20< new_age<80:
self._age = new_age
else:
raise ValueError('Age must be between 20 and 80')
p = Person('Peter', 30)
print(p.age)
p.age = 200
print(p.age)
p1 = Person('Dev',200)
p.age = p.age +1
p.age += 1
print(p.age)
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class MyClass():
a = 5
def __init__(self, x):
self.x = x
def method1(self):
print(self.x)
@classmethod
def method2(cls):
print(cls.a)
@staticmethod
def method3(m,n):
retrun m+n
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of Python course available on CourseGalaxy.com
class Person:
def greet(self):
print('I am a Person')
class Teacher(Person):
def greet(self):
print('I am a Teacher')
class Student(Person):
def greet(self):
print('I am a Student')
class TeachingAssistant(Student, Teacher):
def greet(self):
print('I am a Teaching Assistant')
x = TeachingAssistant()
x.greet()
print(TeachingAssistant.__mro__)
print(TeachingAssistant.mro())
print(x.__class__.__mro__)
// ===== BEGIN python =====
#!/usr/bin/python
# -*- coding: utf-8 -*-
# #*** <License> ************************************************************#
# This module is part of the repository CNDB.
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/bsd_3c.html>.
# #*** </License> ***********************************************************#
from _TFL.pyk import pyk
from rsclib.HTML_Parse import tag, Page_Tree
from rsclib.autosuper import autosuper
from spider.common import Interface, Inet4, Inet6, unroutable
from spider.common import WLAN_Config
from spider.luci import Version_Mixin
class Status (Page_Tree, Version_Mixin) :
url = 'cgi-bin/luci/freifunk/status/status'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
wl_names = dict \
( ssid = 'ssid'
, _bsiid = 'bssid'
, channel = 'channel'
, mode = 'mode'
)
def parse (self) :
root = self.tree.getroot ()
self.wlans = []
self.routes = {}
for div in root.findall (".//%s" % tag ("div")) :
id = div.get ('id')
if id == 'cbi-wireless' :
wlan_div = div
elif id == 'cbi-routes' :
route_div = div
self.try_get_version (div)
for d in self.tbl_iter (wlan_div) :
for k, newkey in pyk.iteritems (self.wl_names) :
if k in d :
d [newkey] = d [k]
wl = WLAN_Config (** d)
self.wlans.append (wl)
for d in self.tbl_iter (route_div) :
iface = d.get ('iface')
gw = d.get ('gateway')
if iface and gw :
self.routes [iface] = gw
self.set_version (root)
# end def parse
def tbl_iter (self, div) :
tbl = div.find (".//%s" % tag ("table"))
assert tbl.get ('class') == 'cbi-section-table'
d = {}
for tr in tbl :
if 'cbi-section-table-row' not in tr.get ('class').split () :
continue
for input in tr.findall (".//%s" % tag ('input')) :
name = input.get ('id').split ('.') [-1]
val = input.get ('value')
d [name] = val
if not d :
continue
yield d
# end def tbl_iter
# end class Status
class Table_Iter (Page_Tree) :
def table_iter (self) :
root = self.tree.getroot ()
for div in root.findall (".//%s" % tag ("div")) :
if div.get ('id') == 'maincontent' :
break
tbl = div.find (".//%s" % tag ("table"))
if tbl is None :
return
for tr in tbl :
if tr [0].tag == tag ('th') :
continue
yield (self.tree.get_text (x) for x in tr)
# end def table_iter
# end class Table_Iter
class OLSR_Connections (Table_Iter) :
url = 'cgi-bin/luci/freifunk/olsr/'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
def parse (self) :
self.neighbors = {}
for l in self.table_iter () :
neighbor, ip, lq, nlq, etx = l
lq, nlq, etx = (float (x) for x in (lq, nlq, etx))
self.neighbors [neighbor] = [ip, lq, nlq, etx]
# end def parse
# end class OLSR_Connections
class OLSR_Routes (Table_Iter) :
url = 'cgi-bin/luci/freifunk/olsr/routes'
retries = 2
timeout = 10
html_charset = 'utf-8' # force utf-8 encoding
def parse (self) :
self.iface_by_gw = {}
for l in self.table_iter () :
announced, gw, iface, metric, etx = l
if gw in self.iface_by_gw :
assert iface == self.iface_by_gw [gw]
else :
self.iface_by_gw [gw] = iface
# end def parse
# end class OLSR_Routes
class OpenWRT (autosuper) :
def __init__ (self, site, request) :
self.site = site
self.request = request
if 'interfaces' in self.request or 'ips' in self.request :
st = Status (site = site)
conn = OLSR_Connections (site = site)
route = OLSR_Routes (site = site)
self.version = st.version
assert len (st.wlans) <= 1
interfaces = {}
ips = {}
count = 0
for gw, ifname in pyk.iteritems (route.iface_by_gw) :
ip, lq, nlq, etx = conn.neighbors [gw]
i4 = Inet4 (ip, None, None, iface = ifname)
ips [i4] = 1
is_wlan = True
if lq == nlq == etx == 1.0 :
is_wlan = False
if ifname in interfaces :
iface = interfaces [ifname]
if not iface.is_wlan and is_wlan :
iface.is_wlan = True
iface.wlan_info = st.wlans [0]
else :
iface = Interface (count, ifname, None)
iface.is_wlan = is_wlan
if is_wlan :
iface.wlan_info = st.wlans [0]
count += 1
interfaces [ifname] = iface
if i4 not in iface.inet4 :
iface.append_inet4 (i4)
wl_if = None
for iface in pyk.itervalues (interfaces) :
if iface.is_wlan :
if wl_if :
m = "Duplicate wlan: %s/%s" % (iface.name, wl_if.name)
raise ValueError (m)
wl_if = iface
# check own ip
n = 'unknown'
i4 = Inet4 (self.request ['ip'], None, None, iface = n)
if i4 not in ips :
assert n not in interfaces
iface = interfaces [n] = Interface (count, n, None)
iface.append_inet4 (i4)
iface.is_wlan = False
if not wl_if and st.wlans :
iface.is_wlan = True
iface.wlan_info = st.wlans [0]
ips [i4] = True
self.request ['ips'] = ips
self.request ['interfaces'] = interfaces
self.request ['version'] = st.version
# end def __init__
# end class OpenWRT
// ===== END =====
// ===== BEGIN python =====
# UCF Senior Design 2017-18
# Group 38
from PIL import Image
import cv2
import imagehash
import math
import numpy as np
DIFF_THRES = 20
LIMIT = 2
RESIZE = 1000
def calc_hash(img):
"""
Calculate the wavelet hash of the image
img: (ndarray) image file
"""
# resize image if height > 1000
img = resize(img)
return imagehash.whash(Image.fromarray(img))
def compare(hash1, hash2):
"""
Calculate the difference between two images
hash1: (array) first wavelet hash
hash2: (array) second wavelet hash
"""
return hash1 - hash2
def limit(img, std_hash, count):
"""
Determine whether image should be removed from image dictionary in main.py
img: (ndarray) image file
std_hash: (array) wavelet hash of comparison standard
count: (int) global count of images similar to comparison standard
"""
# calculate hash for given image
cmp_hash = calc_hash(img)
# compare to standard
diff = compare(std_hash, cmp_hash)
# image is similar to standard
if diff <= DIFF_THRES:
# if there are 3 similar images already, remove image
if count >= LIMIT:
return 'remove'
# non-similar image found
else:
# update comparison standard
return 'update_std'
# else continue reading images with same standard
return 'continue'
def resize(img):
"""
Resize an image
img: (ndarray) RGB color image
"""
# get dimensions of image
width = np.shape(img)[1]
height = np.shape(img)[0]
# if height of image is greater than 1000, resize it to 1000
if width > RESIZE:
# keep resize proportional
scale = RESIZE / width
resized_img = cv2.resize(
img, (RESIZE, math.floor(height / scale)), cv2.INTER_AREA)
# return resized image
return resized_img
# if height of image is less than 1000, return image unresized
return img
def set_standard(images, filename):
"""
Set new comparison standard and update information
images: (dictionary) dictionary containing all the image data
filename: (String) name of the image file
"""
return filename, calc_hash(images[filename]), 0
// ===== END =====
// ===== BEGIN python =====
# Copyright 2018 Google LLC
#
# 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.
from .cli.cli import main
# TODO(hongyes): add more commands:
# kfp compile (migrate from dsl-compile)
# kfp experiment (manage experiments)
if __name__ == '__main__':
main()
// ===== END =====
// ===== BEGIN python =====
import time
from PyQt5 import QtGui, QtCore
from ui.room_item import Ui_Form
from PyQt5.QtWidgets import QWidget
class Room_Item(QWidget,Ui_Form):
def __init__(self,parent=None,room_data=None):
super(Room_Item,self).__init__(parent)
self.setupUi(self)
self.data = room_data
self.setRoomInfo()
def setRoomInfo(self):
self.room_name.setText('{}({})'.format(self.data['naturalName'], self.data['roomName']))
self.description.setText("<a style='color:#BCBCBC'>{}</a>".format(self.data['description']))
timeStamp = int(self.data['creationDate']) / 1000
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
self.create_time.setText("<a style='color:#BCBCBC'>{}</a>".format(otherStyleTime))
members = len(self.data['owners']) + len(self.data['admins']) + len(self.data['members'])
memberCounter = "<a style='color:#BCBCBC'>{}/{}</a>".format(members, ('∞' if self.data['maxUsers']==0 else self.data['maxUsers']))
self.member.setText(memberCounter)
// ===== END =====
// ===== BEGIN python =====
import asyncio
import re
import sys
import traceback
import toga
from toga import Key
from .keys import toga_to_winforms_key
from .libs import Threading, WinForms, shcore, user32, win_version
from .libs.proactor import WinformsProactorEventLoop
from .window import Window
class MainWindow(Window):
def winforms_FormClosing(self, sender, event):
if not self.interface.app._impl._is_exiting:
event.Cancel = not self.interface.app.exit()
class App:
_MAIN_WINDOW_CLASS = MainWindow
def __init__(self, interface):
self.interface = interface
self.interface._impl = self
# Winforms app exit is tightly bound to the close of the MainWindow.
# The FormClosing message on MainWindow calls app.exit(), which
# will then trigger the "on_exit" handler (which might abort the
# close). However, if app.exit() succeeds, it will request the
# Main Window to close... which calls app.exit().
# So - we have a flag that is only ever sent once a request has been
# made to exit the native app. This flag can be used to shortcut any
# window-level close handling.
self._is_exiting = False
self.loop = WinformsProactorEventLoop()
asyncio.set_event_loop(self.loop)
def create(self):
self.native = WinForms.Application
self.app_context = WinForms.ApplicationContext()
# Check the version of windows and make sure we are setting the DPI mode
# with the most up to date API
# Windows Versioning Check Sources : https://www.lifewire.com/windows-version-numbers-2625171
# and https://docs.microsoft.com/en-us/windows/release-information/
if win_version.Major >= 6: # Checks for Windows Vista or later
# Represents Windows 8.1 up to Windows 10 before Build 1703 which should use
# SetProcessDpiAwareness(True)
if ((win_version.Major == 6 and win_version.Minor == 3) or
(win_version.Major == 10 and win_version.Build < 15063)):
shcore.SetProcessDpiAwareness(True)
# Represents Windows 10 Build 1703 and beyond which should use
# SetProcessDpiAwarenessContext(-2)
elif win_version.Major == 10 and win_version.Build >= 15063:
user32.SetProcessDpiAwarenessContext(-2)
# Any other version of windows should use SetProcessDPIAware()
else:
user32.SetProcessDPIAware()
self.native.EnableVisualStyles()
self.native.SetCompatibleTextRenderingDefault(False)
self.interface.commands.add(
toga.Command(
lambda _: self.interface.about(),
'About {}'.format(self.interface.name),
group=toga.Group.HELP
),
toga.Command(None, 'Preferences', group=toga.Group.FILE),
# Quit should always be the last item, in a section on it's own
toga.Command(
lambda _: self.interface.exit(),
'Exit ' + self.interface.name,
shortcut=Key.MOD_1 + 'q',
group=toga.Group.FILE,
section=sys.maxsize
),
toga.Command(
lambda _: self.interface.visit_homepage(),
'Visit homepage',
enabled=self.interface.home_page is not None,
group=toga.Group.HELP
)
)
self._create_app_commands()
# Call user code to populate the main window
self.interface.startup()
self.create_menus()
self.interface.icon.bind(self.interface.factory)
self.interface.main_window._impl.set_app(self)
def create_menus(self):
self._menu_items = {}
self._menu_groups = {}
toga.Group.FILE.order = 0
menubar = WinForms.MenuStrip()
submenu = None
for cmd in self.interface.commands:
if cmd == toga.GROUP_BREAK:
submenu = None
elif cmd == toga.SECTION_BREAK:
submenu.DropDownItems.Add('-')
else:
submenu = self._submenu(cmd.group, menubar)
item = WinForms.ToolStripMenuItem(cmd.label)
if cmd.action:
item.Click += cmd._impl.as_handler()
item.Enabled = cmd.enabled
if cmd.shortcut is not None:
shortcut_keys = toga_to_winforms_key(cmd.shortcut)
item.ShortcutKeys = shortcut_keys
item.ShowShortcutKeys = True
cmd._impl.native.append(item)
self._menu_items[item] = cmd
submenu.DropDownItems.Add(item)
self.interface.main_window._impl.native.Controls.Add(menubar)
self.interface.main_window._impl.native.MainMenuStrip = menubar
self.interface.main_window.content.refresh()
def _submenu(self, group, menubar):
try:
return self._menu_groups[group]
except KeyError:
if group is None:
submenu = menubar
else:
parent_menu = self._submenu(group.parent, menubar)
submenu = WinForms.ToolStripMenuItem(group.label)
# Top level menus are added in a different way to submenus
if group.parent is None:
parent_menu.Items.Add(submenu)
else:
parent_menu.DropDownItems.Add(submenu)
self._menu_groups[group] = submenu
return submenu
def _create_app_commands(self):
# No extra menus
pass
def open_document(self, fileURL):
'''Add a new document to this app.'''
print("STUB: If you want to handle opening documents, implement App.open_document(fileURL)")
def winforms_thread_exception(self, sender, winforms_exc):
# The PythonException returned by Winforms doesn't give us
# easy access to the underlying Python stacktrace; so we
# reconstruct it from the string message.
# The Python message is helpfully included in square brackets,
# as the context for the first line in the .net stack trace.
# So, look for the closing bracket and the start of the Python.net
# stack trace. Then, reconstruct the line breaks internal to the
# remaining string.
print("Traceback (most recent call last):")
py_exc = winforms_exc.get_Exception()
full_stack_trace = py_exc.StackTrace
regex = re.compile(
r"^\[(?:'(.*?)', )*(?:'(.*?)')\] (?:.*?) Python\.Runtime",
re.DOTALL | re.UNICODE
)
stacktrace_relevant_lines = regex.findall(full_stack_trace)
if len(stacktrace_relevant_lines) == 0:
self.print_stack_trace(full_stack_trace)
else:
for lines in stacktrace_relevant_lines:
for line in lines:
self.print_stack_trace(line)
print(py_exc.Message)
@classmethod
def print_stack_trace(cls, stack_trace_line):
for level in stack_trace_line.split("', '"):
for line in level.split("\\n"):
if line:
print(line)
def run_app(self):
try:
self.create()
self.native.ThreadException += self.winforms_thread_exception
self.loop.run_forever(self.app_context)
except: # NOQA
traceback.print_exc()
def main_loop(self):
thread = Threading.Thread(Threading.ThreadStart(self.run_app))
thread.SetApartmentState(Threading.ApartmentState.STA)
thread.Start()
thread.Join()
def show_about_dialog(self):
message_parts = []
if self.interface.name is not None:
if self.interface.version is not None:
message_parts.append(
"{name} v{version}".format(
// ===== END =====
// ===== BEGIN python =====
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SimplePhotogrammetryRoutePlanner
A QGIS plugin
A imple photogrammetry route planner.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-04-24
copyright : (C) 2021 by Xiangyong Luo
email : [email protected]
git sha : $Format:%H$
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
This script initializes the plugin, making it known to QGIS.
"""
__version__ = "0.4.0"
# noinspection PyPep8Naming
def classFactory(iface): # pylint: disable=invalid-name
"""Load SimplePhotogrammetryRoutePlanner class from file SimplePhotogrammetryRoutePlanner.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from .SimplePhotogrammetryRoutePlanner import SimplePhotogrammetryRoutePlanner
return SimplePhotogrammetryRoutePlanner(iface)
// ===== END =====
// ===== BEGIN python =====
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 14:38:20 2018
dimension reduction with VarianceThreshold using sklearn.
Feature selector that removes all low-variance features.
@author: lenovo
"""
from sklearn.feature_selection import VarianceThreshold
import numpy as np
#
np.random.seed(1)
X = np.random.randn(100, 10)
X = np.hstack([X, np.zeros([100, 5])])
#
def featureSelection_variance(X, thrd):
sel = VarianceThreshold(threshold=thrd)
X_selected = sel.fit_transform(X)
mask = sel.get_support()
return X_selected, mask
X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]
selector = VarianceThreshold()
selector.fit_transform(X)
selector.variances_
// ===== END =====
// ===== BEGIN python =====
#!/usr/bin/env python
# coding=utf-8
from my_multi_main3 import main
import numpy as np
import argparse
import time
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
parser.add_argument('--norm-flag', type=bool, default=False,
help='Triggering the Layer Normalization flag for attention scores')
parser.add_argument('--gamma', type=float, default=None,
help='Controlling the sparisty of gfusedmax/sparsemax, the smaller, the more sparse')
parser.add_argument('--lam', type=float, default=1.0,
help='Lambda: Controlling the smoothness of gfusedmax, the larger, the smoother')
parser.add_argument('--max-type', type=str, default='softmax',choices=['softmax','sparsemax','gfusedmax'],
help='mapping function in attention')
parser.add_argument('--optim-type', type=str, default='SGD',choices=['SGD','Adam'],
help='mapping function in attention')
parser.add_argument('--head-cnt', type=int, default=2, metavar='S', choices=[1,2,4,5,10],
help='Number of heads for attention (default: 1)')
args = parser.parse_args()
hyperparameter_choices = {
'lr':list(10**np.arange(-4,-1,0.5)),
'norm_flag': [True,False],
'gamma':list(10**np.arange(-1,3,0.5))+[None,],
'lam':list(10**np.arange(-2,2,0.5)),
'max_type':['softmax','sparsemax','gfusedmax'],
# 'max_type':['sparsemax'],
'optim_type':['SGD','Adam'],
'head_cnt':[1,2,4,5,10,20]
}
param_num = 25
record = np.zeros([param_num,len(hyperparameter_choices)+1])
record_name = 'record3_multi_%s.csv'%time.strftime('%Y-%m-%d_%H-%M-%S',time.localtime())
for n in range(param_num):
for param_index,(k,v) in enumerate(hyperparameter_choices.items()):
print(param_index,k)
value_index = np.random.choice(len(v))
if isinstance(v[value_index],str) or isinstance(v[value_index],bool) or v[value_index] is None:
record[n,param_index] = value_index
else:
record[n,param_index] = v[value_index]
setattr(args,k,v[value_index])
record[n,-1] = main(args)
np.savetxt(record_name, record, delimiter=',')
// ===== END =====
// ===== BEGIN python =====
"""HDF5 related files.
This file contains a set of functions that related to read and write
HDF5 files.
Author: Yuhuang Hu
Email : [email protected]
"""
from __future__ import print_function, absolute_import
import h5py
from spiker import log
logger = log.get_logger("data-hdf5", log.DEBUG)
def init_hdf5(file_path, mode="w", cam_type="davis"):
"""Init HDF5 file object.
# Parameters
file_path : str
absolute path for the HDF5 file.
mode : str
w : for writing
r : for reading
cam_type : str
davis : for DAVIS camera
dvs : for DVS camera
# Returns
dataset : h5py.File
The file object of the given dataset
"""
if mode == "w":
dataset = h5py.File(file_path, mode=mode)
dataset.create_group("dvs")
dataset.create_group("extra")
if cam_type == "davis":
dataset.create_group("aps")
dataset.create_group("imu")
elif mode == "r":
dataset = h5py.File(file_path, mode=mode)
return dataset
// ===== END =====
// ===== BEGIN python =====
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flatbuf
import flatbuffers
class FloatingPoint(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsFloatingPoint(cls, buf, offset):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = FloatingPoint()
x.Init(buf, n + offset)
return x
# FloatingPoint
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# FloatingPoint
def Precision(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos)
return 0
def FloatingPointStart(builder): builder.StartObject(1)
def FloatingPointAddPrecision(builder, precision): builder.PrependInt16Slot(0, precision, 0)
def FloatingPointEnd(builder): return builder.EndObject()
// ===== END =====
// ===== BEGIN python =====
"""[Scynced Lights]
Class attributes are "shared"
Instance attributes are not shared.
"""
def sub(x, y):
f
class Light:
pass
a = Light()
b = Ligth()
// ===== END =====
// ===== BEGIN python =====
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<[email protected]>
# http://binux.me
# Created on 2012-11-14 17:09:50
from __future__ import unicode_literals, division, absolute_import
import time
import logging
from collections import deque
try:
from UserDict import DictMixin
except ImportError:
from collections import Mapping as DictMixin
import six
from six import iteritems
from six.moves import cPickle
class BaseCounter(object):
def __init__(self):
raise NotImplementedError
def event(self, value=1):
"""Fire a event."""
raise NotImplementedError
def value(self, value):
"""Set counter value."""
raise NotImplementedError
@property
def avg(self):
"""Get average value"""
raise NotImplementedError
@property
def sum(self):
"""Get sum of counter"""
raise NotImplementedError
def empty(self):
"""Clear counter"""
raise NotImplementedError
class TotalCounter(BaseCounter):
"""Total counter"""
def __init__(self):
self.cnt = 0
def event(self, value=1):
self.cnt += value
def value(self, value):
self.cnt = value
@property
def avg(self):
return self.cnt
@property
def sum(self):
return self.cnt
def empty(self):
return self.cnt == 0
class AverageWindowCounter(BaseCounter):
"""
Record last N(window) value
"""
def __init__(self, window_size=300):
self.window_size = window_size
self.values = deque(maxlen=window_size)
def event(self, value=1):
self.values.append(value)
value = event
@property
def avg(self):
return self.sum / len(self.values)
@property
def sum(self):
return sum(self.values)
def empty(self):
if not self.values:
return True
class TimebaseAverageWindowCounter(BaseCounter):
"""
Record last window_size * window_interval seconds values.
records will trim evert window_interval seconds
"""
def __init__(self, window_size=30, window_interval=10):
self.max_window_size = window_size
self.window_size = 0
self.window_interval = window_interval
self.values = deque(maxlen=window_size)
self.times = deque(maxlen=window_size)
self.cache_value = 0
self.cache_start = None
self._first_data_time = None
def event(self, value=1):
now = time.time()
if self._first_data_time is None:
self._first_data_time = now
if self.cache_start is None:
self.cache_value = value
self.cache_start = now
elif now - self.cache_start > self.window_interval:
self.values.append(self.cache_value)
self.times.append(self.cache_start)
self.on_append(self.cache_value, self.cache_start)
self.cache_value = value
self.cache_start = now
else:
self.cache_value += value
return self
def value(self, value):
self.cache_value = value
def _trim_window(self):
now = time.time()
if self.cache_start and now - self.cache_start > self.window_interval:
self.values.append(self.cache_value)
self.times.append(self.cache_start)
self.on_append(self.cache_value, self.cache_start)
self.cache_value = 0
self.cache_start = None
if self.window_size != self.max_window_size and self._first_data_time is not None:
time_passed = now - self._first_data_time
self.window_size = min(self.max_window_size, time_passed / self.window_interval)
window_limit = now - self.window_size * self.window_interval
while self.times and self.times[0] < window_limit:
self.times.popleft()
self.values.popleft()
@property
def avg(self):
sum = float(self.sum)
if not self.window_size:
return 0
return sum / self.window_size / self.window_interval
@property
def sum(self):
self._trim_window()
return sum(self.values) + self.cache_value
def empty(self):
self._trim_window()
if not self.values and not self.cache_start:
return True
def on_append(self, value, time):
pass
class CounterValue(DictMixin):
"""
A dict like value item for CounterManager.
"""
def __init__(self, manager, keys):
self.manager = manager
self._keys = keys
def __getitem__(self, key):
if key == '__value__':
key = self._keys
return self.manager.counters[key]
else:
key = self._keys + (key, )
available_keys = []
for _key in self.manager.counters:
if _key[:len(key)] == key:
available_keys.append(_key)
if len(available_keys) == 0:
raise KeyError
elif len(available_keys) == 1:
if available_keys[0] == key:
return self.manager.counters[key]
else:
return CounterValue(self.manager, key)
else:
return CounterValue(self.manager, key)
def __len__(self):
return len(self.keys())
def __iter__(self):
return iter(self.keys())
def __contains__(self, key):
return key in self.keys()
def keys(self):
result = set()
for key in self.manager.counters:
if key[:len(self._keys)] == self._keys:
key = key[len(self._keys):]
result.add(key[0] if key else '__value__')
return result
def to_dict(self, get_value=None):
"""Dump counters as a dict"""
result = {}
for key, value in iteritems(self):
if isinstance(value, BaseCounter):
if get_value is not None:
value = getattr(value, get_value)
result[key] = value
else:
result[key] = value.to_dict(get_value)
return result
class CounterManager(DictMixin):
"""
A dict like counter manager.
When using a tuple as event key, say: ('foo', 'bar'), You can visite counter
with manager['foo']['bar']. Or get all counters which first element is 'foo'
by manager['foo'].
It's useful for a group of counters.
"""
def __init__(self, cls=TimebaseAverageWindowCounter):
"""init manager with Counter cls"""
self.cls = cls
self.counters = {}
def event(self, key, value=1):
"""Fire a event of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:
self.counters[key] = self.cls()
self.counters[key].event(value)
return self
def value(self, key, value=1):
"""Set value of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:
self.counters[key] = self.cls()
self.counters[key].value(value)
return self
def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key]
def __getitem__(self, key):
key = (key, )
available_keys = []
for _key in self.counters:
if _key[:len(key)] == key:
available_keys.append(_key)
if len(available_keys) == 0:
raise KeyError
elif len(available_keys) == 1:
if available_keys[0] == key:
return self.counters[key]
else:
return Count
// ===== END =====
// ===== BEGIN python =====
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Feature extractor class for ViT."""
from typing import List, Optional, Union
import numpy as np
from PIL import Image
from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from ...file_utils import TensorType
from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ImageFeatureExtractionMixin, is_torch_tensor
from ...utils import logging
logger = logging.get_logger(__name__)
class ViTFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin):
r"""
Constructs a ViT feature extractor.
This feature extractor inherits from :class:`~transformers.FeatureExtractionMixin` which contains most of the main
methods. Users should refer to this superclass for more information regarding those methods.
Args:
do_resize (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether to resize the input to a certain :obj:`size`.
size (:obj:`int` or :obj:`Tuple(int)`, `optional`, defaults to 224):
Resize the input to the given size. If a tuple is provided, it should be (width, height). If only an
integer is provided, then the input will be resized to (size, size). Only has an effect if :obj:`do_resize`
is set to :obj:`True`.
resample (:obj:`int`, `optional`, defaults to :obj:`PIL.Image.BILINEAR`):
An optional resampling filter. This can be one of :obj:`PIL.Image.NEAREST`, :obj:`PIL.Image.BOX`,
:obj:`PIL.Image.BILINEAR`, :obj:`PIL.Image.HAMMING`, :obj:`PIL.Image.BICUBIC` or :obj:`PIL.Image.LANCZOS`.
Only has an effect if :obj:`do_resize` is set to :obj:`True`.
do_normalize (:obj:`bool`, `optional`, defaults to :obj:`True`):
Whether or not to normalize the input with mean and standard deviation.
image_mean (:obj:`List[int]`, defaults to :obj:`[0.5, 0.5, 0.5]`):
The sequence of means for each channel, to be used when normalizing images.
image_std (:obj:`List[int]`, defaults to :obj:`[0.5, 0.5, 0.5]`):
The sequence of standard deviations for each channel, to be used when normalizing images.
"""
model_input_names = ["pixel_values"]
def __init__(
self,
do_resize=True,
size=224,
resample=Image.BILINEAR,
do_normalize=True,
image_mean=None,
image_std=None,
**kwargs
):
super().__init__(**kwargs)
self.do_resize = do_resize
self.size = size
self.resample = resample
self.do_normalize = do_normalize
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
def __call__(
self,
images: Union[
Image.Image, np.ndarray, "torch.Tensor", List[Image.Image], List[np.ndarray], List["torch.Tensor"] # noqa
],
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs
) -> BatchFeature:
"""
Main method to prepare for the model one or several image(s).
.. warning::
NumPy arrays and PyTorch tensors are converted to PIL images when resizing, so the most efficient is to pass
PIL images.
Args:
images (:obj:`PIL.Image.Image`, :obj:`np.ndarray`, :obj:`torch.Tensor`, :obj:`List[PIL.Image.Image]`, :obj:`List[np.ndarray]`, :obj:`List[torch.Tensor]`):
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
number of channels, H and W are image height and width.
return_tensors (:obj:`str` or :class:`~transformers.file_utils.TensorType`, `optional`, defaults to :obj:`'np'`):
If set, will return tensors of a particular framework. Acceptable values are:
* :obj:`'tf'`: Return TensorFlow :obj:`tf.constant` objects.
* :obj:`'pt'`: Return PyTorch :obj:`torch.Tensor` objects.
* :obj:`'np'`: Return NumPy :obj:`np.ndarray` objects.
* :obj:`'jax'`: Return JAX :obj:`jnp.ndarray` objects.
Returns:
:class:`~transformers.BatchFeature`: A :class:`~transformers.BatchFeature` with the following fields:
- **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
width).
"""
# Input type checking for clearer error
valid_images = False
# Check that images has a valid type
if isinstance(images, (Image.Image, np.ndarray)) or is_torch_tensor(images):
valid_images = True
elif isinstance(images, (list, tuple)):
if len(images) == 0 or isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0]):
valid_images = True
if not valid_images:
raise ValueError(
"Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
"`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
)
is_batched = bool(
isinstance(images, (list, tuple))
and (isinstance(images[0], (Image.Image, np.ndarray)) or is_torch_tensor(images[0]))
)
if not is_batched:
images = [images]
# transformations (resizing + normalization)
if self.do_resize and self.size is not None:
images = [self.resize(image=image, size=self.size, resample=self.resample) for image in images]
if self.do_normalize:
images = [self.normalize(image=image, mean=self.image_mean, std=self.image_std) for image in images]
# return as BatchFeature
data = {"pixel_values": images}
encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
return encoded_inputs
// ===== END =====
// ===== BEGIN python =====
#!/usr/bin/env python3
UNKNOWN = -1
def read_val():
return int(input())
def read_row():
return list(map(int, input().split()))
def read_grid():
return [read_row() for _ in range(read_val())]
def make_blank_row(i):
return [UNKNOWN] * i
def make_blank_grid(n):
return [make_blank_row(i) for i in range(1, n + 1)]
def compute_max_path_sum(grid):
memo = make_blank_grid(len(grid))
def dfs(i, j):
if i == len(grid):
return 0
if memo[i][j] == UNKNOWN:
memo[i][j] = grid[i][j] + max(dfs(i + 1, j), dfs(i + 1, j + 1))
return memo[i][j]
return dfs(0, 0)
for t in range(read_val()):
print(compute_max_path_sum(read_grid()))
// ===== END =====
// ===== BEGIN python =====
import platform
# print(platform.system())
operating_system = platform.system().lower()
if operating_system == 'darwin':
from .blender_utils_macos import get_installed_blender_versions
operating_system_name = 'macos'
elif operating_system == 'linux':
from .blender_utils_linux import get_installed_blender_versions
operating_system_name = 'linux'
elif operating_system == 'windows':
from .blender_utils_windows import get_installed_blender_versions
operating_system_name = 'windows'
else:
raise Exception("Unimplemented for OS {}".format(operating_system))
from .blender_utils_web import get_blender_version_download_links
def find_blender(version):
# TODO: add fuzzy version matching, ie. '>=2.80', '~2.80', '<2.80', etc.
installed_versions = get_installed_blender_versions()
if version in installed_versions:
return installed_versions[version]
else:
print("blender version '{}' not found; found {} version(s):".format(version, len(installed_versions)))
for v, path in installed_versions.items():
print(" {}: {}".format(v, path))
print("searching web archive...")
versions = get_blender_version_download_links(version, operating_system_name)
print("found {} download(s) for blender version '{}', platform '{}':".format(len(versions), version, operating_system_name))
for url in versions:
print(" {}".format(url))
if __name__ == '__main__':
for version, exec_path in get_installed_blender_versions().items():
print("found blender {version}: {path}".format(version=version,
path=exec_path))
blender = find_blender('2.80')
if blender:
print("Found blender: '{}'".format(blender))
else:
print("No matching blender version installed :(")
// ===== END =====
// ===== BEGIN python =====
import functools
import random
from math import cos, pi
import cv2
import kornia
import numpy as np
import torch
from kornia.augmentation import ColorJitter
from data.util import read_img
from PIL import Image
from io import BytesIO
# Get a rough visualization of the above distribution. (Y-axis is meaningless, just spreads data)
from utils.util import opt_get
'''
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
data = np.asarray([get_rand() for _ in range(5000)])
plt.plot(data, np.random.uniform(size=(5000,)), 'x')
plt.show()
'''
def kornia_color_jitter_numpy(img, setting):
if setting * 255 > 1:
# I'm using Kornia's ColorJitter, which requires pytorch arrays in b,c,h,w format.
img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0)
img = ColorJitter(setting, setting, setting, setting)(img)
img = img.squeeze(0).permute(1,2,0).numpy()
return img
# Performs image corruption on a list of images from a configurable set of corruption
# options.
class ImageCorruptor:
def __init__(self, opt):
self.opt = opt
self.reset_random()
self.blur_scale = opt['corruption_blur_scale'] if 'corruption_blur_scale' in opt.keys() else 1
self.fixed_corruptions = opt['fixed_corruptions'] if 'fixed_corruptions' in opt.keys() else []
self.num_corrupts = opt['num_corrupts_per_image'] if 'num_corrupts_per_image' in opt.keys() else 0
self.cosine_bias = opt_get(opt, ['cosine_bias'], True)
if self.num_corrupts == 0:
return
else:
self.random_corruptions = opt['random_corruptions'] if 'random_corruptions' in opt.keys() else []
def reset_random(self):
if 'random_seed' in self.opt.keys():
self.rand = random.Random(self.opt['random_seed'])
else:
self.rand = random.Random()
# Feeds a random uniform through a cosine distribution to slightly bias corruptions towards "uncorrupted".
# Return is on [0,1] with a bias towards 0.
def get_rand(self):
r = self.rand.random()
if self.cosine_bias:
return 1 - cos(r * pi / 2)
else:
return r
def corrupt_images(self, imgs, return_entropy=False):
if self.num_corrupts == 0 and not self.fixed_corruptions:
if return_entropy:
return imgs, []
else:
return imgs
if self.num_corrupts == 0:
augmentations = []
else:
augmentations = random.choices(self.random_corruptions, k=self.num_corrupts)
# Sources of entropy
corrupted_imgs = []
entropy = []
undo_fns = []
applied_augs = augmentations + self.fixed_corruptions
for img in imgs:
for aug in augmentations:
r = self.get_rand()
img, undo_fn = self.apply_corruption(img, aug, r, applied_augs)
if undo_fn is not None:
undo_fns.append(undo_fn)
for aug in self.fixed_corruptions:
r = self.get_rand()
img, undo_fn = self.apply_corruption(img, aug, r, applied_augs)
entropy.append(r)
if undo_fn is not None:
undo_fns.append(undo_fn)
# Apply undo_fns after all corruptions are finished, in same order.
for ufn in undo_fns:
img = ufn(img)
corrupted_imgs.append(img)
if return_entropy:
return corrupted_imgs, entropy
else:
return corrupted_imgs
def apply_corruption(self, img, aug, rand_val, applied_augmentations):
undo_fn = None
if 'color_quantization' in aug:
# Color quantization
quant_div = 2 ** (int(rand_val * 10 / 3) + 2)
img = img * 255
img = (img // quant_div) * quant_div
img = img / 255
elif 'color_jitter' in aug:
lo_end = 0
hi_end = .2
setting = rand_val * (hi_end - lo_end) + lo_end
img = kornia_color_jitter_numpy(img, setting)
elif 'gaussian_blur' in aug:
img = cv2.GaussianBlur(img, (0,0), self.blur_scale*rand_val*1.5)
elif 'motion_blur' in aug:
# Motion blur
intensity = self.blur_scale*rand_val * 3 + 1
angle = random.randint(0,360)
k = np.zeros((intensity, intensity), dtype=np.float32)
k[(intensity - 1) // 2, :] = np.ones(intensity, dtype=np.float32)
k = cv2.warpAffine(k, cv2.getRotationMatrix2D((intensity / 2 - 0.5, intensity / 2 - 0.5), angle, 1.0),
(intensity, intensity))
k = k * (1.0 / np.sum(k))
img = cv2.filter2D(img, -1, k)
elif 'block_noise' in aug:
# Large distortion blocks in part of an img, such as is used to mask out a face.
pass
elif 'lq_resampling' in aug:
# Random mode interpolation HR->LR->HR
if 'lq_resampling4x' == aug:
scale = 4
else:
if rand_val < .3:
scale = 1
elif rand_val < .7:
scale = 2
else:
scale = 4
if scale > 1:
interpolation_modes = [cv2.INTER_NEAREST, cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_LANCZOS4]
mode = random.randint(0,4) % len(interpolation_modes)
# Downsample first, then upsample using the random mode.
img = cv2.resize(img, dsize=(img.shape[1]//scale, img.shape[0]//scale), interpolation=mode)
def lq_resampling_undo_fn(scale, img):
return cv2.resize(img, dsize=(img.shape[1]*scale, img.shape[0]*scale), interpolation=cv2.INTER_LINEAR)
undo_fn = functools.partial(lq_resampling_undo_fn, scale)
elif 'color_shift' in aug:
# Color shift
pass
elif 'interlacing' in aug:
# Interlacing distortion
pass
elif 'chromatic_aberration' in aug:
# Chromatic aberration
pass
elif 'noise' in aug:
# Random noise
if 'noise-5' == aug:
noise_intensity = 5 / 255.0
else:
noise_intensity = (rand_val*6) / 255.0
img += np.random.rand(*img.shape) * noise_intensity
elif 'jpeg' in aug:
if 'noise' not in applied_augmentations and 'noise-5' not in applied_augmentations:
if aug == 'jpeg':
lo=10
range=20
elif aug == 'jpeg-low':
lo=15
range=10
elif aug == 'jpeg-medium':
lo=23
range=25
elif aug == 'jpeg-broad':
lo=15
range=60
elif aug == 'jpeg-normal':
lo=47
range=35
else:
raise NotImplementedError("specified jpeg corruption doesn't exist")
# JPEG compression
qf = (int((1-rand_val)*range) + lo)
# Use PIL to perform a mock compression to a data buffer, then swap back to cv2.
img = (img * 255).astype(np.uint8)
img = Image.fromarray(img)
buffer = BytesIO()
img.save(buffer, "JPEG", quality=qf, optimize=True)
buffer.seek(0)
jpeg_img_bytes = np.asarray(bytearray(buffer.read()), dtype="uint8")
img = read_img("buffer", jpeg_img_bytes, rgb=True)
elif 'saturation' in aug:
# Lightening / saturation
saturation = rand_val * .3
img = np.clip(img + saturation, a_max=1, a_min=0)
elif 'greyscale' in aug:
// ===== END =====
// ===== BEGIN python =====
# This test requires CPython3.5
print(b"%%" % ())
print(b"=%d=" % 1)
print(b"=%d=%d=" % (1, 2))
print(b"=%s=" % b"str")
print(b"=%r=" % b"str")
print("PASS")
// ===== END =====
// ===== BEGIN python =====
#
# test_JpegCompression.py
#
import pytest
import albumentations as A
from .context import TfDataAugmentation as Tfda
from . import test_utils
from .test_utils import TestResult
@pytest.mark.parametrize(
"quality_lower, quality_upper, expected, message", [
# quality_lower
(-1, 100, TestResult.Error,
"quality_lower < min => Error"),
(0, 100, TestResult.OK,
"quality_lower == min => OK"),
(100, 100, TestResult.OK,
"quality_lower == max => OK"),
(101, 100, TestResult.Error,
"quality_lower >= max => Error"),
# quality_upper
(0, -1, TestResult.Error,
"quality_upper < min => Error"),
(0, 0, TestResult.OK,
"quality_upper == min => OK"),
(0, 100, TestResult.OK,
"quality_upper == max => OK"),
(0, 101, TestResult.Error,
"quality_upper > max => Error"),
# Relation
(50, 50, TestResult.OK,
"quality_lower == quality_upper => OK"),
(51, 50, TestResult.Error,
"quality_lower > quality_upper => Error"),
])
def test_hue_shift_limit_value(
quality_lower, quality_upper, expected, message):
try:
Tfda.JpegCompression(
quality_lower=quality_lower,
quality_upper=quality_upper)
actual = TestResult.OK
except ValueError:
actual = TestResult.Error
assert expected == actual, message
def test_call():
quality_lower = 50
quality_upper = 100
tgt_jpeg = Tfda.JpegCompression(
quality_lower=quality_lower,
quality_upper=quality_upper,
p=1.0)
tgt_transform = \
test_utils.make_tgt_transform(tgt_jpeg)
image = test_utils.make_test_image()
tgt_result = tgt_transform(image=image)
actual_image = tgt_result['image']
image_np = image.numpy()
quality = float(tgt_jpeg.get_param('quality'))
expected_image = A.image_compression(
image_np, quality, image_type='.jpg')
test_utils.partial_assert_array(
expected_image, actual_image, 0.6, "image", eps=0.1)
// ===== END =====
// ===== BEGIN python =====
import os
from torch.utils.data import DataLoader
from continuum.datasets import CIFAR10, InMemoryDataset
from continuum.datasets import MNIST
import torchvision
from continuum.scenarios import TransformationIncremental
import pytest
import numpy as np
from continuum.transforms.bg_swap import BackgroundSwap
DATA_PATH = os.environ.get("CONTINUUM_DATA_PATH")
# Uncomment for debugging via image output
# import matplotlib.pyplot as plt
def test_bg_swap_fast():
"""
Fast test for background swap.
"""
bg_x = np.ones(shape=[2, 5, 5, 3]) * -1
bg_y = np.random.rand(2)
fg = np.random.normal(loc=.5, scale=.1, size=[5, 5])
bg = InMemoryDataset(bg_x, bg_y)
bg_swap = BackgroundSwap(bg, input_dim=(5, 5), normalize_bg=None)
spliced_1_channel = bg_swap(fg)[:, :, 0]
assert np.array_equal((spliced_1_channel <= -1), (fg <= .5))
@pytest.mark.slow
def test_background_swap_numpy():
"""
Test background swap on a single ndarray input.
"""
mnist = MNIST(DATA_PATH, download=True, train=True)
cifar = CIFAR10(DATA_PATH, download=True, train=True)
bg_swap = BackgroundSwap(cifar, input_dim=(28, 28))
im = mnist.get_data()[0][0]
im = bg_swap(im)
# Uncomment for debugging
# plt.imshow(im, interpolation='nearest')
# plt.show()
@pytest.mark.slow
def test_background_swap_torch():
"""
Test background swap on a single tensor input.
"""
cifar = CIFAR10(DATA_PATH, download=True, train=True)
mnist = torchvision.datasets.MNIST(DATA_PATH, train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor()
]))
bg_swap = BackgroundSwap(cifar, input_dim=(28, 28))
im = mnist[0][0]
im = bg_swap(im)
# Uncomment for debugging
# plt.imshow(im.permute(1, 2, 0), interpolation='nearest')
# plt.show()
@pytest.mark.slow
def test_background_tranformation():
"""
Example code using TransformationIncremental to create a setting with 3 tasks.
"""
cifar = CIFAR10(DATA_PATH, train=True)
mnist = MNIST(DATA_PATH, download=False, train=True)
nb_task = 3
list_trsf = []
for i in range(nb_task):
list_trsf.append([torchvision.transforms.ToTensor(), BackgroundSwap(cifar, bg_label=i, input_dim=(28, 28)),
torchvision.transforms.ToPILImage()])
scenario = TransformationIncremental(mnist, base_transformations=[torchvision.transforms.ToTensor()],
incremental_transformations=list_trsf)
folder = "tests/samples/background_trsf/"
if not os.path.exists(folder):
os.makedirs(folder)
for task_id, task_data in enumerate(scenario):
task_data.plot(path=folder, title=f"background_{task_id}.jpg", nb_samples=100, shape=[28, 28, 3])
loader = DataLoader(task_data)
_, _, _ = next(iter(loader))
// ===== END =====
// ===== BEGIN python =====
# =========================================================================================
# Copyright 2015 Community Information Online Consortium (CIOC) and KCL Software Solutions
#
# 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.
# =========================================================================================
# std lib
import os
# jQuery and jQueryUI versions
JQUERY_VERSION = "1.6.2"
JQUERY_UI_VERSION = "1.8.16"
# formatting constants
DATE_TEXT_SIZE = 25
TEXT_SIZE = 85
TEXTAREA_COLS = 85
TEXTAREA_ROWS_SHORT = 2
TEXTAREA_ROWS_LONG = 4
TEXTAREA_ROWS_XLONG = 10
MAX_LENGTH_CHECKLIST_NOTES = 255
EMAIL_LENGTH = 60
# application running constants
_app_path = None
_config_file = None
_app_name = None
session_lock_dir = None
publish_dir = None
def update_cache_values():
# called from application init at startup
global _app_path, _config_file, _app_name, session_lock_dir, publish_dir
if _app_path is None:
_app_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
_app_name = os.path.split(_app_path)[1]
_config_file = os.path.join(_app_path, '..', '..', 'config', _app_name + '.ini')
session_lock_dir = os.path.join(_app_path, 'python', 'session_lock')
publish_dir = os.path.join(_app_path, 'python', 'published_files')
try:
os.makedirs(session_lock_dir)
except os.error:
pass
try:
os.makedirs(publish_dir)
except os.error:
pass
// ===== END =====
// ===== BEGIN python =====
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from .._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
class WebSiteManagementClientConfiguration(Configuration):
"""Configuration for WebSiteManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: Your Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).
:type subscription_id: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
super(WebSiteManagementClientConfiguration, self).__init__(**kwargs)
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2015-08-01"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-web/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs: Any
) -> None:
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
// ===== END =====
// ===== BEGIN python =====
import django.http
import unittest.mock
from .. import middleware
def get_response(req):
# dummy get_response, just return an empty response
return django.http.HttpResponse()
def test_leaves_remote_addr_alone_if_no_real_ip():
remote_addr = object()
request = unittest.mock.MagicMock()
request.META = {"REMOTE_ADDR": remote_addr}
middleware.XRealIPMiddleware(get_response)(request)
assert request.META["REMOTE_ADDR"] is remote_addr
def test_switches_out_x_real_ip_if_available():
remote_addr = object()
x_real_ip = object()
request = unittest.mock.MagicMock()
request.META = {"REMOTE_ADDR": remote_addr, "HTTP_X_REAL_IP": x_real_ip}
middleware.XRealIPMiddleware(get_response)(request)
assert request.META["REMOTE_ADDR"] is x_real_ip
assert request.META["HTTP_X_REAL_IP"] is x_real_ip
// ===== END =====
// ===== BEGIN python =====
#!/usr/bin/env python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
GPIO.output(21, GPIO.LOW)
time.sleep(3.00)
GPIO.output(21, GPIO.HIGH)
GPIO.cleanup()
// ===== END =====
// ===== BEGIN python =====
from direct.directnotify.DirectNotifyGlobal import directNotify
class Notifier:
def __init__(self, name):
"""
@param name: The name of the notifier. Be sure to add it to your config/Config.prc!
@type name: str
"""
self.notify = directNotify.newCategory(name)
// ===== END =====
// ===== BEGIN python =====
import numpy as np
def train_ml_squarer() -> None:
print("Training!")
def square() -> int:
"""Square a number...maybe"""
return np.random.randint(1, 100)
if __name__ == '__main__':
train_ml_squarer()
// ===== END =====
// ===== BEGIN python =====
"""
Platformer Game
"""
import arcade
# Constants
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Platformer"
# Constants used to scale our sprites from their original size
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = SPRITE_PIXEL_SIZE * TILE_SCALING
# Movement speed of player, in pixels per frame
PLAYER_MOVEMENT_SPEED = 10
GRAVITY = 1
PLAYER_JUMP_SPEED = 20
class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self):
# Call the parent class and set up the window
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
# Our TileMap Object
self.tile_map = None
# Our Scene Object
self.scene = None
# Separate variable that holds the player sprite
self.player_sprite = None
# Our physics engine
self.physics_engine = None
# A Camera that can be used for scrolling the screen
self.camera = None
# A Camera that can be used to draw GUI elements
self.gui_camera = None
# Keep track of the score
self.score = 0
# Load sounds
self.collect_coin_sound = arcade.load_sound(":resources:sounds/coin1.wav")
self.jump_sound = arcade.load_sound(":resources:sounds/jump1.wav")
arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)
def setup(self):
"""Set up the game here. Call this function to restart the game."""
# Setup the Cameras
self.camera = arcade.Camera(self.width, self.height)
self.gui_camera = arcade.Camera(self.width, self.height)
# Name of map file to load
map_name = ":resources:tiled_maps/map.json"
# Layer specific options are defined based on Layer names in a dictionary
# Doing this will make the SpriteList for the platforms layer
# use spatial hashing for detection.
layer_options = {
"Platforms": {
"use_spatial_hash": True,
},
}
# Read in the tiled map
self.tile_map = arcade.load_tilemap(map_name, TILE_SCALING, layer_options)
# Initialize Scene with our TileMap, this will automatically add all layers
# from the map as SpriteLists in the scene in the proper order.
self.scene = arcade.Scene.from_tilemap(self.tile_map)
# Keep track of the score
self.score = 0
# Set up the player, specifically placing it at these coordinates.
image_source = ":resources:images/animated_characters/female_adventurer/femaleAdventurer_idle.png"
self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
self.player_sprite.center_x = 128
self.player_sprite.center_y = 128
self.scene.add_sprite("Player", self.player_sprite)
# --- Other stuff
# Set the background color
if self.tile_map.background_color:
arcade.set_background_color(self.tile_map.background_color)
# Create the 'physics engine'
self.physics_engine = arcade.PhysicsEnginePlatformer(
self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Platforms"]
)
def on_draw(self):
"""Render the screen."""
# Clear the screen to the background color
arcade.start_render()
# Activate the game camera
self.camera.use()
# Draw our Scene
self.scene.draw()
# Activate the GUI camera before drawing GUI elements
self.gui_camera.use()
# Draw our score on the screen, scrolling it with the viewport
score_text = f"Score: {self.score}"
arcade.draw_text(
score_text,
10,
10,
arcade.csscolor.WHITE,
18,
)
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed."""
if key == arcade.key.UP or key == arcade.key.W:
if self.physics_engine.can_jump():
self.player_sprite.change_y = PLAYER_JUMP_SPEED
arcade.play_sound(self.jump_sound)
elif key == arcade.key.LEFT or key == arcade.key.A:
self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
elif key == arcade.key.RIGHT or key == arcade.key.D:
self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
"""Called when the user releases a key."""
if key == arcade.key.LEFT or key == arcade.key.A:
self.player_sprite.change_x = 0
elif key == arcade.key.RIGHT or key == arcade.key.D:
self.player_sprite.change_x = 0
def center_camera_to_player(self):
screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)
screen_center_y = self.player_sprite.center_y - (
self.camera.viewport_height / 2
)
if screen_center_x < 0:
screen_center_x = 0
if screen_center_y < 0:
screen_center_y = 0
player_centered = screen_center_x, screen_center_y
self.camera.move_to(player_centered)
def on_update(self, delta_time):
"""Movement and game logic"""
# Move the player with the physics engine
self.physics_engine.update()
# See if we hit any coins
coin_hit_list = arcade.check_for_collision_with_list(
self.player_sprite, self.scene["Coins"]
)
# Loop through each coin we hit (if any) and remove it
for coin in coin_hit_list:
# Remove the coin
coin.remove_from_sprite_lists()
# Play a sound
arcade.play_sound(self.collect_coin_sound)
# Add one to the score
self.score += 1
# Position the camera
self.center_camera_to_player()
def main():
"""Main function"""
window = MyGame()
window.setup()
arcade.run()
if __name__ == "__main__":
main()
// ===== END =====
// ===== BEGIN python =====
#!/usr/bin/env python3
'''
lib/ycmd/start.py
Server bootstrap logic. Includes a utility class for normalizing parameters and
calculating default ones. Also includes a helper to set up the temporary
options file.
'''
import logging
import os
import tempfile
from ..process import (
FileHandles,
Process,
)
from ..util.fs import (
default_python_binary_path,
save_json_file,
)
from ..ycmd.constants import (
YCMD_LOG_SPOOL_OUTPUT,
YCMD_LOG_SPOOL_SIZE,
YCMD_DEFAULT_SERVER_CHECK_INTERVAL_SECONDS,
YCMD_DEFAULT_SERVER_IDLE_SUICIDE_SECONDS,
)
from ..ycmd.settings import (
get_default_settings_path,
generate_settings_data,
)
logger = logging.getLogger('sublime-ycmd.' + __name__)
class StartupParameters(object):
'''
Startup parameters for a ycmd server instance.
Should include all the necessary configuration for creating the ycmd
server process. Also calculates defaults for certain parameters.
'''
def __init__(self, ycmd_root_directory=None,
ycmd_settings_path=None,
working_directory=None,
python_binary_path=None,
server_idle_suicide_seconds=None,
server_check_interval_seconds=None):
self._ycmd_root_directory = None
self._ycmd_settings_path = None
self._working_directory = None
self._python_binary_path = None
self._server_idle_suicide_seconds = None
self._server_check_interval_seconds = None
# additional attributes, can be set via the properties
self._log_level = None
self._stdout_log_path = None
self._stderr_log_path = None
self._keep_logs = None
self.ycmd_root_directory = ycmd_root_directory
self.ycmd_settings_path = ycmd_settings_path
self.working_directory = working_directory
self.python_binary_path = python_binary_path
self.server_idle_suicide_seconds = server_idle_suicide_seconds
self.server_check_interval_seconds = server_check_interval_seconds
@property
def ycmd_root_directory(self):
if self._ycmd_root_directory is None:
logger.warning('no ycmd root directory has been set')
return self._ycmd_root_directory
@ycmd_root_directory.setter
def ycmd_root_directory(self, ycmd_root_directory):
if ycmd_root_directory is not None and \
not isinstance(ycmd_root_directory, str):
raise TypeError(ycmd_root_directory,)
self._ycmd_root_directory = ycmd_root_directory
@property
def ycmd_settings_path(self):
if self._ycmd_settings_path is None:
if self._ycmd_root_directory is not None:
return get_default_settings_path(self._ycmd_root_directory)
logger.warning('no ycmd root directory has been set')
return self._ycmd_settings_path
@ycmd_settings_path.setter
def ycmd_settings_path(self, ycmd_settings_path):
if ycmd_settings_path is not None and \
not isinstance(ycmd_settings_path, str):
raise TypeError(ycmd_settings_path,)
self._ycmd_settings_path = ycmd_settings_path
@property
def working_directory(self):
if self._working_directory is None:
return os.getcwd()
return self._working_directory
@working_directory.setter
def working_directory(self, working_directory):
if working_directory is not None and \
not isinstance(working_directory, str):
raise TypeError(working_directory,)
self._working_directory = working_directory
@property
def python_binary_path(self):
if self._python_binary_path is None:
return default_python_binary_path()
return self._python_binary_path
@python_binary_path.setter
def python_binary_path(self, python_binary_path):
if python_binary_path is not None and \
not isinstance(python_binary_path, str):
raise TypeError(python_binary_path,)
self._python_binary_path = python_binary_path
@property
def server_idle_suicide_seconds(self):
if self._server_idle_suicide_seconds is None:
return YCMD_DEFAULT_SERVER_IDLE_SUICIDE_SECONDS
return self._server_idle_suicide_seconds
@server_idle_suicide_seconds.setter
def server_idle_suicide_seconds(self, server_idle_suicide_seconds):
if server_idle_suicide_seconds is not None and \
not isinstance(server_idle_suicide_seconds, int):
raise TypeError(server_idle_suicide_seconds,)
self._server_idle_suicide_seconds = server_idle_suicide_seconds
@property
def server_check_interval_seconds(self):
if self._server_check_interval_seconds is None:
return YCMD_DEFAULT_SERVER_CHECK_INTERVAL_SECONDS
return self._server_check_interval_seconds
@server_check_interval_seconds.setter
def server_check_interval_seconds(self, server_check_interval_seconds):
if server_check_interval_seconds is not None and \
not isinstance(server_check_interval_seconds, int):
raise TypeError(server_check_interval_seconds,)
self._server_check_interval_seconds = server_check_interval_seconds
@property
def log_level(self):
return self._log_level
@log_level.setter
def log_level(self, log_level):
if log_level is not None and not isinstance(log_level, str):
raise TypeError('log level must be a str: %r' % (log_level))
if log_level is not None and not _is_valid_log_level(log_level):
logger.warning('log level unrecognized: %r', log_level)
# but fall through and do it anyway
self._log_level = log_level
@property
def stdout_log_path(self):
return self._stdout_log_path
@stdout_log_path.setter
def stdout_log_path(self, stdout_log_path):
if stdout_log_path is not None and \
not isinstance(stdout_log_path, str):
raise TypeError(
'stdout log path must be a str: %r' % (stdout_log_path)
)
self._stdout_log_path = stdout_log_path
@property
def stderr_log_path(self):
return self._stderr_log_path
@stderr_log_path.setter
def stderr_log_path(self, stderr_log_path):
if stderr_log_path is not None and \
not isinstance(stderr_log_path, str):
raise TypeError(
'stderr_log_path must be a str: %r' % (stderr_log_path)
)
self._stderr_log_path = stderr_log_path
@property
def keep_logs(self):
if self._keep_logs is None:
return False
return self._keep_logs
@keep_logs.setter
def keep_logs(self, keep_logs):
if keep_logs is not None and not isinstance(keep_logs, bool):
raise TypeError('keep-logs must be a bool: %r' % (keep_logs))
self._keep_logs = keep_logs
@property
def ycmd_module_directory(self):
if self._ycmd_root_directory is None:
logger.error('no ycmd root directory set')
raise AttributeError
return os.path.join(self._ycmd_root_directory, 'ycmd')
def copy(self):
'''
Creates a shallow-copy of the startup parameters.
'''
raw_attrs = [
'_ycmd_root_directory',
'_ycmd_settings_path',
'_working_directory',
'_python_binary_path',
'_server_idle_suicide_seconds',
'_server_check_interval_seconds',
'_log_level',
'_stdout_log_path',
'_stderr_log_path',
'_keep_logs',
]
result = StartupParameters()
for attr in raw_attrs:
attr_value = getattr(self, attr)
setattr(result, attr, attr_value)
return result
def __iter__(self):
''' Dictionary-compatibl
// ===== END =====
// ===== BEGIN javascript =====
/*
* Copyright 2019 Lightbend Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const should = require("chai").should();
const Long = require("long");
const PNCounter = require("../../src/crdts/pncounter");
const protobufHelper = require("../../src/protobuf-helper");
const CrdtDelta = protobufHelper.moduleRoot.cloudstate.crdt.CrdtDelta;
function roundTripDelta(delta) {
return CrdtDelta.decode(CrdtDelta.encode(delta).finish());
}
describe("PNCounter", () => {
it("should have a value of zero when instantiated", () => {
const counter = new PNCounter();
counter.value.should.equal(0);
should.equal(counter.getAndResetDelta(), null);
});
it("should reflect a delta update", () => {
const counter = new PNCounter();
counter.applyDelta(roundTripDelta({
pncounter: {
change: 10
}
}));
counter.value.should.equal(10);
// Try incrementing it again
counter.applyDelta(roundTripDelta({
pncounter: {
change: -3
}
}));
counter.value.should.equal(7);
});
it("should generate deltas", () => {
const counter = new PNCounter();
counter.increment(10);
counter.value.should.equal(10);
roundTripDelta(counter.getAndResetDelta()).pncounter.change.toNumber().should.equal(10);
should.equal(counter.getAndResetDelta(), null);
counter.decrement(3);
counter.value.should.equal(7);
counter.decrement(4);
counter.value.should.equal(3);
roundTripDelta(counter.getAndResetDelta()).pncounter.change.toNumber().should.equal(-7);
should.equal(counter.getAndResetDelta(), null);
});
it("should support long values", () => {
const impossibleDouble = Long.ZERO.add(Number.MAX_SAFE_INTEGER).add(1);
const counter = new PNCounter();
counter.increment(Number.MAX_SAFE_INTEGER);
counter.increment(1);
counter.longValue.should.eql(impossibleDouble);
roundTripDelta(counter.getAndResetDelta()).pncounter.change.should.eql(impossibleDouble);
});
it("should support incrementing by long values", () => {
const impossibleDouble = Long.ZERO.add(Number.MAX_SAFE_INTEGER).add(1);
const counter = new PNCounter();
counter.increment(impossibleDouble);
counter.longValue.should.eql(impossibleDouble);
roundTripDelta(counter.getAndResetDelta()).pncounter.change.should.eql(impossibleDouble);
});
it("should support empty initial deltas (for ORMap added)", () => {
const counter = new PNCounter();
counter.value.should.equal(0);
should.equal(counter.getAndResetDelta(), null);
roundTripDelta(counter.getAndResetDelta(/* initial = */ true)).pncounter.change.toNumber().should.equal(0);
});
});
// ===== END =====
// ===== BEGIN javascript =====
import express from 'express'
// const PatientController = require('../controllers/patient-controller');
// import {PatientController} from '../controllers/patient-controller';
import {getItems,
getItemById,
createItem,
updateItem,
deleteItem} from '../controllers/patient-controller.js';
export const router = express.Router();
router.get('/items', getItems);
router.get('/item/:id', getItemById);
router.post('/item', createItem);
router.put('/item/:id', updateItem);
router.delete('/item/:id', deleteItem);
// module.exports = router;
// ===== END =====
// ===== BEGIN javascript =====
var webPasses = require('../lib/http-proxy/passes/web-incoming'),
httpProxy = require('../lib/http-proxy'),
expect = require('expect.js'),
http = require('http');
describe('lib/http-proxy/passes/web.js', function() {
describe('#deleteLength', function() {
it('should change `content-length`', function() {
var stubRequest = {
method: 'DELETE',
headers: {}
};
webPasses.deleteLength(stubRequest, {}, {});
expect(stubRequest.headers['content-length']).to.eql('0');
})
});
describe('#timeout', function() {
it('should set timeout on the socket', function() {
var done = false, stubRequest = {
socket: {
setTimeout: function(value) { done = value; }
}
}
webPasses.timeout(stubRequest, {}, { timeout: 5000});
expect(done).to.eql(5000);
});
});
describe('#XHeaders', function () {
var stubRequest = {
connection: {
remoteAddress: '192.168.1.2',
remotePort: '8080'
},
headers: {
host: '192.168.1.2:8080'
}
}
it('set the correct x-forwarded-* headers', function () {
webPasses.XHeaders(stubRequest, {}, { xfwd: true });
expect(stubRequest.headers['x-forwarded-for']).to.be('192.168.1.2');
expect(stubRequest.headers['x-forwarded-port']).to.be('8080');
expect(stubRequest.headers['x-forwarded-proto']).to.be('http');
});
});
});
describe('#createProxyServer.web() using own http server', function () {
it('should proxy the request using the web proxy handler', function (done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
function requestHandler(req, res) {
proxy.web(req, res);
}
var proxyServer = http.createServer(requestHandler);
var source = http.createServer(function(req, res) {
source.close();
proxyServer.close();
expect(req.method).to.eql('GET');
expect(req.headers.host.split(':')[1]).to.eql('8081');
done();
});
proxyServer.listen('8081');
source.listen('8080');
http.request('http://127.0.0.1:8081', function() {}).end();
});
it('should detect a proxyReq event and modify headers', function (done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080',
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
function requestHandler(req, res) {
proxy.web(req, res);
}
var proxyServer = http.createServer(requestHandler);
var source = http.createServer(function(req, res) {
source.close();
proxyServer.close();
expect(req.headers['x-special-proxy-header']).to.eql('foobar');
done();
});
proxyServer.listen('8081');
source.listen('8080');
http.request('http://127.0.0.1:8081', function() {}).end();
});
it('should proxy the request and handle error via callback', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
var proxyServer = http.createServer(requestHandler);
function requestHandler(req, res) {
proxy.web(req, res, function (err) {
proxyServer.close();
expect(err).to.be.an(Error);
expect(err.code).to.be('ECONNREFUSED');
done();
});
}
proxyServer.listen('8082');
http.request({
hostname: '127.0.0.1',
port: '8082',
method: 'GET',
}, function() {}).end();
});
it('should proxy the request and handle error via event listener', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
var proxyServer = http.createServer(requestHandler);
function requestHandler(req, res) {
proxy.once('error', function (err, errReq, errRes) {
proxyServer.close();
expect(err).to.be.an(Error);
expect(errReq).to.be.equal(req);
expect(errRes).to.be.equal(res);
expect(err.code).to.be('ECONNREFUSED');
done();
});
proxy.web(req, res);
}
proxyServer.listen('8083');
http.request({
hostname: '127.0.0.1',
port: '8083',
method: 'GET',
}, function() {}).end();
});
it('should proxy the request and handle timeout error (proxyTimeout)', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:45000',
proxyTimeout: 100
});
require('net').createServer().listen(45000);
var proxyServer = http.createServer(requestHandler);
var started = new Date().getTime();
function requestHandler(req, res) {
proxy.once('error', function (err, errReq, errRes) {
proxyServer.close();
expect(err).to.be.an(Error);
expect(errReq).to.be.equal(req);
expect(errRes).to.be.equal(res);
expect(new Date().getTime() - started).to.be.greaterThan(99);
expect(err.code).to.be('ECONNRESET');
done();
});
proxy.web(req, res);
}
proxyServer.listen('8084');
http.request({
hostname: '127.0.0.1',
port: '8084',
method: 'GET',
}, function() {}).end();
});
it('should proxy the request and handle timeout error', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:45001',
timeout: 100
});
require('net').createServer().listen(45001);
var proxyServer = http.createServer(requestHandler);
var cnt = 0;
var doneOne = function() {
cnt += 1;
if(cnt === 2) done();
}
var started = new Date().getTime();
function requestHandler(req, res) {
proxy.once('error', function (err, errReq, errRes) {
proxyServer.close();
expect(err).to.be.an(Error);
expect(errReq).to.be.equal(req);
expect(errRes).to.be.equal(res);
expect(err.code).to.be('ECONNRESET');
doneOne();
});
proxy.web(req, res);
}
proxyServer.listen('8085');
var req = http.request({
hostname: '127.0.0.1',
port: '8085',
method: 'GET',
}, function() {});
req.on('error', function(err) {
expect(err).to.be.an(Error);
expect(err.code).to.be('ECONNRESET');
expect(new Date().getTime() - started).to.be.greaterThan(99);
doneOne();
});
req.end();
});
it('should proxy the request and provide a proxyRes event with the request and response parameters', function(done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
function requestHandler(req, res) {
proxy.once('proxyRes', function (proxyRes, pReq, pRes) {
source.close();
proxyServer.close();
expect(pReq).to.be.equal(req);
expect(pRes).to.be.equal(res);
done();
});
proxy.web(req, res);
}
var proxyServer = http.createServer(requestHandler);
var source = http.createServer(function(req, res) {
res.end('Response');
});
proxyServer.listen('8086');
source.listen('8080');
http.request('http://127.0.0.1:8086', function() {}).end();
});
it('should proxy the request and handle changeOrigin option', function (done) {
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080',
changeOrigin: true
});
function requestHandler(req, res) {
proxy.web(req, res);
}
var proxyServer = http.createServer(requestHandler);
var source = http.createServer(function(req, res) {
source.close();
proxyServer.close();
expect(req.method).to.eql('GET');
expect(req.headers.host.split(':')[1]).to.eql('8080');
done();
});
proxyServer.listen('8081');
source.listen('8080');
http.request('http://127.0.0.1:8081', function() {}).end();
});
});
// ===== END =====
// ===== BEGIN javascript =====
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
app: 'app',
dist: 'dist',
test: 'test',
sass: {
dist: {
options: {
style: 'expanded', // expanded or nested or compact or compressed
loadPath: '<%= app %>/bower_components/foundation/scss',
compass: true,
quiet: true
},
files: {
'<%= app %>/css/app.css': '<%= app %>/scss/app.scss'
}
}
},
postcss: {
options: {
processors: [
require('autoprefixer')({browsers: 'last 2 versions'})
]
},
dist: {
src: '<%= app %>/css/app.css'
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'<%= app %>/js/**/*.js'
]
},
karma: {
unit: {
configFile: '<%= test %>/karma.conf.js'
}
},
clean: {
dist: {
src: ['<%= dist %>/*']
},
},
copy: {
dist: {
files: [{
expand: true,
cwd:'<%= app %>/',
src: ['fonts/**', '**/*.html', '!**/*.scss', '!bower_components/**'],
dest: '<%= dist %>/'
}]
},
},
imagemin: {
target: {
files: [{
expand: true,
cwd: '<%= app %>/images/',
src: ['**/*.{jpg,gif,svg,jpeg,png}'],
dest: '<%= dist %>/images/'
}]
}
},
uglify: {
options: {
preserveComments: 'some',
mangle: false
}
},
useminPrepare: {
html: ['<%= app %>/index.html'],
options: {
dest: '<%= dist %>'
}
},
usemin: {
html: ['<%= dist %>/**/*.html', '!<%= app %>/bower_components/**'],
css: ['<%= dist %>/css/**/*.css'],
options: {
dirs: ['<%= dist %>']
}
},
watch: {
grunt: {
files: ['Gruntfile.js'],
tasks: ['sass', 'postcss']
},
sass: {
files: '<%= app %>/scss/**/*.scss',
tasks: ['sass', 'postcss']
},
livereload: {
files: ['<%= app %>/**/*.html', '!<%= app %>/bower_components/**', '<%= app %>/js/**/*.js', '<%= app %>/css/**/*.css', '<%= app %>/images/**/*.{jpg,gif,svg,jpeg,png}'],
options: {
livereload: true
}
}
},
connect: {
app: {
options: {
port: 9000,
base: '<%= app %>/',
open: true,
livereload: true,
hostname: '127.0.0.1'
}
},
dist: {
options: {
port: 9001,
base: '<%= dist %>/',
open: true,
keepalive: true,
livereload: false,
hostname: '127.0.0.1'
}
}
},
wiredep: {
target: {
src: [
'<%= app %>/**/*.html'
],
exclude: [
'modernizr',
'jquery-placeholder',
'foundation'
]
}
}
});
grunt.registerTask('compile-sass', ['sass', 'postcss']);
grunt.registerTask('bower-install', ['wiredep']);
grunt.registerTask('default', ['compile-sass', 'bower-install', 'connect:app', 'watch']);
grunt.registerTask('validate-js', ['jshint']);
grunt.registerTask('server-dist', ['connect:dist']);
grunt.registerTask('publish', ['compile-sass', 'clean:dist', 'validate-js', 'useminPrepare', 'copy:dist', 'newer:imagemin', 'concat', 'cssmin', 'uglify', 'usemin']);
grunt.loadNpmTasks('grunt-karma');
};
// ===== END =====
// ===== BEGIN javascript =====
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(["dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"dojo/topic",
"app/context/app-topics",
"app/common/Templated",
"dojo/text!./templates/App.html",
"dojo/i18n!../nls/resources",
"app/etc/util",
"app/main/SearchPanel",
"app/main/MapPanel",
"app/main/AboutPanel",
"app/content/MetadataEditor",
"app/content/UploadMetadata"],
function(declare, lang, array, topic, appTopics, Templated, template, i18n, util, SearchPanel, MapPanel, AboutPanel,
MetadataEditor, UploadMetadata) {
var oThisClass = declare([Templated], {
i18n: i18n,
templateString: template,
postCreate: function() {
this.inherited(arguments);
var self = this;
this.updateUI();
var ignoreMapPanelActivated = false;
$("a[href='#searchPanel']").on("shown.bs.tab",lang.hitch(this, function(e) {
this.setHash('searchPanel')
}));
$("a[href='#mapPanel']").on("shown.bs.tab",lang.hitch(this, function(e) {
this.setHash('mapPanel')
if (!ignoreMapPanelActivated && !self.mapPanel.mapWasInitialized) {
self.mapPanel.ensureMap();
}
}));
$("a[href='#aboutPanel']").on("shown.bs.tab",lang.hitch(this, function(e) {
this.setHash('aboutPanel')
}));
topic.subscribe(appTopics.AddToMapClicked,lang.hitch(this, function(params){
if (self.mapPanel.mapWasInitialized) {
$("a[href='#mapPanel']").tab("show");
self.mapPanel.addToMap(params);
} else {
var urlParams = {resource: params.type+":"+this.normalizeUrl(params.url)};
ignoreMapPanelActivated = true;
$("a[href='#mapPanel']").tab("show");
self.mapPanel.ensureMap(urlParams);
ignoreMapPanelActivated = false;
}
}));
topic.subscribe(appTopics.SignedIn,function(params){
self.updateUI();
});
$("#idAppDropdown").on("show.bs.dropdown",function() {
self.updateUI();
});
if (location.hash==null || location.hash.length==0) {
this.setHash('searchPanel')
} else if ( $("a[href='"+location.hash+"']").length > 0) {
$("a[href='"+location.hash+"']").tab("show");
}
},
/* =================================================================================== */
setHash: function(hash) {
var el = document.getElementById(hash);
var id = el.id;
el.removeAttribute('id');
location.hash = hash;
el.setAttribute('id',id);
},
createMetadataClicked: function() {
var editor = new MetadataEditor();
editor.show();
},
signInClicked: function() {
AppContext.appUser.showSignIn();
},
signOutClicked: function() {
AppContext.appUser.signOut();
},
uploadClicked: function() {
if (AppContext.appUser.isPublisher()) (new UploadMetadata()).show();
},
editFacetClicked: function() {
console.warn("TODO provide edit facet functionality in App.js")
},
/* =================================================================================== */
getCreateAccountUrl: function() {
if (AppContext.geoportal && AppContext.geoportal.createAccountUrl) {
return util.checkMixedContent(AppContext.geoportal.createAccountUrl);
}
return null;
},
updateUI: function() {
var updateHref = function(node,link,href) {
if (typeof href === "string" && href.length > 0) {
link.href = href;
node.style.display = "";
} else {
link.href = "#";
node.style.display = "none";
}
};
var v;
if (AppContext.appUser.isSignedIn()) {
v = i18n.nav.welcomePattern.replace("{name}",AppContext.appUser.getUsername());
util.setNodeText(this.usernameNode,v);
this.userOptionsNode.style.display = "";
this.signInNode.style.display = "none";
this.signOutNode.style.display = "";
this.adminOptionsBtnNode.style.display = "";
updateHref(this.createAccountNode,this.createAccountLink,null);
updateHref(this.myProfileNode,this.myProfileLink,AppContext.appUser.getMyProfileUrl());
} else {
this.usernameNode.innerHTML = "";
this.userOptionsNode.style.display = "none";
this.createAccountNode.style.display = "none";
this.signInNode.style.display = "";
this.signOutNode.style.display = "none";
this.adminOptionsBtnNode.style.display = "none";
updateHref(this.createAccountNode,this.createAccountLink,this.getCreateAccountUrl());
updateHref(this.myProfileNode,this.myProfileLink,null);
}
var isAdmin = AppContext.appUser.isAdmin();
var isPublisher = AppContext.appUser.isPublisher();
$("li[data-role='admin']").each(function(i,nd) {
if (isAdmin) nd.style.display = "";
else nd.style.display = "none";
});
$("li[data-role='publisher']").each(function(i,nd) {
if (isPublisher) nd.style.display = "";
else nd.style.display = "none";
});
if (!FileReader) this.uploadNode.style.display = "none";
},
normalizeUrl: function(url) {
var services = ["mapserver", "imageserver", "featureserver", "streamserver", "vectortileserver"];
var selSrv = array.filter(services, function(srv) { return url.toLowerCase().indexOf(srv)>=0; });
if (selSrv && selSrv.length>0) {
var srv = selSrv[0];
url = url.substr(0, url.toLowerCase().indexOf(srv) + srv.length);
}
return url;
},
_onHome: function() {
this.searchPanelLink.click()
location.hash = "searchPanel"
}
});
return oThisClass;
});
// ===== END =====
// ===== BEGIN javascript =====
const AWS = require('aws-sdk');
require('amazon-cognito-js');
const { onConflict, onDatasetDeleted, onDatasetsMerged } = require('./sync-handlers');
const cognitoSyncManager = () => new AWS.CognitoSyncManager({ DataStore: AWS.CognitoSyncManager.StoreInMemory });
const getCognitoCredentials = (accessToken) => {
// Initialize the Amazon Cognito credentials provider
AWS.config.region = process.env.COGNITO_AWS_REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: process.env.COGNITO_IDENTITY_POOL_ID,
Logins: { 'www.amazon.com': accessToken },
});
return AWS.config.credentials.getPromise();
};
const openOrCreateDataset = datasetName => new Promise((resolve, reject) => {
cognitoSyncManager().openOrCreateDataset(datasetName, (error, dataset) => {
if (error) {
console.error(`Failed to open dataset: ${datasetName}`, error);
return reject(error);
}
console.log('Opened dataset:', datasetName);
return resolve(dataset);
});
});
const saveItemsToDataset = (dataset, items) => new Promise((resolve, reject) => {
dataset.putAll(items, (error) => {
if (error) {
console.error(`Failed to save items to dataset: ${items}`, error);
return reject(error);
}
console.log('Saved items to dataset:', items);
return resolve(dataset);
});
});
const saveItemToDataset = (dataset, itemId, item) => new Promise((resolve, reject) => {
dataset.put(itemId, item, (error, record) => {
if (error) {
console.error(`Failed to save item to dataset: ${item}`, error);
return reject(error);
}
console.log('Saved item to dataset:', record);
return resolve(dataset);
});
});
const removeItemsFromDataset = (dataset, itemIds) => {
// Save null values for the specified item IDs, causing them to be removed upon synchronization.
const removedItems = itemIds.reduce((records, itemId) => ({ ...records, [itemId]: null }), {});
return saveItemsToDataset(dataset, removedItems);
};
const removeItemFromDataset = (dataset, itemId) => new Promise((resolve, reject) => {
dataset.remove(itemId, (error, record) => {
if (error) {
console.error(`Failed to remove item from dataset: ${itemId}`, error);
return reject(error);
}
console.log('Removed item from dataset:', record);
return resolve(dataset);
});
});
const synchronizeDataset = dataset => new Promise((resolve, reject) => {
dataset.synchronize({
onSuccess(syncedDataset, updatedRecords) {
console.log('Synchronized dataset to remote store:', `${updatedRecords.length} records updated`);
resolve(syncedDataset);
},
onFailure(error) {
console.error('Failed to synchronize dataset to remote store:', error);
reject(error);
},
onConflict,
onDatasetDeleted,
onDatasetsMerged,
});
});
module.exports = {
getCognitoCredentials,
openOrCreateDataset,
saveItemsToDataset,
saveItemToDataset,
removeItemsFromDataset,
removeItemFromDataset,
synchronizeDataset,
};
// ===== END =====
// ===== BEGIN javascript =====
Template[getTemplate('postUpvote')].helpers({
upvoted: function(){
var user = Meteor.user();
if(!user) return false;
return _.include(this.upvoters, user._id);
},
oneBasedRank: function(){
if(typeof this.rank !== 'undefined')
return this.rank + 1;
}
});
Template[getTemplate('postUpvote')].events({
'click .upvote-link': function(e, instance){
var post = this;
e.preventDefault();
if(!Meteor.user()){
Router.go('/signin');
throwError(i18n.t("Please log in first"));
}
Meteor.call('upvotePost', post, function(error, result){
trackEvent("post upvoted", {'_id': post._id});
});
}
});
// ===== END =====
// ===== BEGIN javascript =====
var m = require('mithril');
module.exports = m.trust('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="24" height="24" viewBox="0 0 24.00 24.00" enable-background="new 0 0 24.00 24.00" xml:space="preserve"><path fill="#000000" fill-opacity="1" stroke-width="1.33333" stroke-linejoin="miter" d="M 3,4C 1.89001,3.9966 1,4.89 1,6L 1,17L 3,17C 3,18.6568 4.34315,20 6,20C 7.65685,20 9,18.6568 9,17L 15,17C 15,18.6568 16.3431,20 18,20C 19.6569,20 21,18.6568 21,17L 23,17L 23,14C 23,12.89 22.11,12 21,12L 19,12L 19,9.5L 23,9.5L 23,6C 23,4.89 22.1097,3.975 21,4L 3,4 Z M 2.5,5.5L 6.5,5.5L 6.5,8L 2.5,8L 2.5,5.5 Z M 8,5.5L 12,5.5L 12,8L 8,8L 8,5.5 Z M 13.5,5.5L 17.5,5.5L 17.5,8L 13.5,8L 13.5,5.5 Z M 19,5.5L 21.5,5.5L 21.5,8L 19,8L 19,5.5 Z M 13.5,9.5L 17.5,9.5L 17.5,12L 13.5,12L 13.5,9.5 Z M 2.5,9.5L 6.5,9.5L 6.5,12L 2.5,12L 2.5,9.5 Z M 8,9.5L 12,9.5L 12,12L 8,12L 8,9.5 Z M 6,15.5C 6.82843,15.5 7.5,16.1716 7.5,17C 7.5,17.8284 6.82843,18.5 6,18.5C 5.17157,18.5 4.5,17.8284 4.5,17C 4.5,16.1716 5.17157,15.5 6,15.5 Z M 18,15.5C 18.8284,15.5 19.5,16.1716 19.5,17C 19.5,17.8284 18.8284,18.5 18,18.5C 17.1716,18.5 16.5,17.8284 16.5,17C 16.5,16.1716 17.1716,15.5 18,15.5 Z "/></svg>');
// ===== END =====
// ===== BEGIN javascript =====
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'plugins/security/views/management/change_password_form/change_password_form';
import 'plugins/security/views/management/password_form/password_form';
import 'plugins/security/views/management/users';
import 'plugins/security/views/management/roles';
import 'plugins/security/views/management/edit_user';
import 'plugins/security/views/management/edit_role/index';
import 'plugins/security/views/management/management.less';
import routes from 'ui/routes';
import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info';
import '../../services/shield_user';
import { ROLES_PATH, USERS_PATH } from './management_urls';
import { management } from 'ui/management';
routes.defaults(/\/management/, {
resolve: {
securityManagementSection: function (ShieldUser, Private) {
const xpackInfo = Private(XPackInfoProvider);
const showSecurityLinks = xpackInfo.get('features.security.showLinks');
function deregisterSecurity() {
management.deregister('security');
}
function ensureSecurityRegistered() {
const registerSecurity = () => management.register('security', {
display: 'Security',
order: 10
});
const getSecurity = () => management.getSection('security');
const security = (management.hasItem('security')) ? getSecurity() : registerSecurity();
if (!security.hasItem('users')) {
security.register('users', {
name: 'securityUsersLink',
order: 10,
display: 'Users',
url: `#${USERS_PATH}`,
});
}
if (!security.hasItem('roles')) {
security.register('roles', {
name: 'securityRolesLink',
order: 20,
display: 'Roles',
url: `#${ROLES_PATH}`,
});
}
}
deregisterSecurity();
if (!showSecurityLinks) return;
// getCurrent will reject if there is no authenticated user, so we prevent them from seeing the security
// management screens
//
// $promise is used here because the result is an ngResource, not a promise itself
return ShieldUser.getCurrent().$promise
.then(ensureSecurityRegistered)
.catch(deregisterSecurity);
}
}
});
// ===== END =====
// ===== BEGIN javascript =====
/*! DataTables 1.10.16
* ©2008-2017 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary DataTables
* @description Paginate, search and order HTML tables
* @version 1.10.16
* @file jquery.dataTables.js
* @author SpryMedia Ltd
* @contact www.datatables.net
* @copyright Copyright 2008-2017 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/*jslint evil: true, undef: true, browser: true */
/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
(function( factory ) {
"use strict";
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
// CommonJS environments without a window global must pass a
// root. This will give an error otherwise
root = window;
}
if ( ! $ ) {
$ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
require('jquery') :
require('jquery')( root );
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}
(function( $, window, document, undefined ) {
"use strict";
/**
* DataTables is a plug-in for the jQuery Javascript library. It is a highly
* flexible tool, based upon the foundations of progressive enhancement,
* which will add advanced interaction controls to any HTML table. For a
* full list of features please refer to
* [DataTables.net](href="http://datatables.net).
*
* Note that the `DataTable` object is not a global variable but is aliased
* to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
* be accessed.
*
* @class
* @param {object} [init={}] Configuration object for DataTables. Options
* are defined by {@link DataTable.defaults}
* @requires jQuery 1.7+
*
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').dataTable();
* } );
*
* @example
* // Initialisation with configuration options - in this case, disable
* // pagination and sorting.
* $(document).ready( function {
* $('#example').dataTable( {
* "paginate": false,
* "sort": false
* } );
* } );
*/
var DataTable = function ( options )
{
/**
* Perform a jQuery selector action on the table's TR elements (from the tbody) and
* return the resulting jQuery object.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
* criterion ("applied") or all TR elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {object} jQuery object, filtered by the given selector.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Highlight every second row
* oTable.$('tr:odd').css('backgroundColor', 'blue');
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to rows with 'Webkit' in them, add a background colour and then
* // remove the filter, thus highlighting the 'Webkit' rows only.
* oTable.fnFilter('Webkit');
* oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
* oTable.fnFilter('');
* } );
*/
this.$ = function ( sSelector, oOpts )
{
return this.api(true).$( sSelector, oOpts );
};
/**
* Almost identical to $ in operation, but in this case returns the data for the matched
* rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
* rather than any descendants, so the data can be obtained for the row/cell. If matching
* rows are found, the data returned is the original data array/object that was used to
* create the row (or a generated array if from a DOM source).
*
* This method is often useful in-combination with $ where both functions are given the
* same parameters and the array indexes will match identically.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select elements that meet the current filter
* criterion ("applied") or all elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the data in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {array} Data for the matched elements. If any elements, as a result of the
* selector, were not TR, TD or TH elements in the DataTable, they will have a null
* entry in the arr
// ===== END =====
// ===== BEGIN javascript =====
import SortDescending from "./SortDescending.svelte";
export { SortDescending };
export default SortDescending;
// ===== END =====
// ===== BEGIN javascript =====
"use strict";
/*
* Copyright (c) 2019 Rafael da Silva Rocha.
*/
exports.__esModule = true;
/**
* @fileoverview TypeScript declaration tests.
* @see https://github.com/rochars/wave-resampler
*/
var index_js_1 = require("../../index.js");
var samples = index_js_1.resample([1], 1, 2);
// ===== END =====
// ===== BEGIN javascript =====
import Constants from 'expo-constants';
import { UnavailabilityError } from 'expo-errors';
import invariant from 'invariant';
import ExpoGoogleSignIn from './ExpoGoogleSignIn';
import GoogleUser from './GoogleUser';
export const { ERRORS, SCOPES, TYPES } = ExpoGoogleSignIn;
const DEFAULT_SCOPES = [SCOPES.PROFILE, SCOPES.EMAIL];
let _initialization;
let _options;
let _currentUser = null;
let _isClientUsageEnabled = false;
function setCurrentUser(currentUser) {
_currentUser = currentUser;
return _currentUser;
}
function validateOptions(options) {
if (!options) {
return {
scopes: DEFAULT_SCOPES,
};
}
if (options.isOfflineEnabled) {
invariant(typeof options.webClientId === 'string' && options.webClientId !== '', 'GoogleSignIn: Offline access (isOfflineEnabled: true) requires a valid google server id `webClientId`');
}
return {
...options,
scopes: options.scopes || DEFAULT_SCOPES,
};
}
function validateOwnership() {
invariant(_isClientUsageEnabled || Constants.appOwnership !== 'expo', 'expo-google-sign-in is not supported in the Expo Client because a custom URL scheme is required at build time. Please refer to the docs for usage outside of Expo www.npmjs.com/package/expo-google-sign-in');
}
async function ensureGoogleIsInitializedAsync(options) {
if (_initialization == null) {
return initAsync(options);
}
return _initialization;
}
async function invokeAuthMethod(method) {
if (!ExpoGoogleSignIn[method]) {
throw new UnavailabilityError('GoogleSignIn', method);
}
await ensureGoogleIsInitializedAsync();
const payload = await ExpoGoogleSignIn[method]();
let account = payload != null ? new GoogleUser(payload) : null;
return setCurrentUser(account);
}
export function allowInClient() {
_isClientUsageEnabled = true;
}
export function getCurrentUser() {
return _currentUser;
}
export async function askForPlayServicesAsync() {
return await getPlayServiceAvailability(true);
}
export async function getPlayServiceAvailability(shouldAsk = false) {
validateOwnership();
if (ExpoGoogleSignIn.arePlayServicesAvailableAsync) {
return await ExpoGoogleSignIn.arePlayServicesAvailableAsync(shouldAsk);
}
else {
return true;
}
}
export async function initAsync(options) {
if (!ExpoGoogleSignIn.initAsync) {
throw new UnavailabilityError('GoogleSignIn', 'initAsync');
}
_options = validateOptions(options || _options || {});
const hasPlayServices = await getPlayServiceAvailability();
if (!hasPlayServices) {
return;
}
_initialization = ExpoGoogleSignIn.initAsync(_options || {});
return _initialization;
}
export async function isSignedInAsync() {
const user = await getCurrentUserAsync();
return user != null;
}
export async function isConnectedAsync() {
return await ExpoGoogleSignIn.isConnectedAsync();
}
export async function signInSilentlyAsync() {
const isConnected = await isConnectedAsync();
if (isConnected) {
try {
const auth = await invokeAuthMethod('signInSilentlyAsync');
return auth;
}
catch (error) {
/* Return null to create parity with Android */
if (error.code === ERRORS.SIGN_IN_REQUIRED) {
return null;
}
throw error;
}
}
return null;
}
export async function signInAsync() {
try {
const user = await invokeAuthMethod('signInAsync');
return { type: 'success', user };
}
catch (error) {
if (error.code === ERRORS.SIGN_IN_CANCELLED) {
return { type: 'cancel', user: null };
}
throw error;
}
}
export async function signOutAsync() {
await invokeAuthMethod('signOutAsync');
}
export async function disconnectAsync() {
await invokeAuthMethod('disconnectAsync');
}
export async function getCurrentUserAsync() {
return await invokeAuthMethod('getCurrentUserAsync');
}
export async function getPhotoAsync(size = 128) {
if (!ExpoGoogleSignIn.getPhotoAsync) {
throw new UnavailabilityError('GoogleSignIn', 'getPhotoAsync');
}
await ensureGoogleIsInitializedAsync();
return await ExpoGoogleSignIn.getPhotoAsync(size);
}
export { default as GoogleAuthData } from './GoogleAuthData';
export { default as GoogleAuthentication } from './GoogleAuthentication';
export { default as GoogleIdentity } from './GoogleIdentity';
export { default as GoogleUser } from './GoogleUser';
//# sourceMappingURL=GoogleSignIn.js.map
// ===== END =====
// ===== BEGIN javascript =====
import Boom from '@hapi/boom';
import { uuid } from 'uuidv4';
import { knex } from '../db';
import Pokemon from '../models/pokemon';
import Purchase from '../models/purchase';
import PurchaseRecord from '../models/purchase_record';
import Inventory from '../models/inventory';
import Sold from '../models/sold';
import SoldRecord from '../models/sold_record';
/**
* CreatePokemon.
*
* @param {*} newPokemon
* @returns
*/
export function createPokemon(newPokemon) {
return knex
.select('pokemons.name')
.from('pokemons')
.where({ name: newPokemon.name })
.then(function (pokemon) {
if (pokemon.length === 0) {
return knex.transaction(function (t) {
const pokemonId = uuid();
return knex('pokemons')
.transacting(t)
.insert({ ...newPokemon, id: pokemonId })
.then(function () {
return knex('inventories').transacting(t).insert({
id: uuid(),
count: 0,
total_price: 0,
pokemon_id: pokemonId
});
})
.then(t.commit)
.catch(t.rollback);
});
}
throw Boom.notFound('User not found');
});
}
/**
* CreatePurchaseRecord.
*
* @param {*} newPurchaseRecord
* @returns
*/
export async function createPurchaseRecord(newPurchaseRecord) {
const purchase = await new Purchase(newPurchaseRecord.purchase).save();
const purchaseRecords = newPurchaseRecord.purchaseRecords.map((record) => {
const total_price = record.price * record.count;
const pokemon_id = record.pokemon.id;
delete record.price;
delete record.pokemon;
const newRecord = {
...record,
purchase_id: purchase.id,
total_price,
pokemon_id,
date: newPurchaseRecord.purchase.date
};
return new PurchaseRecord(newRecord).save();
});
const newPurchaseRecords = await Promise.all(purchaseRecords);
/* eslint-disable no-await-in-loop */
for (const record of newPurchaseRecords) {
const inventory = await Inventory.where({ pokemon_id: record.attributes.pokemon_id }).fetch({ require: true });
const newCount = parseInt(record.attributes.count) + parseInt(inventory.attributes.count);
const newTotalPrice = parseInt(record.attributes.total_price) + parseInt(inventory.attributes.total_price);
const newInventoryParams = {
count: newCount,
total_price: newTotalPrice,
updated_at: new Date()
};
await new Inventory({ id: inventory.id }).save(newInventoryParams);
}
return {
purchase,
purchaseRecords: newPurchaseRecords
};
}
/**
* CreateSoldRecord.
*
* @param {*} newSoldRecord
* @returns
*/
export async function createSoldRecord(newSoldRecord) {
const data = await knex.transaction(async function (t) {
const createdSold = await knex('solds')
.transacting(t)
.insert({ ...newSoldRecord.sold, id: uuid() })
.returning(['id'])
.then(async (sold) => {
const soldRecords = newSoldRecord.soldRecords.map((record) => {
const total_price = record.price * record.count;
delete record.price;
const pokemon_id = record.pokemon.id;
delete record.pokemon;
return {
...record,
sold_id: sold[0].id,
total_price,
date: newSoldRecord.sold.date,
pokemon_id,
id: uuid()
};
});
const createRecords = await knex('sold_records')
.transacting(t)
.insert(soldRecords)
.returning(['id', 'pokemon_id', 'count', 'total_price']);
return {
sold,
records: createRecords
};
});
/* eslint-disable no-await-in-loop */
for (const record of createdSold.records) {
const inventory = await knex('inventories').where({ pokemon_id: record.pokemon_id }).first();
const newCount = parseInt(inventory.count) - parseInt(record.count);
if (newCount < 0) throw Boom.badRequest('Error Counts');
const newTotalPrice = parseInt(inventory.total_price) - parseInt(record.total_price);
const newInventoryParams = {
id: uuid(),
count: newCount,
total_price: newTotalPrice,
updated_at: new Date()
};
await knex('inventories').transacting(t).where({ id: inventory.id }).update(newInventoryParams);
}
return createdSold;
});
return data;
}
/**
* QueryPurchaseRecords.
*
* @returns
*/
export async function queryPurchaseRecords() {
const data = await knex('purchases')
.select([
knex.ref('purchase_records.id').as('purchase_record_id'),
knex.ref('purchases.name').as('purchase_name'),
knex.ref('purchases.status').as('purchase_status'),
'purchases.purchaser',
'purchases.date',
'purchases.split',
'purchase_records.purchase_id',
'purchase_records.count',
'purchase_records.total_price',
'purchase_records.pokemon_id',
knex.ref('pokemons.name').as('pokemon_name')
])
.join('purchase_records', function () {
this.on('purchases.id', '=', 'purchase_records.purchase_id');
this.andOnVal('purchases.status', '=', 'active');
})
.join('pokemons', 'purchase_records.pokemon_id', '=', 'pokemons.id');
const tempData = {};
for (const item of data) {
if (!tempData[item.purchase_id]) {
tempData[item.purchase_id] = {
purchase: {
id: item.purchase_id,
name: item.purchase_name,
purchaser: item.purchaser,
date: item.date,
total_price: 0,
split: item.split
},
purchase_records: []
};
}
tempData[item.purchase_id].purchase_records.push({
record: {
id: item.purchase_record_id,
count: item.count,
total_price: item.total_price
},
pokemon: {
id: item.pokemon_id,
name: item.pokemon_name
}
});
tempData[item.purchase_id].purchase.total_price += item.total_price;
}
return Object.values(tempData).map((item) => item);
}
/**
* QueryInventories.
*
* @returns
*/
export async function queryInventories(params) {
if (params.name) {
let query = knex('pokemons');
query = query.where('name', 'like', `%${params.name}%`);
const pokemons = await query.select();
const inventoryPromises = pokemons.map(async (pokemon) => {
return await knex('inventories')
.where({ pokemon_id: pokemon.id })
.then((inventories) => {
return {
...inventories[0],
pokemon
};
});
});
return await Promise.all(inventoryPromises);
} else {
return new Inventory().fetchAll({ withRelated: ['pokemon'] }).then((inventories) => inventories);
}
}
/**
* QuerySoldRecords.
*
* @returns
*/
export async function querySoldRecords() {
const data = await knex('solds')
.select([
knex.ref('sold_records.id').as('sold_record_id'),
knex.ref('solds.name').as('sold_name'),
'solds.date',
'solds.payee',
'solds.split',
'solds.sales_channel',
'sold_records.sold_id',
'sold_records.count',
'sold_records.total_price',
'sold_records.pokemon_id',
knex.ref('pokemons.name').as('pokemon_name')
])
.join('sold_records', function () {
this.on('solds.id', '=', 'sold_records.sold_id');
this.andOnVal('solds.status', '=', 'active');
})
.join('pokemons', 'sold_records.pokemon_id', '=', 'pokemons.id');
const tempData = {};
for (const item of data) {
if (!tempData[item.sold_id]) {
tempData[item.sold_id] = {
sold: {
id: item.sold_id,
name: item.sold_name,
date: item.date,
total_price: 0,
payee: item.payee,
salesChannel: item.sales_channel,
split: item.split
},
sold_records: []
};
}
tempData[item.sold_id].
// ===== END =====
// ===== BEGIN javascript =====
var path = require('path');
var fs = require('fs');
// 返回该目录下所有文件的绝对路径(包括子目录)
function readdir(dir, opts) {
if ( opts === void 0 ) opts={};
var files = fs.readdirSync(dir);
var p = normalizePattern(opts.pattern);
var returnFiles = [];
for (var i = 0; i < files.length; i++) {
var absfile = path.join(dir, files[i]);
if (!p(absfile)) { continue; }
var isdir = fs.lstatSync(absfile).isDirectory();
returnFiles = returnFiles.concat(isdir ? readdir(absfile, opts) : absfile);
}
return returnFiles;
};
function normalizePattern(fn) {
if (!fn) { return function () { return true; }; }
if (fn && fn.test) { return function (x) { return fn.test(x); }; }
return fn;
}
module.exports = readdir;
// ===== END =====
// ===== BEGIN javascript =====
import React from 'react';
import ReactDOM from 'react-dom';
// import App from './components/App';
import Routes from './Routes';
import './index.css';
ReactDOM.render(<Routes />, document.getElementById('root'));
// ===== END =====
// ===== BEGIN javascript =====
function arePasswordsEqual(original, newPassword) {
if (original == newPassword) {
return true;
}
else {
return false;
}
}
// ===== END =====
// ===== BEGIN javascript =====
import 'whatwg-fetch';
export function getUsers(){
return get('users');
}
function get(url){
return fetch(url).then(onSuccess,onError);
}
function onSuccess(response){
response.json();
}
function onError(error){
console.log(error); //eslint-disable-line no-console
}
// ===== END =====
// ===== BEGIN javascript =====
require('dotenv').config();
const SETTINGS = process.env;
const {Client, Collection, MessageEmbed} = require('discord.js')
const { join } = require("path");
const { readdirSync } = require("fs");
/**
* Client Events
*/
const client = new Client();
client.login(SETTINGS.DISCORD_BOT_TOKEN);
client.commands = new Collection();
client.prefix = SETTINGS.prefix;
const cooldowns = new Collection();
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
client.on("ready", () => {
console.log(`${client.user.username} ready!`);
client.user.setActivity(`${SETTINGS.prefix}help`, { type: "LISTENING" });
});
client.on("warn", (info) => console.log(info));
client.on("error", console.error);
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(SETTINGS.prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if ((SETTINGS.channelRestricted === "true") && (message.channel.id !== SETTINGS.statChannel)) {
let wrongChannelEmbed = new MessageEmbed()
.setTitle(`Ooops! Wrong Channel`)
.setDescription(`**You can only search a player up at <#${SETTINGS.statChannel}>.**`)
.setColor("#ff0300")
.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio')
.setThumbnail("https://i.imgur.com/fqymYyZ.png");
wrongChannelEmbed.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio')
wrongChannelEmbed.setTimestamp();
wrongChannelEmbed.setFooter(SETTINGS.author, SETTINGS.footerImg);
message.channel.send(wrongChannelEmbed)
.then(msg => { msg.delete({timeout: 5000})})
.then(message.delete({timeout: 1000}))
.catch(console.error);
return;
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const cdtimestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 1) * 1000;
if (cdtimestamps.has(message.author.id)) {
const expirationTime = cdtimestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
let wrongSyntaxEmbed = new MessageEmbed()
.setTitle(`Ooops! You are too fast!`)
.setDescription(`**Usage of this command is protected with a cooldown.**`)
.setColor("#ff0300")
.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio')
.setThumbnail("https://i.imgur.com/fqymYyZ.png");
wrongSyntaxEmbed.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio')
wrongSyntaxEmbed.addField(`Try after`,`\`${timeLeft.toFixed(1)}second(s)\``);
wrongSyntaxEmbed.setTimestamp();
wrongSyntaxEmbed.setFooter(SETTINGS.author, SETTINGS.footerImg);
message.channel.send(wrongSyntaxEmbed)
.then(msg => { msg.delete({timeout: 5000})})
.then(message.delete({timeout: 5000}))
.catch(console.error);
return;
}
}
//${timeLeft.toFixed(1)}
cdtimestamps.set(message.author.id, now);
setTimeout(() => cdtimestamps.delete(message.author.id), cooldownAmount);
try {
await command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("Oops something went wrong... How about try that again?").catch(console.error);
}
});
/*
* Importing all the commands
*/
const commandList = readdirSync(join(__dirname, "comms")).filter((file) => file.endsWith(".js"));
for (const file of commandList) {
const command = require(join(__dirname, "comms", `${file}`));
client.commands.set(command.name, command);
}
// ===== END =====
// ===== BEGIN javascript =====
import React, { Component } from 'react';
import styles from './App.css';
import MainContainer from './containers/MainContainer';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
class App extends Component {
render() {
return (
<div className={styles.container}>
<Header />
<MainContainer />
<Footer className="master branch" />
</div>
);
}
}
const a = 12;
let b = 'String';
const c = 'Super test';
export default App;
// ===== END =====
// ===== BEGIN javascript =====
polyline = {
"vertices" : {
[0,0,0],
[0,100,0],
[100,100,0],
[100,0,0]
},
"numberFloors": "none",
"buildingType": "office"
}
// ===== END =====
// ===== BEGIN javascript =====
/**
* Created by Kelvin on 6/28/2016.
*/
'use strict';
describe('Controller: RSVPCtrl', function () {
// load the controller's module
beforeEach(module('tiffanyAndKelvin'));
beforeEach(module('templates'));
var RSVPCtrl,
scope,
rootScope,
deferred;
var rsvpData = {
data: {}
};
beforeEach(module(function($provide) {
$provide.factory('GoogleCalendar', function($q) {
//calendarInitDefer = $q.defer();
return {
initialized: $q.resolve(),
setCalendarEvent: function() {return $q.resolve();}
}
});
}));
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $q) {
rootScope = $rootScope;
scope = $rootScope.$new();
deferred = $q.defer();
var promise = deferred.promise;
rsvpData.save = function(formModel) {
return promise;
};
rsvpData.pepe = 'test';
RSVPCtrl = $controller('RSVPCtrl', {
rsvpData: rsvpData
});
spyOn(rsvpData, 'save').and.callThrough();
spyOn($.fn, 'removeClass');
}));
it('should initialize isSaving to false', function() {
expect(RSVPCtrl.isSaving).toBe(false);
});
it('should initialize showCloseButton to true', function() {
expect(RSVPCtrl.showCloseButton).toBe(true);
});
it('should initialize form to an empty object', function() {
var expected = {};
expect(RSVPCtrl.form).toEqual(expected);
});
it('should set formModel to be rsvpData.data', function() {
expect(RSVPCtrl.formModel).toEqual(rsvpData.data);
});
it('should return whether a given property on form is dirty and invalid', function() {
var element = 'foo';
var idx = 'bar';
RSVPCtrl.form.foobar = {
$dirty: true,
$invalid: false
};
var expected = false;
var actual = RSVPCtrl.showErrors(element, idx);
expect(actual).toBe(expected);
});
it('should initialize calendarEventAdded to false', function() {
expect(RSVPCtrl.calendarEventAdded).toBe(false);
});
it('should set calendarEventAdded to true if setCalendarEvent resolves', function() {
RSVPCtrl.authCalendar();
scope.$apply();
expect(RSVPCtrl.calendarEventAdded).toBe(true);
});
describe('closeToast', function() {
it('should set showCloseButton to true when called', function() {
RSVPCtrl.showCloseButton = false;
RSVPCtrl.closeToast();
expect(RSVPCtrl.showCloseButton).toBe(true);
});
it('should call removeClass with show-up', function() {
RSVPCtrl.closeToast('success');
expect($.fn.removeClass).toHaveBeenCalledWith('show-up');
});
});
describe('submit', function() {
var formModel = {
code: 'foo'
};
var mockForm = {
$setPristine: function() {}
};
beforeEach(function() {
RSVPCtrl.form = mockForm;
RSVPCtrl.submit(formModel);
spyOn($.fn, 'addClass');
spyOn(mockForm, '$setPristine');
});
it('should call save on rsvpData', function() {
expect(rsvpData.save).toHaveBeenCalledWith(formModel);
});
it('should set showThankYou to be true when successful', function() {
deferred.resolve();
scope.$apply();
expect(RSVPCtrl.showThankYou).toBe(true);
});
it('should set atLeastOneGoing to false if not at least one person is going', function() {
deferred.resolve();
scope.$apply();
expect(RSVPCtrl.atLeastOneGoing).toBe(false);
});
it('should set atLeastOneGoing to true if not at least one person is going', function() {
deferred.resolve();
scope.$apply();
formModel = {
"A0": {
"firstName": "Darbie",
"going": "0",
"lastName": "Grant",
"plusOne": false,
"plusOneDependent": false
},
"B1": {
"firstName": "Dave",
"going": "1",
"lastName": "Grant",
"plusOne": false,
"plusOneDependent": false
},
"C2": {
"firstName": "Natalie",
"going": "0",
"lastName": "Grant",
"plusOne": false,
"plusOneDependent": false
},
"responded": false
};
RSVPCtrl.submit(formModel);
deferred.resolve();
scope.$apply();
expect(RSVPCtrl.atLeastOneGoing).toBe(true);
});
it('should set the from to pristine when successful', function() {
deferred.resolve();
scope.$apply();
expect(mockForm.$setPristine).toHaveBeenCalled();
});
it('should call add class with show-up when not successful', function() {
deferred.reject();
scope.$apply();
expect($.fn.addClass).toHaveBeenCalledWith('show-up');
});
it('should set showCloseButton false when not successful', function() {
deferred.reject();
scope.$apply();
expect(RSVPCtrl.showCloseButton).toBe(false);
});
it('should set isSaving to true', function() {
expect(RSVPCtrl.isSaving).toBe(true);
});
it('should set isSaving to false when the promise finishes', function() {
deferred.reject();
scope.$apply();
expect(RSVPCtrl.isSaving).toBe(false);
});
});
describe('goingChanged', function() {
it('should not modify mainNotGoin person.plusOneDependent is false', function() {
var expected = false;
RSVPCtrl.mainNotGoing = expected;
RSVPCtrl.goingChanged({plusOneDependent: false});
expect(RSVPCtrl.mainNotGoing).toBe(expected);
});
it('should set mainNotGoing to person.going "0" === false or "1" === true', function () {
var expected = true;
var person = {
plusOneDependent: true,
going: '0'
};
RSVPCtrl.goingChanged(person);
expect(RSVPCtrl.mainNotGoing).toBe(true);
});
});
});
// ===== END =====
// ===== BEGIN javascript =====
/** When your routing table is too long, you can split it into small modules **/
import Layout from '@/layout'
const componentsRouter = {
path: '/components',
component: Layout,
redirect: 'noRedirect',
name: 'ComponentDemo',
meta: {
title: '组件',
icon: 'component'
},
children: [
{
path: 'tinymce',
component: () => import('@/views/components-demo/tinymce'),
name: 'TinymceDemo',
meta: { title: '富文本编辑器' }
},
{
path: 'markdown',
component: () => import('@/views/components-demo/markdown'),
name: 'MarkdownDemo',
meta: { title: 'Markdown' }
},
{
path: 'json-editor',
component: () => import('@/views/components-demo/json-editor'),
name: 'JsonEditorDemo',
meta: { title: 'JSON 编辑器' }
},
{
path: 'split-pane',
component: () => import('@/views/components-demo/split-pane'),
name: 'SplitpaneDemo',
meta: { title: 'SplitPane' }
},
{
path: 'avatar-upload',
component: () => import('@/views/components-demo/avatar-upload'),
name: 'AvatarUploadDemo',
meta: { title: '头像上传' }
},
{
path: 'dropzone',
component: () => import('@/views/components-demo/dropzone'),
name: 'DropzoneDemo',
meta: { title: 'Dropzone' }
},
{
path: 'sticky',
component: () => import('@/views/components-demo/sticky'),
name: 'StickyDemo',
meta: { title: 'Sticky' }
},
{
path: 'count-to',
component: () => import('@/views/components-demo/count-to'),
name: 'CountToDemo',
meta: { title: 'Count To' }
},
{
path: 'mixin',
component: () => import('@/views/components-demo/mixin'),
name: 'ComponentMixinDemo',
meta: { title: '小组件' }
},
{
path: 'back-to-top',
component: () => import('@/views/components-demo/back-to-top'),
name: 'BackToTopDemo',
meta: { title: '返回顶部' }
},
{
path: 'drag-dialog',
component: () => import('@/views/components-demo/drag-dialog'),
name: 'DragDialogDemo',
meta: { title: '拖拽 Dialog' }
},
{
path: 'drag-select',
component: () => import('@/views/components-demo/drag-select'),
name: 'DragSelectDemo',
meta: { title: '拖拽 Select' }
},
{
path: 'dnd-list',
component: () => import('@/views/components-demo/dnd-list'),
name: 'DndListDemo',
meta: { title: '列表拖拽' }
},
{
path: 'drag-kanban',
component: () => import('@/views/components-demo/drag-kanban'),
name: 'DragKanbanDemo',
meta: { title: '可拖拽看板' }
}
]
}
export default componentsRouter
// ===== END =====
// ===== BEGIN javascript =====
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.1.1
build: 47
*/
YUI.add("lang/datatype-date-format_es-US",function(A){A.Intl.add("datatype-date-format","es-US",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %l:%M:%S %p %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%m/%d/%y","X":"%l:%M:%S %p"});},"3.1.1");YUI.add("lang/datatype-date_es-US",function(A){},"3.1.1",{use:["lang/datatype-date-format_es-US"]});
// ===== END =====
// ===== BEGIN javascript =====
module.exports = {
name: 'lmbase-collection',
preset: '../../jest.config.js',
coverageDirectory: '../../coverage/libs/lmbase-collection',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
],
};
// ===== END =====
// ===== BEGIN javascript =====
(window.webpackJsonp=window.webpackJsonp||[]).push([[60],{409:function(s,e,t){"use strict";t.r(e);var o=t(42),a=Object(o.a)({},(function(){var s=this,e=s.$createElement,t=s._self._c||e;return t("ContentSlotsDistributor",{attrs:{"slot-key":s.$parent.slotKey}},[t("h1",{attrs:{id:"session-分布式方案"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#session-分布式方案"}},[s._v("#")]),s._v(" Session 分布式方案")]),s._v(" "),t("h2",{attrs:{id:"基于-nfs-net-filesystem-的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-nfs-net-filesystem-的-session-共享"}},[s._v("#")]),s._v(" 基于 nfs(net filesystem) 的 Session 共享")]),s._v(" "),t("p",[s._v("将共享服务器目录 mount 各服务器的本地 session 目录,session 读写受共享服务器 io 限制,"),t("strong",[s._v("不能满足高并发")]),s._v("。")]),s._v(" "),t("h2",{attrs:{id:"基于关系数据库的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于关系数据库的-session-共享"}},[s._v("#")]),s._v(" 基于关系数据库的 Session 共享")]),s._v(" "),t("p",[s._v("这种方案普遍使用。使用关系数据库存储 session 数据,对于 mysql 数据库,建议使用 heap 引擎。这种方案性能取决于数据库的性能,在高并发下容易造成表锁(虽然可以采用行锁的存储引擎,性能会下降),并且需要自己实现 session 过期淘汰机制。")]),s._v(" "),t("h2",{attrs:{id:"基于-cookie-的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-cookie-的-session-共享"}},[s._v("#")]),s._v(" 基于 Cookie 的 Session 共享")]),s._v(" "),t("p",[s._v("这种方案也在大型互联网中普遍使用,将用户的 session 加密序列化后以 cookie 的方式保存在网站根域名下(比如 taobao.com),当用户访问所有二级域名站点式,浏览器会传递所有匹配的根域名的 cookie 信息,这样实现了用户 cookie 化 session 的多服务共享。此方案能够节省大量服务器资源,缺点是存储的信息长度受到 http 协议限制;cookie 的信息还需要做加密解密;请求任何资源时都会将 cookie 附加到 http 头上传到服务器,占用了一定带宽。")]),s._v(" "),t("h2",{attrs:{id:"基于-web-容器的-session-机制"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-web-容器的-session-机制"}},[s._v("#")]),s._v(" 基于 Web 容器的 Session 机制")]),s._v(" "),t("p",[s._v("利用容器机制,通过配置即可实现。")]),s._v(" "),t("h2",{attrs:{id:"基于-zookeeper-的分布式-session-存储"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-zookeeper-的分布式-session-存储"}},[s._v("#")]),s._v(" 基于 Zookeeper 的分布式 Session 存储")]),s._v(" "),t("h2",{attrs:{id:"基于-redis-memcached-的-session-共享存储"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-redis-memcached-的-session-共享存储"}},[s._v("#")]),s._v(" 基于 Redis/Memcached 的 Session 共享存储")]),s._v(" "),t("p",[s._v("这些 key/value 非关系存储有较高的性能,轻松达到 2000 左右的 qps,内置的过期机制正好满足 session 的自动实效特性。")])])}),[],!1,null,null,null);e.default=a.exports}}]);
// ===== END =====
// ===== BEGIN javascript =====
import styled from "styled-components";
const HeaderFooterWrapper = styled.div`
max-width: 500px;
margin: 0 auto;
display: grid;
grid-template-rows: max-content auto max-content;
min-height: 100vh;
`;
const Header = styled.div`
padding: 2rem 1rem 1rem;
`;
const Page = styled.div`
padding: 1rem;
`;
const Place = styled.div`
padding: 1rem;
`;
const Footer = styled.div`
padding: 1rem;
text-align: center;
opacity: 0.3;
`;
export { HeaderFooterWrapper, Header, Page, Place, Footer };
// ===== END =====
// ===== BEGIN javascript =====
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const ExtractPlugin = require('extract-text-webpack-plugin')
const isDev = process.env.NODE_ENV === 'development'
const config = {
target: 'web',
entry: path.join(__dirname, 'src/index.js'),
output: {
filename: 'bundle.[hash:8].js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.jsx$/,
loader: 'babel-loader'
},
{
test: /\.(gif|jpg|jpeg|png|svg)$/,
use: [
{
loader: 'url-loader', // 是对file-loader的封装
options: {
limit: 1024, // 如果图片小于1024,就转化成base64位
name: '[name].[ext]'
}
}
]
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: isDev ? '"development"' : '"production"'
}
}),
new HTMLPlugin()
],
// externals: {
// 'vue': 'Vue'
// }
}
if (isDev) {
// 开发环境的css代码可以内联
config.module.rules.push({
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
sourceMap: true // stylus-loader会生成sourceMap,postcss-loader也会,加上这个选项表示用生成的sourceMap,提示编译效率
}
},
'stylus-loader'
]
})
config.devtool = '#cheap-module-eval-source-map'
// devServer 在webpack2.0后才有的
config.devServer = {
port: 8000,
// host: '127.0.0.1', // 好处: 可以在别人电脑上通过ip访问,或者手机
host: '0.0.0.0', // 好处: 可以在别人电脑上通过ip访问,或者手机
overlay: { // 编译的时候出现错误,就显示到网页上
errors: true
},
hot: true, // 热更新,只更新修改的页面,不会刷新整个页面
// open: true // 自动打开网页
}
// 热更新的相关插件
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
)
} else {
// 第三方的类库,一般比较稳定,不会和业务代码一样经常变动,所以要单独打包
config.entry = {
app: path.join(__dirname, 'src/index.js'),
vendor: ['vue']
}
// 如果是hash,那么每次打包,各个带有hash的文件,他们的hash都是相同的,
// 这样,每次生成环境打包后,vendor也是每次都变化了,每次都会重新加载,就没有单独打包的意义了
// 使用chunkhash的话,每个单独文件的hash都不同
config.output.filename = '[name].[chunkhash:8].js'
// 生产环境的css需要外联
config.module.rules.push({
test: /\.styl$/,
use: ExtractPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
'stylus-loader'
]
})
})
config.plugins.push(
new ExtractPlugin('styles.[contentHash:8].css'), // css相关插件
new webpack.optimize.CommonsChunkPlugin({ // 第三方类库打包,单独打包到vendor.js中
name: 'vendor'
}),
// FIXME: 这边还是不大明白,再看看https://www.imooc.com/video/16410
new webpack.optimize.CommonsChunkPlugin({
name: 'runtime'
})
)
}
module.exports = config
// ===== END =====
// ===== BEGIN javascript =====
// @flow
import * as React from 'react'
import { AppRegistry } from 'react-native'
import App from './modules/app/components/App'
import 'moment/min/locales'
AppRegistry.registerComponent('Integreat', () => () => <App />)
// ===== END =====
// ===== BEGIN javascript =====
/**
* Copyright (c) 2014, 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
"use strict";
/**
* Copyright (c) 2015, Oracle and/or its affiliates.
* All rights reserved.
*/
define(['ojs/ojcore', 'jquery', 'ojs/ojcomponentcore', 'promise', 'ojdnd', 'ojs/ojdomscroller', 'ojs/ojeditablevalue', 'ojs/ojmenu', 'ojs/ojdatasource-common', 'ojs/ojpagingtabledatasource', 'ojs/ojflattenedtreetabledatasource'],
function(oj, $, compCore)
{
/**
* Copyright (c) 2014, Oracle and/or its affiliates.
* All rights reserved.
*/
/**
* @preserve Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
/**
* @ojcomponent oj.ojTable
* @augments oj.baseComponent
*
* @classdesc
* The ojTable component enhances a HTML table element into one that supports all
* the features in JET Table. </p>
*
* <h3 id="touch-section">
* Touch End User Information
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#touch-section"></a>
* </h3>
*
* {@ojinclude "name":"touchDoc"}
*
* <h3 id="keyboard-section">
* Keyboard End User Information
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#keyboard-section"></a>
* </h3>
*
* {@ojinclude "name":"keyboardDoc"}
*
* <h3 id="a11y-section">
* Accessibility
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#a11y-section"></a>
* </h3>
*
* <p>Developers should always either specify the <code class="prettyprint">summary</code> attribute or <code class="prettyprint">caption</code> child tag for the table element to conform to accessibility guidelines.</p>
*
* <h3 id="styling-section">
* Styling
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#styling-section"></a>
* </h3>
*
* {@ojinclude "name":"stylingDoc"}
*
* <h3 id="perf-section">
* Performance
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#perf-section"></a>
* </h3>
*
* <h4>Data Set Size</h4>
* <p>As a rule of thumb, it's recommended that applications limit the amount of data to display. Displaying large
* number of items in Table makes it hard for users to find what they are looking for, but affects the
* rendering performance as well. If displaying large number of items is neccessary, consider use a paging control with Table
* to limit the number of items to display at a time. Also consider setting <code class="prettyprint">scrollPolicy</code> to
* 'loadMoreOnScroll' to enable infinite scrolling to reduce the number of elements in the DOM at any given time .</p>
*
* <h4>Cell Content</h4>
* <p>Table allows developers to specify arbitrary content inside its cells. In order to minimize any negative effect on
* performance, you should avoid putting a large number of heavy-weight components inside a cell because as you add more complexity
* to the structure, the effect will be multiplied because there can be many items in the Table.</p>
*
* <!-- - - - - Above this point, the tags are for the class.
* Below this point, the tags are for the constructor (initializer). - - - - - - -->
*
*
* @desc Creates a JET Table.
*
* @param {Object=} options a map of option-value pairs to set on the component
*
* @example <caption>Initialize the table via the JET <code class="prettyprint">ojComponent</code> binding:</caption>
* <table id="table" summary="Department List" aria-label="Departments Table"
* data-bind="ojComponent: {component: 'ojTable', data: datasource, columns:
* [{headerText: 'Department Id', field: 'DepartmentId'},
* {headerText: 'Department Name', field: 'DepartmentName'},
* {headerText: 'Location Id', field: 'LocationId'},
* {headerText: 'Manager Id', field: 'ManagerId'}]}">
*
* @example <caption>Initialize the table with column templates via the JET <code class="prettyprint">ojComponent</code> binding:</caption>
* <table id="table" summary="Department List" aria-label="Departments Table"
* data-bind="ojComponent: {component: 'ojTable', data: datasource, columns:
* [{headerText: 'Department Id', field: 'DepartmentId'},
* {headerText: 'Department Name', field: 'DepartmentName'},
* {headerText: 'Location Id', field: 'LocationId'},
* {headerText: 'Manager Id', field: 'ManagerId'}]},
* {headerTemplate: 'oracle_link_hdr', template: 'oracle_link'}]}">
* <script type="text/html" id="oracle_link_hdr">
* <th style="padding-left: 5px; padding-right: 5px;">
* Oracle Link
* </th>
* </script>
* <script type="text/html" id="oracle_link">
* <td>
* <a href="http://www.oracle.com">Oracle</a>
* </td>
* </script>
*
* @example <caption>Initialize the table with rowTemplate via the JET <code class="prettyprint">ojComponent</code> binding:</caption>
* <table id="table" summary="Department List" aria-label="Departments Table"
* data-bind="ojComponent: {component: 'ojTable', data: datasource, columns:
* [{headerText: 'Department Id', field: 'DepartmentId'},
* {headerText: 'Department Name', field: 'DepartmentName'},
* {headerText: 'Location Id', field: 'LocationId'},
* {headerText: 'Manager Id', field: 'ManagerId'}],
* rowTemplate: 'row_tmpl'}">
* <script type="text/html" id="row_tmpl">
* <tr>
* <td data-bind="text: DepartmentId">
* </td>
* <td data-bind="text: DepartmentName">
* </td>
* <td data-bind="text: LocationId">
* </td>
* <td data-bind="text: ManagerId">
* </td>
* </tr>
* </script>
*/
(function() {
oj.__registerWidget("oj.ojTable", $['oj']['baseComponent'],
{
version: '1.0.0',
defaultElement: '<table>',
widgetEventPrefix: 'oj',
options:
{
/**
* Accessibility options.
* <p>
* The following options are supported:
* <ul>
* <li>rowHeader: columnId</li>
* </ul>
* The td cells in the column specified by the rowHeader
* attribute will be assigned an id and then referenced by the
* headers attribute in the rest of the cells in the row.
* This is required by screenReaders. By default the first column
* will be taken as the rowHeader.
* @expose
* @public
* @instance
* @memberof! oj.ojTable
* @type {Object.<string, string>|null}
* @property {string} rowHeader the column id to be used as the row header by screen readers
* @default <code class="prettyprint">null</code>
*/
accessibility: null,
/**
* The current row the user has navigated to. Can be an index and/or key value.
* When both are specified, the index is used as a hint.
* Returns the current row or null if there is none.
* @expose
* @public
* @instance
* @memberof! oj.ojTable
* @type {Object}
* @default <code class="prettyprint">null</code>
*
* @example <caption>Get the current row:</caption>
* $( ".selector" ).ojTable("option", "currentRow");
*
* @example <caption>Set the current row on the table during initialization:</caption>
* $(".selector").ojTable({"currentRow", {rowKey: '123'}});
*
* @example <caption>Set the current row on the table during initialization:</caption>
* $(".selector").ojTable({"currentRow", {rowIndex: 1}});
*
* @example <caption>Set the current row on the table after initialization:</caption>
* $(".selector").ojTable("option", "currentRow", {rowKey: '123'});
*
* @e
// ===== END =====
// ===== BEGIN typescript =====
export * from './easyparcel/easyparcel.definition';
export * from './easyparcel/easyparcel.module';
export * from './easyparcel/easyparcel.service';
// ===== END =====
// ===== BEGIN typescript =====
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Connection from './connection.ts'
import { bookmark } from './internal/index.ts'
/**
* Inteface define a common way to acquire a connection
*
* @private
*/
class ConnectionProvider {
/**
* This method acquires a connection against the specified database.
*
* Access mode and Bookmarks only applies to routing driver. Access mode only
* differentiates the target server for the connection, where WRITE selects a
* WRITER server, whereas READ selects a READ server. Bookmarks, when specified,
* is only passed to the routing discovery procedure, for the system database to
* synchronize on creation of databases and is never used in direct drivers.
*
* @param {object} param - object parameter
* @property {string} param.accessMode - the access mode for the to-be-acquired connection
* @property {string} param.database - the target database for the to-be-acquired connection
* @property {Bookmark} param.bookmarks - the bookmarks to send to routing discovery
* @property {string} param.impersonatedUser - the impersonated user
* @property {function (databaseName:string?)} param.onDatabaseNameResolved - Callback called when the database name get resolved
*/
acquireConnection(param?: {
accessMode?: string
database?: string
bookmarks: bookmark.Bookmark,
impersonatedUser?: string,
onDatabaseNameResolved?: (databaseName?: string) => void
}): Promise<Connection> {
throw Error('Not implemented')
}
/**
* This method checks whether the backend database supports multi database functionality
* by checking protocol handshake result.
*
* @returns {Promise<boolean>}
*/
supportsMultiDb(): Promise<boolean> {
throw Error('Not implemented')
}
/**
* This method checks whether the backend database supports transaction config functionality
* by checking protocol handshake result.
*
* @returns {Promise<boolean>}
*/
supportsTransactionConfig(): Promise<boolean> {
throw Error('Not implemented')
}
/**
* This method checks whether the backend database supports transaction config functionality
* by checking protocol handshake result.
*
* @returns {Promise<boolean>}
*/
supportsUserImpersonation(): Promise<boolean> {
throw Error('Not implemented')
}
/**
* Closes this connection provider along with its internals (connections, pools, etc.)
*
* @returns {Promise<void>}
*/
close(): Promise<void> {
throw Error('Not implemented')
}
}
export default ConnectionProvider
// ===== END =====
// ===== BEGIN typescript =====
import TelegramBot = require('node-telegram-bot-api');
import { v4 as uuidv4 } from 'uuid';
import downloadUtils = require('./download_tools/utils');
import * as ariaTools from './download_tools/aria-tools';
import constants = require('./.constants');
import msgTools = require('./bot_utils/msg-tools');
import dlm = require('./dl_model/dl-manager');
import driveList = require('./drive/drive-list');
import driveUtils = require('./drive/drive-utils');
import driveDirectLink = require('./drive/drive-directLink');
import cloneFn = require('./drive/drive-clone2');
import driveDownload = require('./drive/drive-tar');
import details = require('./dl_model/detail');
import filenameUtils = require('./download_tools/filename-utils');
import { EventRegex } from './bot_utils/event_regex';
// import { exec } from 'child_process';
import checkDiskSpace = require('check-disk-space');
import gdUtils = require('./drive/gd-utils');
const telegraph = require('telegraph-node')
const ph = new telegraph();
const eventRegex = new EventRegex();
const bot = new TelegramBot(constants.TOKEN, { polling: true });
var websocketOpened = false;
var statusInterval: NodeJS.Timeout;
var dlManager = dlm.DlManager.getInstance();
initAria2();
if (constants.USE_SERVICE_ACCOUNT && !constants.IS_TEAM_DRIVE) {
console.log('In order to use Service account for clone the drive should be Team drive. Please set IS_TEAM_DRIVE to true in .constants.js');
process.exit();
}
bot.on("polling_error", msg => console.error(msg.message));
function setEventCallback(regexp: RegExp, regexpNoName: RegExp,
callback: ((msg: TelegramBot.Message, match?: RegExpExecArray) => void)): void {
bot.onText(regexpNoName, (msg, match) => {
// Return if the command didn't have the bot name for non PMs ("Bot name" could be blank depending on config)
if (msg.chat.type !== 'private' && !match[0].match(regexp))
return;
callback(msg, match);
});
}
setEventCallback(eventRegex.commandsRegex.start, eventRegex.commandsRegexNoName.start, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
msgTools.sendMessage(bot, msg, 'You should know the commands already. Happy mirroring.', -1);
}
});
setEventCallback(eventRegex.commandsRegex.id, eventRegex.commandsRegexNoName.id, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
msgTools.sendMessage(bot, msg, "This chat's id is: <code>" + msg.chat.id + "</code>", 60000);
}
});
setEventCallback(eventRegex.commandsRegex.mirrorTar, eventRegex.commandsRegexNoName.mirrorTar, async (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
try {
mirror(msg, await checkIfTorrentFile(msg, match), true);
} catch (error) {
console.log("Error in mirror: ", error.message);
msgTools.sendMessage(bot, msg, error.message, 60000);
}
}
});
setEventCallback(eventRegex.commandsRegex.mirror, eventRegex.commandsRegexNoName.mirror, async (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
try {
mirror(msg, await checkIfTorrentFile(msg, match));
} catch (error) {
console.log("Error in mirror: ", error.message);
msgTools.sendMessage(bot, msg, error.message, 60000);
}
}
});
async function checkIfTorrentFile(msg: TelegramBot.Message, match: RegExpExecArray) {
if (msg.hasOwnProperty("reply_to_message") && msg.reply_to_message.hasOwnProperty("document") && msg.reply_to_message.document.hasOwnProperty("file_id")) {
if (msg.reply_to_message.document.mime_type === 'application/x-bittorrent') {
match[4] = await bot.getFileLink(msg.reply_to_message.document.file_id);
} else {
throw new Error('Reply to a torrent file only for mirroring.');
}
}
return match;
}
setEventCallback(eventRegex.commandsRegex.disk, eventRegex.commandsRegexNoName.disk, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
// exec(`df --output="size,used,avail" -h "${constants.ARIA_DOWNLOAD_LOCATION_ROOT}" | tail -n1`,
// (err, res) => {
// var disk = res.trim().split(/\s+/);
// msgTools.sendMessage(bot, msg, `Total space: ${disk[0]}B\nUsed: ${disk[1]}B\nAvailable: ${disk[2]}B`);
// }
// );
checkDiskSpace(constants.ARIA_DOWNLOAD_LOCATION_ROOT).then(res => {
let used = res.size - res.free;
msgTools.sendMessage(bot, msg, `Total space: ${downloadUtils.formatSize(res.size)}\nUsed: ${downloadUtils.formatSize(used)}\nAvailable: ${downloadUtils.formatSize(res.free)}`);
}).catch(error => {
console.log('checkDiskSpace: ', error.message);
msgTools.sendMessage(bot, msg, `Error checking disk space: ${error.message}`);
});
}
});
setEventCallback(eventRegex.commandsRegex.mf, eventRegex.commandsRegexNoName.mf, (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
if (msg.hasOwnProperty("reply_to_message") && msg.reply_to_message.hasOwnProperty("document") && msg.reply_to_message.document.hasOwnProperty("file_id")) {
bot.getFileLink(msg.reply_to_message.document.file_id).then((res) => {
match.splice(2, 0, '69');// insert some fake values so that index matches in mirror fucntions
match.splice(3, 0, '69');
match.splice(4, 0, res);
mirror(msg, match);
}).catch(err => {
console.log("couldn't get file link: ", err.message);
msgTools.sendMessage(bot, msg, err.message, 60000);
});
} else {
msgTools.sendMessage(bot, msg, 'Failed to start download. Reply to a torrent file.', 60000);
}
}
});
setEventCallback(eventRegex.commandsRegex.unzipMirror, eventRegex.commandsRegexNoName.unzipMirror, (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
mirror(msg, match, false, true);
}
});
/**
* Start a new download operation. Make sure that this is triggered by an
* authorized user, because this function itself does not check for that.
* @param {Object} msg The Message that triggered the download
* @param {Array} match Message matches
* @param {boolean} isTar Decides if this download should be archived before upload
* @param {boolean} isUnZip Decides if this download should be extracted before upload
*/
function mirror(msg: TelegramBot.Message, match: RegExpExecArray, isTar?: boolean, isUnZip?: boolean): void {
if (match.length < 5 || !match[4]) return;
if (websocketOpened) {
match[4] = match[4].trim();
if (downloadUtils.isDownloadAllowed(match[4])) {
prepDownload(msg, match[4], isTar, isUnZip);
} else {
msgTools.sendMessage(bot, msg, `Download failed. Blacklisted URL.`);
}
} else {
msgTools.sendMessage(bot, msg, `Websocket isn't open. Can't download`);
}
}
setEventCallback(eventRegex.commandsRegex.mirrorStatus, eventRegex.commandsRegexNoName.mirrorStatus, (msg) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
sendStatusMessage(msg);
}
});
setEventCallback(eventRegex.commandsRegex.list, eventRegex.commandsRegexNoName.list, async (msg, match) => {
if (msgTools.isAuthorized(msg) < 0) {
msgTools.sendUnauthorizedMessage(bot, msg);
} else {
const searchingMsg = await bot.sendMessage(msg.chat.id, `🔍Searching for files.... Please wait.`, {
reply_to_message_id: msg.message_id,
parse_mode: 'HTML'
});
driveList.listFiles(match[4], async (err, res) => {
msgTools.deleteMsg(bot, searchingMsg);
if (err) {
msgTools.sendMessage(bot, msg, 'Failed to fetch the list of files');
} else {
if (constants.TELEGRAPH_TOKEN) {
try {
if (res.length === 0) {
msgTools.sendMessage(bot, msg, 'T
// ===== END =====
// ===== BEGIN typescript =====
export * as path from "https://deno.land/[email protected]/path/mod.ts";
export {
compile,
preprocess,
} from "https://deno.land/x/[email protected]/compiler/core.js";
export type {
compileOptions,
PreprocessorGroup,
} from "https://deno.land/x/[email protected]/compiler/types.ts";
// ===== END =====
// ===== BEGIN typescript =====
/**
* The `ComposerBody` component handles the body, or the content, of the
* composer. Subclasses should implement the `onsubmit` method and override
* `headerTimes`.
*
* ### Attrs
*
* - `composer`
* - `originalContent`
* - `submitLabel`
* - `placeholder`
* - `user`
* - `confirmExit`
* - `disabled`
*
* @abstract
*/
export default class ComposerBody extends Component<import("../../common/Component").ComponentAttrs> {
constructor();
composer: any;
/**
* Whether or not the component is loading.
*
* @type {Boolean}
*/
loading: boolean | undefined;
/**
* Check if there is any unsaved data.
*
* @return {String}
*/
hasChanges(): string;
/**
* Build an item list for the composer's header.
*
* @return {ItemList}
*/
headerItems(): ItemList;
/**
* Handle the submit event of the text editor.
*
* @abstract
*/
onsubmit(): void;
/**
* Stop loading.
*/
loaded(): void;
}
import Component from "../../common/Component";
import ItemList from "../../common/utils/ItemList";
// ===== END =====
// ===== BEGIN typescript =====
import * as oak from "https://deno.land/x/oak/mod.ts";
import * as sqlite from "https://deno.land/x/sqlite/mod.ts";
export {
oak,
sqlite
}
// ===== END =====
// ===== BEGIN typescript =====
// Needed to make @types/puppeteer pass type checking
// See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/24419
interface Element {}
// ===== END =====
// ===== BEGIN typescript =====
/* Dotenv */
import "https://deno.land/x/dotenv/load.ts";
/* Telegram */
export { Bot } from "https://deno.land/x/[email protected]/mod.ts";
// ===== END =====
// ===== BEGIN typescript =====
import React from "react";
import { TestWrapper } from "../test-utils";
import { UploadButton } from ".";
import { cleanup, fireEvent, render } from "@testing-library/react";
afterEach(cleanup);
test("render upload button with default text", async () => {
const testId = "upload-button";
const mockOnChange = jest.fn((result) => result);
const { container, getByTestId } = render(
<TestWrapper>
<UploadButton
buttonProps={
{
variant: "contained",
color: "primary",
"data-testid": testId,
} as unknown
}
onChange={mockOnChange}
/>
</TestWrapper>,
);
expect(getByTestId(testId)).toHaveTextContent("Upload File");
expect(getByTestId(testId)).not.toHaveTextContent("Upload File(s)");
fireEvent.change(getByTestId("upload-button-input-field"));
expect(mockOnChange).toHaveBeenCalled();
// TODO(nsawas): Figure out how to test return result of Filelist {}.
const valueType = typeof mockOnChange.mock.results[0].value;
expect(valueType).toEqual("object");
expect(container).toMatchSnapshot();
});
test("render upload button with default text and default props for uploading multiple files", async () => {
const testId = "upload-button";
const { container, getByTestId } = render(
<TestWrapper>
<UploadButton
allowMultiple
buttonProps={
{
variant: "contained",
color: "primary",
"data-testid": testId,
} as unknown
}
onChange={() => {}}
/>
<UploadButton allowMultiple onChange={() => {}} />
</TestWrapper>,
);
expect(getByTestId(testId)).toHaveTextContent("Upload File(s)");
expect(container).toMatchSnapshot();
});
// ===== END =====
// ===== BEGIN typescript =====
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { get } from 'lodash';
import { SavedObjectsServiceStart, Logger } from 'src/core/server';
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { getSavedObjectAttributesFromRepo } from '../lib/telemetry';
interface ITelemetry {
ui_viewed: {
setup_guide: number;
engines_overview: number;
};
ui_error: {
cannot_connect: number;
};
ui_clicked: {
create_first_engine_button: number;
header_launch_button: number;
engine_table_link: number;
};
}
export const AS_TELEMETRY_NAME = 'app_search_telemetry';
/**
* Register the telemetry collector
*/
export const registerTelemetryUsageCollector = (
usageCollection: UsageCollectionSetup,
savedObjects: SavedObjectsServiceStart,
log: Logger
) => {
const telemetryUsageCollector = usageCollection.makeUsageCollector<ITelemetry>({
type: 'app_search',
fetch: async () => fetchTelemetryMetrics(savedObjects, log),
isReady: () => true,
schema: {
ui_viewed: {
setup_guide: { type: 'long' },
engines_overview: { type: 'long' },
},
ui_error: {
cannot_connect: { type: 'long' },
},
ui_clicked: {
create_first_engine_button: { type: 'long' },
header_launch_button: { type: 'long' },
engine_table_link: { type: 'long' },
},
},
});
usageCollection.registerCollector(telemetryUsageCollector);
};
/**
* Fetch the aggregated telemetry metrics from our saved objects
*/
const fetchTelemetryMetrics = async (savedObjects: SavedObjectsServiceStart, log: Logger) => {
const savedObjectsRepository = savedObjects.createInternalRepository();
const savedObjectAttributes = await getSavedObjectAttributesFromRepo(
AS_TELEMETRY_NAME,
savedObjectsRepository,
log
);
const defaultTelemetrySavedObject: ITelemetry = {
ui_viewed: {
setup_guide: 0,
engines_overview: 0,
},
ui_error: {
cannot_connect: 0,
},
ui_clicked: {
create_first_engine_button: 0,
header_launch_button: 0,
engine_table_link: 0,
},
};
// If we don't have an existing/saved telemetry object, return the default
if (!savedObjectAttributes) {
return defaultTelemetrySavedObject;
}
return {
ui_viewed: {
setup_guide: get(savedObjectAttributes, 'ui_viewed.setup_guide', 0),
engines_overview: get(savedObjectAttributes, 'ui_viewed.engines_overview', 0),
},
ui_error: {
cannot_connect: get(savedObjectAttributes, 'ui_error.cannot_connect', 0),
},
ui_clicked: {
create_first_engine_button: get(
savedObjectAttributes,
'ui_clicked.create_first_engine_button',
0
),
header_launch_button: get(savedObjectAttributes, 'ui_clicked.header_launch_button', 0),
engine_table_link: get(savedObjectAttributes, 'ui_clicked.engine_table_link', 0),
},
} as ITelemetry;
};
// ===== END =====
// ===== BEGIN typescript =====
/*
Copyright 2019-2020 eMobilify GmbH
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { IDisplayText } from "./common"
import { IEnergyMix } from "./locations"
import { IPrice } from "./session"
export interface ITariff {
country_code: string
party_id: string
id: string
currency: string
type?: string
tariff_alt_text?: IDisplayText[]
tariff_alt_url?: string
min_price?: IPrice
max_price?: IPrice
elements: ITariffElement[]
start_date_time?: string
end_date_time?: string
energy_mix?: IEnergyMix
last_updated: string
}
export interface ITariffElement {
price_components: IPriceComponent[]
restrictions?: {
start_time?: string
end_time?: string
start_date?: string
end_date?: string
min_kwh?: number
max_kwh?: number
min_current?: number
max_current?: number
min_power?: number
max_power?: number
min_duration?: number
max_duration?: number
day_of_week?: string[]
reservation?: string
}
}
export interface IPriceComponent {
type: "ENERGY" | "FLAT" | "PARKING_TIME" | "TIME"
price: number
vat?: number
step_size: number
}
// ===== END =====
// ===== BEGIN typescript =====
module.exports = (__testFn) => {
describe('sugar.js.is.object', () => {
it('Should detect the passed variable type correctly', () => {
class myClass { }
expect(__testFn({ hello: 'world' })).toBe(true);
expect(__testFn(12)).toBe(false);
expect(__testFn(function () { })).toBe(false);
expect(__testFn(new myClass())).toBe(false);
});
});
}
// ===== END =====
// ===== BEGIN typescript =====
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UIModule } from '../ui/ui.module';
import {
DEMOANGULARMATERIAL_COMPONENTS,
DemoAngularMaterialComponent,
DemoMaterialAddressComponent,
DemoMaterialDashboardComponent,
DemoMaterialDragAndDropComponent,
DemoMaterialTableComponent,
DemoMaterialTreeComponent
} from './components';
import {
DemoAngularMaterialModule as SharedDemoAngularMaterialModule,
routeDemoAngularMaterial
} from '@application/features';
@NgModule({
imports: [
SharedDemoAngularMaterialModule,
UIModule,
RouterModule.forChild(
routeDemoAngularMaterial(
DemoAngularMaterialComponent,
DemoMaterialAddressComponent,
DemoMaterialDashboardComponent,
DemoMaterialDragAndDropComponent,
DemoMaterialTableComponent,
DemoMaterialTreeComponent
)
)
],
declarations: [...DEMOANGULARMATERIAL_COMPONENTS],
exports: [...DEMOANGULARMATERIAL_COMPONENTS]
})
export class DemoAngularMaterialModule {}
// ===== END =====
// ===== BEGIN typescript =====
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Stores {
@PrimaryGeneratedColumn()
id?: number;
@Column({ type: 'varchar', length: 255, default: ''})
name?: string;
@Column({ type: 'varchar', length: 255})
phone?: string;
@Column({ type: 'varchar', length: 500, default: '', nullable: true })
location?: string;
@Column({ type: 'varchar', length: 255, default: '', nullable: true })
representative?: string;
@Column({ type: 'boolean', default: false})
is_location_verify?: boolean;
@Column({ type: 'simple-array'})
services?: string[];
}
// ===== END =====
// ===== BEGIN typescript =====
/******************************************************************************
* Spine Runtimes Software License
* Version 2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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.
*****************************************************************************/
namespace pixi_spine.core {
export class SlotData {
index: number;
name: string;
boneData: BoneData;
color = new Color(1, 1, 1, 1);
darkColor: Color;
attachmentName: string;
blendMode: BlendMode;
constructor (index: number, name: string, boneData: BoneData) {
if (index < 0) throw new Error("index must be >= 0.");
if (name == null) throw new Error("name cannot be null.");
if (boneData == null) throw new Error("boneData cannot be null.");
this.index = index;
this.name = name;
this.boneData = boneData;
}
}
}
// ===== END =====
// ===== BEGIN typescript =====
import os from 'os';
import sinon from 'sinon';
import { LogLevel, ReportType, strykerCoreSchema, StrykerOptions } from '@stryker-mutator/api/core';
import { testInjector, factory } from '@stryker-mutator/test-helpers';
import { expect } from 'chai';
import { OptionsValidator, validateOptions, markUnknownOptions } from '../../../src/config/options-validator';
import { coreTokens } from '../../../src/di';
import { createCpuInfo } from '../../helpers/producers';
describe(OptionsValidator.name, () => {
let sut: OptionsValidator;
beforeEach(() => {
sut = testInjector.injector.provideValue(coreTokens.validationSchema, strykerCoreSchema).injectClass(OptionsValidator);
});
it('should validate an empty object', () => {
sut.validate({});
expect(testInjector.logger.fatal).not.called;
expect(testInjector.logger.error).not.called;
expect(testInjector.logger.warn).not.called;
});
it('should fill default values', () => {
const options: Record<string, unknown> = {};
sut.validate(options);
const expectedOptions: StrykerOptions = {
allowConsoleColors: true,
appendPlugins: [],
checkers: [],
cleanTempDir: true,
inPlace: false,
clearTextReporter: {
allowColor: true,
logTests: true,
maxTestsToLog: 3,
},
commandRunner: {
command: 'npm test',
},
coverageAnalysis: 'off',
dashboard: {
baseUrl: 'https://dashboard.stryker-mutator.io/api/reports',
reportType: ReportType.Full,
},
disableTypeChecks: '{test,src,lib}/**/*.{js,ts,jsx,tsx,html,vue}',
dryRunTimeoutMinutes: 5,
eventReporter: {
baseDir: 'reports/mutation/events',
},
fileLogLevel: LogLevel.Off,
jsonReporter: {
fileName: 'reports/mutation/mutation.json',
},
logLevel: LogLevel.Information,
maxConcurrentTestRunners: 9007199254740991,
maxTestRunnerReuse: 0,
mutate: [
'{src,lib}/**/!(*.+(s|S)pec|*.+(t|T)est).+(cjs|mjs|js|ts|jsx|tsx|html|vue)',
'!{src,lib}/**/__tests__/**/*.+(cjs|mjs|js|ts|jsx|tsx|html|vue)',
],
mutator: {
excludedMutations: [],
plugins: null,
},
plugins: ['@stryker-mutator/*'],
reporters: ['clear-text', 'progress', 'html'],
symlinkNodeModules: true,
tempDirName: '.stryker-tmp',
testRunner: 'command',
testRunnerNodeArgs: [],
thresholds: {
break: null,
high: 80,
low: 60,
},
timeoutFactor: 1.5,
timeoutMS: 5000,
tsconfigFile: 'tsconfig.json',
warnings: true,
};
expect(options).deep.eq(expectedOptions);
});
it('should validate the default options', () => {
actAssertValid();
});
describe('thresholds', () => {
it('should be invalid with thresholds < 0 or > 100', () => {
testInjector.options.thresholds.high = -1;
testInjector.options.thresholds.low = 101;
actValidationErrors('Config option "thresholds.high" should be >= 0, was -1.', 'Config option "thresholds.low" should be <= 100, was 101.');
});
it('should be invalid with thresholds.high null', () => {
// @ts-expect-error invalid setting
testInjector.options.thresholds.high = null;
actValidationErrors('Config option "thresholds.high" has the wrong type. It should be a number, but was a null.');
});
it('should not allow high < low', () => {
testInjector.options.thresholds.high = 20;
testInjector.options.thresholds.low = 21;
actValidationErrors('Config option "thresholds.high" should be higher than "thresholds.low".');
});
});
it('should be invalid with invalid logLevel', () => {
// @ts-expect-error invalid setting
testInjector.options.logLevel = 'thisTestPasses';
actValidationErrors(
'Config option "logLevel" should be one of the allowed values ("off", "fatal", "error", "warn", "info", "debug", "trace"), but was "thisTestPasses".'
);
});
it('should be invalid with non-numeric timeoutMS', () => {
breakConfig('timeoutMS', 'break');
actValidationErrors('Config option "timeoutMS" has the wrong type. It should be a number, but was a string.');
});
it('should be invalid with non-numeric timeoutFactor', () => {
breakConfig('timeoutFactor', 'break');
actValidationErrors('Config option "timeoutFactor" has the wrong type. It should be a number, but was a string.');
});
it('should be invalid with non-numeric dryRunTimeout', () => {
breakConfig('dryRunTimeoutMinutes', 'break');
actValidationErrors('Config option "dryRunTimeoutMinutes" has the wrong type. It should be a number, but was a string.');
});
it('should be invalid with negative numeric dryRunTimeout', () => {
breakConfig('dryRunTimeoutMinutes', -1);
actValidationErrors('Config option "dryRunTimeoutMinutes" should be >= 0, was -1.');
});
describe('plugins', () => {
it('should be invalid with non-array plugins', () => {
breakConfig('plugins', '@stryker-mutator/typescript');
actValidationErrors('Config option "plugins" has the wrong type. It should be a array, but was a string.');
});
it('should be invalid with non-string array elements', () => {
breakConfig('plugins', ['stryker-jest', 0]);
actValidationErrors('Config option "plugins[1]" has the wrong type. It should be a string, but was a number.');
});
});
describe('appendPlugins', () => {
it('should be invalid with non-array plugins', () => {
breakConfig('appendPlugins', '@stryker-mutator/typescript');
actValidationErrors('Config option "appendPlugins" has the wrong type. It should be a array, but was a string.');
});
it('should be invalid with non-string array elements', () => {
breakConfig('appendPlugins', ['stryker-jest', 0]);
actValidationErrors('Config option "appendPlugins[1]" has the wrong type. It should be a string, but was a number.');
});
});
describe('mutator', () => {
it('should be invalid with non-string mutator', () => {
// @ts-expect-error invalid setting
testInjector.options.mutator = 1;
actValidationErrors('Config option "mutator" has the wrong type. It should be a object, but was a number.');
});
it('should report a deprecation warning for "mutator.name"', () => {
testInjector.options.mutator = {
// @ts-expect-error invalid setting
name: 'javascript',
};
sut.validate(testInjector.options);
expect(testInjector.logger.warn).calledWith(
'DEPRECATED. Use of "mutator.name" is no longer needed. You can remove "mutator.name" from your configuration. Stryker now supports mutating of JavaScript and friend files out of the box.'
);
});
it('should report a deprecation warning for mutator as a string', () => {
// @ts-expect-error invalid setting
testInjector.options.mutator = 'javascript';
sut.validate(testInjector.options);
expect(testInjector.logger.warn).calledWith(
'DEPRECATED. Use of "mutator" as string is no longer needed. You can remove it from your configuration. Stryker now supports mutating of JavaScript and friend files out of the box.'
);
});
});
describe('testFramework', () => {
it('should report a deprecation warning', () => {
testInjector.options.testFramework = '';
sut.validate(testInjector.options);
expect(testInjector.logger.warn).calledWith(
'DEPRECATED. Use of "testFramework" is no longer needed. You can remove it from your configuration. Your test runner plugin now handles its own test framework integration.'
);
});
});
describe('reporters', () => {
it('should be invalid with non-array reporters', () => {
breakConfig('reporters', '@stryker-mutator/typescript');
actValidationErrors('Config option "reporters" has the wrong type. It should be a array, but was a string.');
});
// ===== END =====
// ===== BEGIN typescript =====
import { getRegionInfo, PartitionHash, RegionHash } from "@aws-sdk/config-resolver";
import { RegionInfoProvider, RegionInfoProviderOptions } from "@aws-sdk/types";
const regionHash: RegionHash = {
"us-east-1": {
variants: [
{
hostname: "workspaces.us-east-1.amazonaws.com",
tags: [],
},
{
hostname: "workspaces-fips.us-east-1.amazonaws.com",
tags: ["fips"],
},
],
},
"us-gov-west-1": {
variants: [
{
hostname: "workspaces.us-gov-west-1.amazonaws.com",
tags: [],
},
{
hostname: "workspaces-fips.us-gov-west-1.amazonaws.com",
tags: ["fips"],
},
],
},
"us-west-2": {
variants: [
{
hostname: "workspaces.us-west-2.amazonaws.com",
tags: [],
},
{
hostname: "workspaces-fips.us-west-2.amazonaws.com",
tags: ["fips"],
},
],
},
};
const partitionHash: PartitionHash = {
aws: {
regions: [
"af-south-1",
"ap-east-1",
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
"ap-south-1",
"ap-southeast-1",
"ap-southeast-2",
"ca-central-1",
"eu-central-1",
"eu-north-1",
"eu-south-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"fips-us-east-1",
"fips-us-west-2",
"me-south-1",
"sa-east-1",
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
],
regionRegex: "^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$",
variants: [
{
hostname: "workspaces.{region}.amazonaws.com",
tags: [],
},
{
hostname: "workspaces-fips.{region}.amazonaws.com",
tags: ["fips"],
},
{
hostname: "workspaces-fips.{region}.api.aws",
tags: ["dualstack", "fips"],
},
{
hostname: "workspaces.{region}.api.aws",
tags: ["dualstack"],
},
],
},
"aws-cn": {
regions: ["cn-north-1", "cn-northwest-1"],
regionRegex: "^cn\\-\\w+\\-\\d+$",
variants: [
{
hostname: "workspaces.{region}.amazonaws.com.cn",
tags: [],
},
{
hostname: "workspaces-fips.{region}.amazonaws.com.cn",
tags: ["fips"],
},
{
hostname: "workspaces-fips.{region}.api.amazonwebservices.com.cn",
tags: ["dualstack", "fips"],
},
{
hostname: "workspaces.{region}.api.amazonwebservices.com.cn",
tags: ["dualstack"],
},
],
},
"aws-iso": {
regions: ["us-iso-east-1", "us-iso-west-1"],
regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
variants: [
{
hostname: "workspaces.{region}.c2s.ic.gov",
tags: [],
},
],
},
"aws-iso-b": {
regions: ["us-isob-east-1"],
regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
variants: [
{
hostname: "workspaces.{region}.sc2s.sgov.gov",
tags: [],
},
],
},
"aws-us-gov": {
regions: ["fips-us-gov-west-1", "us-gov-east-1", "us-gov-west-1"],
regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
variants: [
{
hostname: "workspaces.{region}.amazonaws.com",
tags: [],
},
{
hostname: "workspaces-fips.{region}.amazonaws.com",
tags: ["fips"],
},
{
hostname: "workspaces-fips.{region}.api.aws",
tags: ["dualstack", "fips"],
},
{
hostname: "workspaces.{region}.api.aws",
tags: ["dualstack"],
},
],
},
};
export const defaultRegionInfoProvider: RegionInfoProvider = async (
region: string,
options?: RegionInfoProviderOptions
) =>
getRegionInfo(region, {
...options,
signingService: "workspaces",
regionHash,
partitionHash,
});
// ===== END =====
// ===== BEGIN typescript =====
export function convertSnaps<T>(snaps) {
return <T[]>snaps.map((snap: any) => {
return {
id: snap.payload.doc.id,
...snap.payload.doc.data(),
};
});
}
// ===== END =====
// ===== BEGIN typescript =====
import { createAsyncThunk } from "@reduxjs/toolkit";
import { comApi } from "../../apis/comApi";
import { CreateChannelDTO, CreateConverationDTO, GetListChannelDTO, GetListConversationDTO, GetMessagesHistoryDTO, SendMessageDTO } from "../../models/dtos";
import { GetListUserStatusDTO } from "../../models/dtos/UserStatusDTOs";
//conversation
export const getOrCreateConversation = createAsyncThunk(
'chat/getOrCreateConversation',
async (data: CreateConverationDTO, thunkAPI) => {
const { dispatch } = thunkAPI;
const createResponse = await comApi.getOrCreateConversation(data);
const response = await comApi.getConversation(createResponse.data)
return response;
}
)
export const getConversation = createAsyncThunk(
'chat/getConversation',
async (id: string, thunkAPI) => {
const response = await comApi.getConversation(id);
return response
}
)
export const getConversations = createAsyncThunk(
'chat/getConversations',
async (data: GetListConversationDTO |undefined, thunkAPI) => {
const response = await comApi.getConversations(data);
return response
}
)
export const deleteConversation = createAsyncThunk(
'chat/deleteConversation',
async (id: string, thunkAPI) => {
const response = await comApi.deleteConversation(id);
return response
}
)
//message
export const sendMessage = createAsyncThunk(
'chat/sendMessage',
async (data: SendMessageDTO, thunkAPI) => {
const response = await comApi.sendMessage(data);
return response
}
)
//channel
export const getChannels = createAsyncThunk(
'chat/getChannels',
async (data: GetListChannelDTO |undefined, thunkAPI) => {
const response = await comApi.getChannels(data);
return response
}
)
export const createChannel = createAsyncThunk(
'chat/createChannel',
async (data: CreateChannelDTO, thunkAPI) => {
const { dispatch } = thunkAPI;
const createResponse = await comApi.createChannel(data);
const response = await comApi.getChannel(createResponse.data);
return response;
}
)
export const getMessageHistory = createAsyncThunk(
'chat/getMessageHistory',
async (data: GetMessagesHistoryDTO, thunkAPI) => {
const response = await comApi.getMessageHistory(data);
return response
},
{
condition: (userId, { getState, extra }) => {
const state = getState() as any
console.log('getMessageHistory-state',state)
// const fetchStatus = users.requests[userId]
// if (fetchStatus === 'fulfilled' || fetchStatus === 'loading') {
// // Already fetched or in progress, don't need to re-fetch
// return false
// }
return true;
},
}
)
//userstatus
export const getUsers = createAsyncThunk(
'chat/getUsers',
async (data: GetListUserStatusDTO |undefined, thunkAPI) => {
const response = await comApi.getUsers(data);
return response
}
)
// ===== END =====
// ===== BEGIN typescript =====
import { Component, HostListener, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Observable, of, Subject } from 'rxjs';
import { MatDialog } from '@angular/material/dialog';
import { KtbProjectSettingsGitComponent } from '../ktb-project-settings-git/ktb-project-settings-git.component';
import { DeleteData, DeleteResult, DeleteType } from '../../_interfaces/delete';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { DataService } from '../../_services/data.service';
import { DtToast } from '@dynatrace/barista-components/toast';
import { NotificationsService } from '../../_services/notifications.service';
import { EventService } from '../../_services/event.service';
import { filter, map, takeUntil } from 'rxjs/operators';
import { Project } from '../../_models/project';
import { FormUtils } from '../../_utils/form.utils';
import { KtbProjectCreateMessageComponent } from '../_status-messages/ktb-project-create-message/ktb-project-create-message.component';
import { NotificationType } from '../../_models/notification';
import { PendingChangesComponent } from '../../_guards/pending-changes.guard';
import { IClientFeatureFlags } from '../../../../shared/interfaces/feature-flags';
import { IGitData, IGitDataExtended } from '../../_interfaces/git-upstream';
import { AppUtils } from '../../_utils/app.utils';
import { FeatureFlagsService } from '../../_services/feature-flags.service';
type DialogState = null | 'unsaved';
@Component({
selector: 'ktb-project-settings',
templateUrl: './ktb-project-settings.component.html',
styleUrls: ['./ktb-project-settings.component.scss'],
})
export class KtbProjectSettingsComponent implements OnInit, OnDestroy, PendingChangesComponent {
private readonly unsubscribe$ = new Subject<void>();
@ViewChild('deleteProjectDialog')
private deleteProjectDialog?: TemplateRef<MatDialog>;
@ViewChild(KtbProjectSettingsGitComponent)
private gitSettingsSection?: KtbProjectSettingsGitComponent;
public gitInputDataExtended?: IGitDataExtended;
public gitInputDataExtendedDefault?: IGitDataExtended;
public projectName?: string;
public projectDeletionData?: DeleteData;
public isProjectLoading: boolean | undefined;
public isCreateMode = false;
public isGitUpstreamInProgress = false;
public isCreatingProjectInProgress = false;
private pendingChangesSubject = new Subject<boolean>();
public isProjectFormTouched = false;
public shipyardFile?: File;
public gitData: IGitData = {
gitFormValid: true,
};
private gitDataExtended?: IGitDataExtended;
public projectNameControl = new FormControl('');
public projectNameForm = new FormGroup({
projectName: this.projectNameControl,
});
public message = 'You have pending changes. Make sure to save your data before you continue.';
public unsavedDialogState: DialogState = null;
public resourceServiceEnabled?: boolean;
constructor(
private route: ActivatedRoute,
private dataService: DataService,
private toast: DtToast,
private router: Router,
private notificationsService: NotificationsService,
private eventService: EventService,
featureFlagService: FeatureFlagsService
) {
featureFlagService.featureFlags$
.pipe(takeUntil(this.unsubscribe$))
.subscribe((featureFlags: IClientFeatureFlags) => {
this.resourceServiceEnabled = featureFlags.RESOURCE_SERVICE_ENABLED;
});
}
public ngOnInit(): void {
this.route.params.subscribe((params) => {
if (!params.projectName) {
this.isCreateMode = true;
this.loadProjectsAndSetValidator();
} else {
this.isProjectLoading = true;
this.isCreateMode = false;
this.isProjectFormTouched = false;
this.projectName = params.projectName;
this.projectDeletionData = {
type: DeleteType.PROJECT,
name: this.projectName || '',
};
this.loadProject(params.projectName);
}
});
this.route.queryParams.subscribe((queryParams) => {
if (queryParams.created) {
this.showCreateNotificationAndRedirect();
}
});
this.eventService.deletionTriggeredEvent.pipe(takeUntil(this.unsubscribe$)).subscribe((data) => {
if (data.type === DeleteType.PROJECT) {
this.deleteProject(data.name);
}
});
}
private loadProjectsAndSetValidator(): void {
this.dataService
.loadProjects()
.pipe(
takeUntil(this.unsubscribe$),
filter((projects: Project[] | undefined): projects is Project[] => !!projects),
map((projects: Project[]) => projects.map((project) => project.projectName))
)
.subscribe((projectNames) => {
this.projectNameControl.setValidators([
Validators.required,
FormUtils.nameExistsValidator(projectNames),
Validators.pattern('[a-z]([a-z]|[0-9]|-)*'),
]);
});
}
private loadProject(projectName: string): void {
this.dataService.loadPlainProject(projectName).subscribe((project: Project) => {
this.gitData = {
gitRemoteURL: project.gitRemoteURI,
gitUser: project.gitUser,
};
this.gitInputDataExtendedDefault = project.gitUpstream;
this.gitInputDataExtended = AppUtils.copyObject(project.gitUpstream); // there should not be a reference. Could
// lead to problems when the form is reset
this.isProjectLoading = false;
});
}
private showCreateNotificationAndRedirect(): void {
this.notificationsService.addNotification(
NotificationType.SUCCESS,
'',
{
component: KtbProjectCreateMessageComponent,
data: {
projectName: this.projectName,
routerLink: `/project/${this.projectName}/settings/services/create`,
},
},
10_000
);
// Remove query param for not showing notification on reload
this.router.navigate(['/', 'project', this.projectName, 'settings', 'project']);
}
public updateGitData(gitData: IGitData): void {
this.gitData.gitRemoteURL = gitData.gitRemoteURL;
this.gitData.gitUser = gitData.gitUser;
this.gitData.gitToken = gitData.gitToken;
this.gitData.gitFormValid = gitData.gitFormValid;
this.projectFormTouched();
}
public updateGitDataExtended(data?: IGitDataExtended): void {
this.gitDataExtended = data;
this.projectFormTouched();
}
public updateShipyardFile(shipyardFile: File | undefined): void {
this.shipyardFile = shipyardFile;
this.projectFormTouched();
}
public setGitUpstream(): void {
if (this.projectName && this.gitData.gitRemoteURL && this.gitData.gitToken) {
this.isGitUpstreamInProgress = true;
this.hideNotification();
this.dataService
.setGitUpstreamUrl(this.projectName, this.gitData.gitRemoteURL, this.gitData.gitToken, this.gitData.gitUser)
.pipe(takeUntil(this.unsubscribe$))
.subscribe(
() => {
this.isGitUpstreamInProgress = false;
this.gitData.gitToken = '';
this.gitData = { ...this.gitData };
this.notificationsService.addNotification(
NotificationType.SUCCESS,
'The Git upstream was changed successfully.'
);
this.pendingChangesSubject.next(true);
this.isProjectFormTouched = false;
},
(err) => {
this.isGitUpstreamInProgress = false;
this.notificationsService.addNotification(
NotificationType.ERROR,
`<div class="long-note align-left p-3">The Git upstream could not be changed:<br/><span class="small">${err.error}</span></div>`
);
}
);
}
}
public async createProject(): Promise<void> {
if (this.shipyardFile) {
this.isCreatingProjectInProgress = true;
const fileContent = await FormUtils.readFileContent(this.shipyardFile)
// ===== END =====
// ===== BEGIN typescript =====
import {
SearchFacetDivider,
SearchFacetInputProps,
SearchFacetName,
SearchFacetOperators
} from '@types'
import groq from 'groq'
export const divider: SearchFacetDivider = {type: 'divider'}
export const inputs: Record<SearchFacetName, SearchFacetInputProps> = {
altText: {
assetTypes: ['file', 'image'],
field: 'altText',
name: 'altText',
operatorType: 'empty',
operatorTypes: ['empty', 'notEmpty', null, 'includes', 'doesNotInclude'],
title: 'Alt Text',
type: 'string',
value: ''
},
description: {
assetTypes: ['file', 'image'],
field: 'description',
name: 'description',
operatorType: 'empty',
operatorTypes: ['empty', 'notEmpty', null, 'includes', 'doesNotInclude'],
title: 'Description',
type: 'string',
value: ''
},
height: {
assetTypes: ['image'],
field: 'metadata.dimensions.height',
name: 'height',
operatorType: 'greaterThan',
operatorTypes: [
'greaterThan',
'greaterThanOrEqualTo',
'lessThan',
'lessThanOrEqualTo',
null,
'equalTo'
],
title: 'Height',
type: 'number',
value: 400
},
inCurrentDocument: {
assetTypes: ['file', 'image'],
name: 'inCurrentDocument',
operatorType: 'is',
options: [
{
name: 'true',
title: 'True',
value: groq`_id in $documentAssetIds`
},
{
name: 'false',
title: 'False',
value: groq`!(_id in $documentAssetIds)`
}
],
selectOnly: true,
title: 'In use in current document',
type: 'select',
value: 'true'
},
inUse: {
assetTypes: ['file', 'image'],
name: 'inUse',
operatorType: 'is',
options: [
{
name: 'true',
title: 'True',
value: groq`count(*[references(^._id)]) > 0`
},
{
name: 'false',
title: 'False',
value: groq`count(*[references(^._id)]) == 0`
}
],
title: 'In use',
type: 'select',
value: 'true'
},
isOpaque: {
assetTypes: ['image'],
field: 'metadata.isOpaque',
name: 'isOpaque',
operatorType: 'equalTo',
options: [
{
name: 'true',
title: 'True',
value: `false`
},
{
name: 'false',
title: 'False',
value: `true`
}
],
title: 'Has transparency',
type: 'select',
value: 'true'
},
orientation: {
assetTypes: ['image'],
name: 'orientation',
operatorType: 'is',
operatorTypes: ['is', 'isNot'],
options: [
{
name: 'portrait',
title: 'Portrait',
value: 'metadata.dimensions.aspectRatio < 1'
},
{
name: 'landscape',
title: 'Landscape',
value: 'metadata.dimensions.aspectRatio > 1'
},
{
name: 'square',
title: 'Square',
value: 'metadata.dimensions.aspectRatio == 1'
}
],
title: 'Orientation',
type: 'select',
value: 'portrait'
},
size: {
assetTypes: ['file', 'image'],
field: 'size',
modifier: 'kb',
modifiers: [
{
name: 'kb',
title: 'KB',
fieldModifier: fieldName => `round(${fieldName} / 1000)`
},
{
name: 'mb',
title: 'MB',
fieldModifier: fieldName => `round(${fieldName} / 1000000)`
}
],
name: 'size',
operatorType: 'greaterThan',
operatorTypes: [
'greaterThan',
'greaterThanOrEqualTo',
'lessThan',
'lessThanOrEqualTo',
null,
'equalTo'
],
title: 'File Size',
type: 'number',
value: 0
},
tag: {
assetTypes: ['file', 'image'],
field: 'opt.media.tags',
name: 'tag',
operatorType: 'references',
operatorTypes: ['references', 'doesNotReference', null, 'empty', 'notEmpty'],
title: 'Tags',
type: 'searchable'
},
title: {
assetTypes: ['file', 'image'],
field: 'title',
name: 'title',
operatorType: 'empty',
operatorTypes: ['empty', 'notEmpty', null, 'includes', 'doesNotInclude'],
title: 'Title',
type: 'string',
value: ''
},
type: {
assetTypes: ['file', 'image'],
name: 'type',
operatorType: 'is',
operatorTypes: ['is', 'isNot'],
options: [
{
name: 'image',
title: 'Image',
value: 'mimeType match "image*"'
},
{
name: 'video',
title: 'Video',
value: 'mimeType match "video*"'
},
{
name: 'audio',
title: 'Audio',
value: 'mimeType match "audio*"'
},
{
name: 'pdf',
title: 'PDF',
value: 'mimeType == "application/pdf"'
}
],
title: 'File Type',
type: 'select',
value: 'image'
},
width: {
assetTypes: ['image'],
field: 'metadata.dimensions.width',
name: 'width',
operatorType: 'greaterThan',
operatorTypes: [
'greaterThan',
'greaterThanOrEqualTo',
'lessThan',
'lessThanOrEqualTo',
null,
'equalTo'
],
title: 'Width',
type: 'number',
value: 400
}
}
export const operators: SearchFacetOperators = {
doesNotInclude: {
fn: (value, field) => (value ? `!(${field} match '*${value}*')` : undefined),
label: 'does not include'
},
doesNotReference: {
fn: (value, _) => (value ? `!references('${value}')` : undefined),
label: 'does not include'
},
empty: {
fn: (_, field) => `!defined(${field})`,
hideInput: true,
label: 'is empty'
},
equalTo: {
fn: (value, field) => (value ? `${field} == ${value}` : undefined),
label: 'is equal to'
},
greaterThan: {
fn: (value, field) => (value ? `${field} > ${value}` : undefined),
label: 'is greater than'
},
greaterThanOrEqualTo: {
fn: (value, field) => (value ? `${field} >= ${value}` : undefined),
label: 'is greater than or equal to'
},
includes: {
fn: (value, field) => (value ? `${field} match '*${value}*'` : undefined),
label: 'includes'
},
is: {
fn: (value, _) => `${value}`,
label: 'is'
},
isNot: {
fn: (value, _) => `!(${value})`,
label: 'is not'
},
lessThan: {
fn: (value, field) => (value ? `${field} < ${value}` : undefined),
label: 'is less than'
},
lessThanOrEqualTo: {
fn: (value, field) => (value ? `${field} <= ${value}` : undefined),
label: 'is less than or equal to'
},
notEmpty: {
fn: (_, field) => `defined(${field})`,
hideInput: true,
label: 'is not empty'
},
references: {
fn: (value, _) => (value ? `references('${value}')` : undefined),
label: 'includes'
}
}
// ===== END =====
// ===== BEGIN typescript =====
import React, { useState, Fragment } from "react";
import {
EuiIcon,
EuiHeaderAlert,
EuiHeaderSectionItemButton,
EuiFlyout,
EuiFlyoutBody,
EuiFlyoutHeader,
EuiTitle,
EuiLink,
EuiFlyoutFooter,
EuiFlexGroup,
EuiFlexItem,
EuiButtonEmpty,
EuiText,
EuiBadge,
} from "@elastic/eui";
export default () => {
const [isFlyoutVisible, setIsFlyoutVisible] = useState(false);
const [showBadge, setShowBadge] = useState(true);
const alerts = [
{
title: "Facial Beauty",
text: "First release.",
action: <EuiLink href="#">Learn about feature controls</EuiLink>,
date: "2021/04/09",
badge: <EuiBadge>0.0.1</EuiBadge>,
},
];
const closeFlyout = () => {
setIsFlyoutVisible(false);
};
const showFlyout = () => {
setShowBadge(false);
setIsFlyoutVisible(!isFlyoutVisible);
};
const button = (
<EuiHeaderSectionItemButton
aria-controls="headerNewsFeed"
aria-expanded={isFlyoutVisible}
aria-haspopup="true"
aria-label={`News feed: ${{ showBadge } ? "Updates available" : "No updates"}`}
onClick={() => showFlyout()}
notification={showBadge && "•"}>
<EuiIcon type="cheer" size="m" />
</EuiHeaderSectionItemButton>
);
let flyout;
if (isFlyoutVisible) {
flyout = (
<EuiFlyout
onClose={() => closeFlyout()}
size="s"
id="headerNewsFeed"
aria-labelledby="flyoutSmallTitle">
<EuiFlyoutHeader hasBorder>
<EuiTitle size="s">
<h2 id="flyoutSmallTitle">What's new</h2>
</EuiTitle>
</EuiFlyoutHeader>
<EuiFlyoutBody>
{alerts.map((alert, i) => (
<EuiHeaderAlert
key={`alert-${i}`}
title={alert.title}
action={alert.action}
text={alert.text}
date={alert.date}
badge={alert.badge}
/>
))}
</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="spaceBetween" alignItems="center">
<EuiFlexItem grow={false}>
<EuiButtonEmpty iconType="cross" onClick={() => closeFlyout()} flush="left">
Close
</EuiButtonEmpty>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiText color="subdued" size="s">
<p>Version 0.0.1</p>
</EuiText>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</EuiFlyout>
);
}
return (
<Fragment>
{button}
{flyout}
</Fragment>
);
};
// ===== END =====
// ===== BEGIN typescript =====
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About CryptoFightClub</source>
<translation>关于黑币</translation>
</message>
<message>
<location line="+39"/>
<source><b>CryptoFightClub</b> version</source>
<translation><b>黑币客户端</b> 版本</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The CryptoFightClub developers</source>
<translation>版权所有 © 2009-2014 比特币Bitcoin开发组
版权所有 © 2012-2014 新星币Novacoin开发组
版权所有 © 2014 黑币CryptoFightClub开发组</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
测试版软件
经MIT/X11软件授权发布, 具体参见http://www.opensource.org/licenses/mit-license.php.
本产品包括由OpenSSL Project (http://www.openssl.org/)开发的OpenSSL工具包 ,由 Eric Young ([email protected]) 撰写的密码学软件以及由 Thomas Bernard 撰写的UPnP软件.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>地址簿</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>双击编辑地址或标签</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>创建新地址</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>复制当前选中的地址到系统剪贴板</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>新建地址(&N)</translation>
</message>
<message>
<location line="-46"/>
<source>These are your CryptoFightClub addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>这是您用来接收支付的黑币地址列表。为不同的支付方建立不同的地址以便于了解支付来源。</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>复制地址(&C)</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>显示二维码(&Q)</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a CryptoFightClub address</source>
<translation>对信息进行签名以证明您对该黑币地址的所有权</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>签名(&M)</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>从列表中删除选中的地址</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified CryptoFightClub address</source>
<translation>验证信息以保证其经过指定黑币地址的签名</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>验证消息(&V)</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>删除(&D)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>复制标签(&L)</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>编辑(&E)</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>导出地址簿数据</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗号分隔文件 (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>导出时发生错误</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>无法写入文件 %1 。</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>密码对话框</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>输入密码</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>新密码</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>重复新密码</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>在系统允许的情况下用于防止sendmoney欺诈,并未提供真正的安全防护措施。</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>仅用于权益增值</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>输入钱包的新密码。<br/>使用的密码请至少包含<b>10个以上随机字符</>,或者是<b>8个以上的单词</b>。</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>加密钱包</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>此操作需要您首先使用密码解锁该钱包。</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>解锁钱包</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>该操作需要您首先使用密码解密钱包。</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>解密钱包</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>更
// ===== END =====
// ===== BEGIN typescript =====
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/keybindingsEditor';
import { localize } from 'vs/nls';
import { Delayer } from 'vs/base/common/async';
import * as DOM from 'vs/base/browser/dom';
import { OS } from 'vs/base/common/platform';
import { dispose, Disposable, IDisposable, combinedDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CheckboxActionViewItem } from 'vs/base/browser/ui/checkbox/checkbox';
import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel';
import { KeybindingLabel } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel';
import { IAction, Action, Separator } from 'vs/base/common/actions';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { EditorOptions, IEditorOpenContext } from 'vs/workbench/common/editor';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { KeybindingsEditorModel, IKeybindingItemEntry, IListEntry, KEYBINDING_ENTRY_TEMPLATE_ID } from 'vs/workbench/services/preferences/common/keybindingsEditorModel';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService, IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding';
import { DefineKeybindingWidget, KeybindingsSearchWidget, KeybindingsSearchOptions } from 'vs/workbench/contrib/preferences/browser/keybindingWidgets';
import { CONTEXT_KEYBINDING_FOCUS, CONTEXT_KEYBINDINGS_EDITOR, CONTEXT_KEYBINDINGS_SEARCH_FOCUS, KEYBINDINGS_EDITOR_COMMAND_RECORD_SEARCH_KEYS, KEYBINDINGS_EDITOR_COMMAND_SORTBY_PRECEDENCE, KEYBINDINGS_EDITOR_COMMAND_DEFINE, KEYBINDINGS_EDITOR_COMMAND_REMOVE, KEYBINDINGS_EDITOR_COMMAND_RESET, KEYBINDINGS_EDITOR_COMMAND_COPY, KEYBINDINGS_EDITOR_COMMAND_COPY_COMMAND, KEYBINDINGS_EDITOR_COMMAND_CLEAR_SEARCH_RESULTS, KEYBINDINGS_EDITOR_COMMAND_DEFINE_WHEN, KEYBINDINGS_EDITOR_COMMAND_SHOW_SIMILAR, KEYBINDINGS_EDITOR_COMMAND_ADD } from 'vs/workbench/contrib/preferences/common/preferences';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IKeybindingEditingService } from 'vs/workbench/services/keybinding/common/keybindingEditing';
import { IListVirtualDelegate, IListRenderer, IListContextMenuEvent, IListEvent } from 'vs/base/browser/ui/list/list';
import { IThemeService, registerThemingParticipant, IColorTheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
import { IContextKeyService, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode, ResolvedKeybinding } from 'vs/base/common/keyCodes';
import { listHighlightForeground, badgeBackground, contrastBorder, badgeForeground, listActiveSelectionForeground, listInactiveSelectionForeground, listHoverForeground, listFocusForeground, editorBackground, foreground, listActiveSelectionBackground, listInactiveSelectionBackground, listFocusBackground, listHoverBackground } from 'vs/platform/theme/common/colorRegistry';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { KeybindingsEditorInput } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { CancellationToken } from 'vs/base/common/cancellation';
import { attachStylerCallback, attachInputBoxStyler, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox';
import { Emitter, Event } from 'vs/base/common/event';
import { MenuRegistry, MenuId, isIMenuItem } from 'vs/platform/actions/common/actions';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { preferencesEditIcon } from 'vs/workbench/contrib/preferences/browser/preferencesWidgets';
import { Color, RGBA } from 'vs/base/common/color';
import { WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme';
import { IBaseActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';
import { IKeybindingsEditorPane } from 'vs/workbench/services/preferences/common/preferences';
const $ = DOM.$;
interface ColumnItem {
column: HTMLElement;
proportion?: number;
width: number;
}
const oddRowBackgroundColor = new Color(new RGBA(130, 130, 130, 0.04));
class ThemableCheckboxActionViewItem extends CheckboxActionViewItem {
constructor(context: any, action: IAction, options: IBaseActionViewItemOptions | undefined, private readonly themeService: IThemeService) {
super(context, action, options);
}
render(container: HTMLElement): void {
super.render(container);
if (this.checkbox) {
this.disposables.add(attachCheckboxStyler(this.checkbox, this.themeService));
}
}
}
export class KeybindingsEditor extends EditorPane implements IKeybindingsEditorPane {
static readonly ID: string = 'workbench.editor.keybindings';
private _onDefineWhenExpression: Emitter<IKeybindingItemEntry> = this._register(new Emitter<IKeybindingItemEntry>());
readonly onDefineWhenExpression: Event<IKeybindingItemEntry> = this._onDefineWhenExpression.event;
private _onLayout: Emitter<void> = this._register(new Emitter<void>());
readonly onLayout: Event<void> = this._onLayout.event;
private keybindingsEditorModel: KeybindingsEditorModel | null = null;
private headerContainer!: HTMLElement;
private actionsContainer!: HTMLElement;
private searchWidget!: KeybindingsSearchWidget;
private overlayContainer!: HTMLElement;
private defineKeybindingWidget!: DefineKeybindingWidget;
private columnItems: ColumnItem[] = [];
private keybindingsListContainer!: HTMLElement;
private unAssignedKeybindingItemToRevealAndFocus: IKeybindingItemEntry | null = null;
private listEntries: IListEntry[] = [];
private keybindingsList!: WorkbenchList<IListEntry>;
private dimension: DOM.Dimension | null = null;
private delayedFiltering: Delayer<void>;
private latestEmptyFilters: string[] = [];
private delayedFilterLogging: Delayer<void>;
private keybindingsEditorContextKey: IContextKey<boolean>;
private keybindingFocusContextKey: IContextKey<boolean>;
private searchFocusContextKey: IContextKey<boolean>;
private readonly sortByPrecedenceAction: Action;
private readonly recordKeysAction: Action;
private ariaLabelElement!: HTMLElement;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IKeybindingService private readonly keybindingsService: IKeybindingService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IKeybindingEditingService private readonly keybindingEditingService: IKeybindingEditingService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@INotificationService private readonly notificationService: INotificationService,
@IClipboardService private readonly clipboardService: IClipboardService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IEditorService private readonly editorService: IEditorService,
@IStorageService storageService: IStorageService
) {
super(KeybindingsEditor.ID,
// ===== END =====
// ===== BEGIN typescript =====
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import electron from 'electron';
import keytar from 'keytar';
import * as ros from '../../services/ros';
const SERVICE_NAME = electron.remote.app.getName();
export const setCredentials = (credentials: ros.IServerCredentials) => {
return keytar.setPassword(
SERVICE_NAME,
credentials.url,
JSON.stringify(credentials),
);
};
export const getCredentials = async (
url: string | null,
): Promise<ros.IServerCredentials | null> => {
if (!url) {
return null;
}
const result = await keytar.getPassword(SERVICE_NAME, url);
if (result) {
return JSON.parse(result);
} else {
return null;
}
};
export const unsetCredentials = async (url: string) => {
return keytar.deletePassword(SERVICE_NAME, url);
};
// ===== END =====
// ===== BEGIN typescript =====
import { promises as fs } from "fs"
import csv from "async-csv"
export const readCSV = async (path: string): Promise<unknown[]> => {
try {
const csvString = await fs.readFile(path, "utf-8")
const rows = await csv.parse(csvString)
return rows
// return rows.map((row) => (row as string).split(","))
} catch (e) {
console.log(`Error reading csv: ${e}`)
}
}
const writeCSV = async (path: string, rows: (string | number)[][]): Promise<void> => {
try {
const stringData = await csv.stringify(rows)
await fs.writeFile(path, stringData)
} catch (e) {
console.log(`Error writing csv: ${e}`)
}
}
// make a backup of current csv
// load current csv
// iterate through rows
// if case number not present, add it to the csv
// else do nothing
// close csv
export const writeRowsToCSV = async (path: string, rows: Record<string, any>[]): Promise<void> => {
await fs.copyFile(path, `${path}_${new Date().toISOString()}.backup`)
const data = await readCSV(path)
const existingCaseNumbers = data.map((row) => row[0])
rows.forEach((json) => {
if (existingCaseNumbers.includes(json.caseNumber)) return
// build array
const newData = [
json.caseNumber,
json.caseStatus,
json.caseDetailsUrl,
json.partyName,
json.partyType,
json.partyDetailsUrl,
]
data.push(newData)
})
await writeCSV(path, data as (string | number)[][])
}
// ===== END =====
// ===== BEGIN typescript =====
import { Request, Response } from 'express';
import * as yup from 'yup';
import { CreateUserService } from '../../services/create/CreateUserService';
const createUserSchema = yup.object().shape({
name: yup.string().required(),
email: yup.string().email().required(),
admin: yup.boolean().notRequired(),
password: yup.string().min(6).required(),
});
class CreateUserController {
async handle(request: Request, response: Response) {
await createUserSchema.validate(request.body, { abortEarly: false });
const { name, email, admin, password } = request.body;
const createUserService = new CreateUserService();
const user = await createUserService.execute({
name,
email,
admin,
password,
});
return response.status(201).json(user);
}
}
export { CreateUserController };
// ===== END =====
// ===== BEGIN typescript =====
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { expect } from 'chai';
import * as path from 'path';
import * as sinon from 'sinon';
import * as TypeMoq from 'typemoq';
import untildify = require('untildify');
import { WorkspaceConfiguration } from 'vscode';
import { LanguageServerType } from '../../../client/activation/types';
import { WorkspaceService } from '../../../client/common/application/workspace';
import { PythonSettings } from '../../../client/common/configSettings';
import { InterpreterPathService } from '../../../client/common/interpreterPathService';
import { PersistentStateFactory } from '../../../client/common/persistentState';
import {
IAutoCompleteSettings,
IExperiments,
IFormattingSettings,
ILintingSettings,
ISortImportSettings,
ITerminalSettings,
} from '../../../client/common/types';
import { noop } from '../../../client/common/utils/misc';
import * as EnvFileTelemetry from '../../../client/telemetry/envFileTelemetry';
import { ITestingSettings } from '../../../client/testing/configuration/types';
import { MockAutoSelectionService } from '../../mocks/autoSelector';
import { MockMemento } from '../../mocks/mementos';
suite('Python Settings', async () => {
class CustomPythonSettings extends PythonSettings {
public update(pythonSettings: WorkspaceConfiguration) {
return super.update(pythonSettings);
}
public initialize() {
noop();
}
}
let config: TypeMoq.IMock<WorkspaceConfiguration>;
let expected: CustomPythonSettings;
let settings: CustomPythonSettings;
setup(() => {
sinon.stub(EnvFileTelemetry, 'sendSettingTelemetry').returns();
config = TypeMoq.Mock.ofType<WorkspaceConfiguration>(undefined, TypeMoq.MockBehavior.Loose);
const workspaceService = new WorkspaceService();
const workspaceMemento = new MockMemento();
const globalMemento = new MockMemento();
const persistentStateFactory = new PersistentStateFactory(globalMemento, workspaceMemento);
expected = new CustomPythonSettings(
undefined,
new MockAutoSelectionService(),
workspaceService,
new InterpreterPathService(persistentStateFactory, workspaceService, []),
undefined,
);
settings = new CustomPythonSettings(
undefined,
new MockAutoSelectionService(),
workspaceService,
new InterpreterPathService(persistentStateFactory, workspaceService, []),
undefined,
);
expected.defaultInterpreterPath = 'python';
});
teardown(() => {
sinon.restore();
});
function initializeConfig(sourceSettings: PythonSettings) {
// string settings
for (const name of [
'pythonPath',
'venvPath',
'condaPath',
'pipenvPath',
'envFile',
'poetryPath',
'defaultInterpreterPath',
]) {
config
.setup((c) => c.get<string>(name))
.returns(() => (sourceSettings as any)[name]);
}
for (const name of ['venvFolders']) {
config
.setup((c) => c.get<string[]>(name))
.returns(() => (sourceSettings as any)[name]);
}
// boolean settings
for (const name of ['downloadLanguageServer', 'autoUpdateLanguageServer']) {
config
.setup((c) => c.get<boolean>(name, true))
.returns(() => (sourceSettings as any)[name]);
}
for (const name of ['disableInstallationCheck', 'globalModuleInstallation']) {
config
.setup((c) => c.get<boolean>(name))
.returns(() => (sourceSettings as any)[name]);
}
// Language server type settings
config.setup((c) => c.get<LanguageServerType>('languageServer')).returns(() => sourceSettings.languageServer);
// "any" settings
config.setup((c) => c.get<any[]>('devOptions')).returns(() => sourceSettings.devOptions);
// complex settings
config.setup((c) => c.get<ILintingSettings>('linting')).returns(() => sourceSettings.linting);
config.setup((c) => c.get<ISortImportSettings>('sortImports')).returns(() => sourceSettings.sortImports);
config.setup((c) => c.get<IFormattingSettings>('formatting')).returns(() => sourceSettings.formatting);
config.setup((c) => c.get<IAutoCompleteSettings>('autoComplete')).returns(() => sourceSettings.autoComplete);
config.setup((c) => c.get<ITestingSettings>('testing')).returns(() => sourceSettings.testing);
config.setup((c) => c.get<ITerminalSettings>('terminal')).returns(() => sourceSettings.terminal);
config.setup((c) => c.get<IExperiments>('experiments')).returns(() => sourceSettings.experiments);
}
function testIfValueIsUpdated(settingName: string, value: any) {
test(`${settingName} updated`, async () => {
expected.pythonPath = 'python3';
(expected as any)[settingName] = value;
initializeConfig(expected);
settings.update(config.object);
expect((settings as any)[settingName]).to.be.equal((expected as any)[settingName]);
config.verifyAll();
});
}
suite('String settings', async () => {
['venvPath', 'condaPath', 'pipenvPath', 'envFile', 'poetryPath', 'defaultInterpreterPath'].forEach(
async (settingName) => {
testIfValueIsUpdated(settingName, 'stringValue');
},
);
});
suite('Boolean settings', async () => {
['downloadLanguageServer', 'autoUpdateLanguageServer', 'globalModuleInstallation'].forEach(
async (settingName) => {
testIfValueIsUpdated(settingName, true);
},
);
});
test('condaPath updated', () => {
expected.pythonPath = 'python3';
expected.condaPath = 'spam';
initializeConfig(expected);
config
.setup((c) => c.get<string>('condaPath'))
.returns(() => expected.condaPath)
.verifiable(TypeMoq.Times.once());
settings.update(config.object);
expect(settings.condaPath).to.be.equal(expected.condaPath);
config.verifyAll();
});
test('condaPath (relative to home) updated', async () => {
expected.pythonPath = 'python3';
expected.condaPath = path.join('~', 'anaconda3', 'bin', 'conda');
initializeConfig(expected);
config
.setup((c) => c.get<string>('condaPath'))
.returns(() => expected.condaPath)
.verifiable(TypeMoq.Times.once());
settings.update(config.object);
expect(settings.condaPath).to.be.equal(untildify(expected.condaPath));
config.verifyAll();
});
function testLanguageServer(
languageServer: LanguageServerType,
expectedValue: LanguageServerType,
isDefault: boolean,
) {
test(languageServer, () => {
expected.pythonPath = 'python3';
expected.languageServer = languageServer;
initializeConfig(expected);
config
.setup((c) => c.get<LanguageServerType>('languageServer'))
.returns(() => expected.languageServer)
.verifiable(TypeMoq.Times.once());
settings.update(config.object);
expect(settings.languageServer).to.be.equal(expectedValue);
expect(settings.languageServerIsDefault).to.be.equal(isDefault);
config.verifyAll();
});
}
suite('languageServer settings', async () => {
const values = [
{ ls: LanguageServerType.Jedi, expected: LanguageServerType.Jedi, default: false },
{ ls: LanguageServerType
// ===== END =====
// ===== BEGIN java =====
/**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.common.data.oauth2;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.SearchTextBasedWithAdditionalInfo;
import org.thingsboard.server.common.data.id.OAuth2ClientRegistrationInfoId;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
@ToString(exclude = {"clientSecret"})
@NoArgsConstructor
public class OAuth2ClientRegistrationInfo extends SearchTextBasedWithAdditionalInfo<OAuth2ClientRegistrationInfoId> implements HasName {
private boolean enabled;
private OAuth2MapperConfig mapperConfig;
private String clientId;
private String clientSecret;
private String authorizationUri;
private String accessTokenUri;
private List<String> scope;
private String userInfoUri;
private String userNameAttributeName;
private String jwkSetUri;
private String clientAuthenticationMethod;
private String loginButtonLabel;
private String loginButtonIcon;
public OAuth2ClientRegistrationInfo(OAuth2ClientRegistrationInfo clientRegistration) {
super(clientRegistration);
this.enabled = clientRegistration.enabled;
this.mapperConfig = clientRegistration.mapperConfig;
this.clientId = clientRegistration.clientId;
this.clientSecret = clientRegistration.clientSecret;
this.authorizationUri = clientRegistration.authorizationUri;
this.accessTokenUri = clientRegistration.accessTokenUri;
this.scope = clientRegistration.scope;
this.userInfoUri = clientRegistration.userInfoUri;
this.userNameAttributeName = clientRegistration.userNameAttributeName;
this.jwkSetUri = clientRegistration.jwkSetUri;
this.clientAuthenticationMethod = clientRegistration.clientAuthenticationMethod;
this.loginButtonLabel = clientRegistration.loginButtonLabel;
this.loginButtonIcon = clientRegistration.loginButtonIcon;
}
@Override
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getName() {
return loginButtonLabel;
}
@Override
public String getSearchText() {
return getName();
}
}
// ===== END =====
// ===== BEGIN java =====
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.stack.Protocol;
import org.jgroups.util.MyReceiver;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
/**
* Tests UNICAST2. Created to test the last-message-dropped problem, see https://issues.jboss.org/browse/JGRP-1548.
* @author Bela Ban
* @since 3.3
*/
@Test(groups=Global.FUNCTIONAL,singleThreaded=true)
public class UNICAST_DropFirstAndLastTest {
protected JChannel a, b;
protected MyReceiver<Integer> rb;
protected DISCARD discard; // on A
protected void setup(Class<? extends Protocol> unicast_class) throws Exception {
a=createChannel(unicast_class, "A");
discard=(DISCARD)a.getProtocolStack().findProtocol(DISCARD.class);
assert discard != null;
a.connect("UNICAST_DropFirstAndLastTest");
rb=new MyReceiver<Integer>().name("B").verbose(true);
b=createChannel(unicast_class, "B").receiver(rb);
b.connect("UNICAST_DropFirstAndLastTest");
Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
}
@AfterMethod protected void destroy() {setLevel("warn", a, b); Util.close(b, a); rb.reset();}
@DataProvider
static Object[][] configProvider() {
return new Object[][]{
{UNICAST.class},
{UNICAST2.class},
{UNICAST3.class}
};
}
/**
* A sends unicast messages 1-5 to B, but we drop message 5. The code in
* https://issues.jboss.org/browse/JGRP-1548 now needs to make sure message 5 is retransmitted to B
* within a short time period, and we don't have to rely on the stable task to kick in.
*/
@Test(dataProvider="configProvider")
public void testLastMessageDropped(Class<? extends Protocol> unicast_class) throws Exception {
setup(unicast_class);
setLevel("trace", a, b);
Address dest=b.getAddress();
for(int i=1; i <= 5; i++) {
Message msg=new Message(dest, i);
if(i == 5)
discard.setDropDownUnicasts(1); // drops the next unicast
a.send(msg);
}
List<Integer> msgs=rb.list();
Util.waitUntilListHasSize(msgs, 5, 5000, 500);
System.out.println("list=" + msgs);
}
/**
* A sends unicast message 1 to B, but we drop message 1. The code in
* https://issues.jboss.org/browse/JGRP-1563 now needs to make sure message 1 is retransmitted to B
* within a short time period, and we don't have to rely on the stable task to kick in.
*/
@Test(dataProvider="configProvider")
public void testFirstMessageDropped(Class<? extends Protocol> unicast_class) throws Exception {
setup(unicast_class);
System.out.println("**** closing all connections ****");
// close all connections, so we can start from scratch and send message A1 to B
for(JChannel ch: Arrays.asList(a,b)) {
Protocol unicast=ch.getProtocolStack().findProtocol(Util.getUnicastProtocols());
removeAllConnections(unicast);
}
setLevel("trace", a, b);
System.out.println("--> A sending first message to B (dropped before it reaches B)");
discard.setDropDownUnicasts(1); // drops the next unicast
a.send(new Message(b.getAddress(), 1));
List<Integer> msgs=rb.list();
try {
Util.waitUntilListHasSize(msgs, 1, 500000, 500);
}
catch(AssertionError err) {
printConnectionTables(a, b);
throw err;
}
System.out.println("list=" + msgs);
printConnectionTables(a, b);
// assert ((UNICAST2)a.getProtocolStack().findProtocol(UNICAST2.class)).connectionEstablished(b.getAddress());
}
protected JChannel createChannel(Class<? extends Protocol> unicast_class, String name) throws Exception {
Protocol unicast=unicast_class.newInstance();
if(unicast instanceof UNICAST2)
unicast.setValue("stable_interval", 1000);
return new JChannel(new SHARED_LOOPBACK().setValue("enable_batching", true),
new PING().setValue("timeout", 1000),
new NAKACK2().setValue("use_mcast_xmit", false),
new DISCARD(),
unicast.setValue("xmit_interval", 500),
new GMS().setValue("print_local_addr", false))
.name(name);
}
protected void printConnectionTables(JChannel ... channels) {
System.out.println("**** CONNECTIONS:");
for(JChannel ch: channels) {
Protocol ucast=ch.getProtocolStack().findProtocol(Util.getUnicastProtocols());
System.out.println(ch.getName() + ":\n" + printConnections(ucast) + "\n");
}
}
protected void setLevel(String level, JChannel ... channels) {
for(JChannel ch: channels)
ch.getProtocolStack().findProtocol(Util.getUnicastProtocols()).level(level);
}
protected String printConnections(Protocol prot) {
if(prot instanceof UNICAST) {
UNICAST unicast=(UNICAST)prot;
return unicast.printConnections();
}
else if(prot instanceof UNICAST2) {
UNICAST2 unicast=(UNICAST2)prot;
return unicast.printConnections();
}
else if(prot instanceof UNICAST3) {
UNICAST3 unicast=(UNICAST3)prot;
return unicast.printConnections();
}
else
throw new IllegalArgumentException("prot (" + prot + ") needs to be UNICAST, UNICAST2 or UNICAST3");
}
protected void removeAllConnections(Protocol prot) {
if(prot instanceof UNICAST) {
UNICAST unicast=(UNICAST)prot;
unicast.removeAllConnections();
}
else if(prot instanceof UNICAST2) {
UNICAST2 unicast=(UNICAST2)prot;
unicast.removeAllConnections();
}
else if(prot instanceof UNICAST3) {
UNICAST3 unicast=(UNICAST3)prot;
unicast.removeAllConnections();
}
else
throw new IllegalArgumentException("prot (" + prot + ") needs to be UNICAST, UNICAST2 or UNICAST3");
}
}
// ===== END =====
// ===== BEGIN java =====
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.storm.exclamation.util;
/**
* Expected output of Exclamation programs.
*/
public class ExclamationData {
public static final String TEXT_WITH_EXCLAMATIONS =
"Goethe - Faust: Der Tragoedie erster Teil!!!!!!\n"
+ "Prolog im Himmel.!!!!!!\n"
+ "Der Herr. Die himmlischen Heerscharen. Nachher Mephistopheles. Die drei!!!!!!\n"
+ "Erzengel treten vor.!!!!!!\n"
+ "RAPHAEL: Die Sonne toent, nach alter Weise, In Brudersphaeren Wettgesang,!!!!!!\n"
+ "Und ihre vorgeschriebne Reise Vollendet sie mit Donnergang. Ihr Anblick!!!!!!\n"
+ "gibt den Engeln Staerke, Wenn keiner Sie ergruenden mag; die unbegreiflich!!!!!!\n"
+ "hohen Werke Sind herrlich wie am ersten Tag.!!!!!!\n"
+ "GABRIEL: Und schnell und unbegreiflich schnelle Dreht sich umher der Erde!!!!!!\n"
+ "Pracht; Es wechselt Paradieseshelle Mit tiefer, schauervoller Nacht. Es!!!!!!\n"
+ "schaeumt das Meer in breiten Fluessen Am tiefen Grund der Felsen auf, Und!!!!!!\n"
+ "Fels und Meer wird fortgerissen Im ewig schnellem Sphaerenlauf.!!!!!!\n"
+ "MICHAEL: Und Stuerme brausen um die Wette Vom Meer aufs Land, vom Land!!!!!!\n"
+ "aufs Meer, und bilden wuetend eine Kette Der tiefsten Wirkung rings umher.!!!!!!\n"
+ "Da flammt ein blitzendes Verheeren Dem Pfade vor des Donnerschlags. Doch!!!!!!\n"
+ "deine Boten, Herr, verehren Das sanfte Wandeln deines Tags.!!!!!!\n"
+ "ZU DREI: Der Anblick gibt den Engeln Staerke, Da keiner dich ergruenden!!!!!!\n"
+ "mag, Und alle deine hohen Werke Sind herrlich wie am ersten Tag.!!!!!!\n"
+ "MEPHISTOPHELES: Da du, o Herr, dich einmal wieder nahst Und fragst, wie!!!!!!\n"
+ "alles sich bei uns befinde, Und du mich sonst gewoehnlich gerne sahst, So!!!!!!\n"
+ "siehst du mich auch unter dem Gesinde. Verzeih, ich kann nicht hohe Worte!!!!!!\n"
+ "machen, Und wenn mich auch der ganze Kreis verhoehnt; Mein Pathos braechte!!!!!!\n"
+ "dich gewiss zum Lachen, Haettst du dir nicht das Lachen abgewoehnt. Von!!!!!!\n"
+ "Sonn' und Welten weiss ich nichts zu sagen, Ich sehe nur, wie sich die!!!!!!\n"
+ "Menschen plagen. Der kleine Gott der Welt bleibt stets von gleichem!!!!!!\n"
+ "Schlag, Und ist so wunderlich als wie am ersten Tag. Ein wenig besser!!!!!!\n"
+ "wuerd er leben, Haettst du ihm nicht den Schein des Himmelslichts gegeben;!!!!!!\n"
+ "Er nennt's Vernunft und braucht's allein, Nur tierischer als jedes Tier!!!!!!\n"
+ "zu sein. Er scheint mir, mit Verlaub von euer Gnaden, Wie eine der!!!!!!\n"
+ "langbeinigen Zikaden, Die immer fliegt und fliegend springt Und gleich im!!!!!!\n"
+ "Gras ihr altes Liedchen singt; Und laeg er nur noch immer in dem Grase! In!!!!!!\n"
+ "jeden Quark begraebt er seine Nase.!!!!!!\n"
+ "DER HERR: Hast du mir weiter nichts zu sagen? Kommst du nur immer!!!!!!\n"
+ "anzuklagen? Ist auf der Erde ewig dir nichts recht?!!!!!!\n"
+ "MEPHISTOPHELES: Nein Herr! ich find es dort, wie immer, herzlich!!!!!!\n"
+ "schlecht. Die Menschen dauern mich in ihren Jammertagen, Ich mag sogar!!!!!!\n"
+ "die armen selbst nicht plagen.!!!!!!\n" + "DER HERR: Kennst du den Faust?!!!!!!\n"
+ "MEPHISTOPHELES: Den Doktor?!!!!!!\n"
+ "DER HERR: Meinen Knecht!!!!!!!\n"
+ "MEPHISTOPHELES: Fuerwahr! er dient Euch auf besondre Weise. Nicht irdisch!!!!!!\n"
+ "ist des Toren Trank noch Speise. Ihn treibt die Gaerung in die Ferne, Er!!!!!!\n"
+ "ist sich seiner Tollheit halb bewusst; Vom Himmel fordert er die schoensten!!!!!!\n"
+ "Sterne Und von der Erde jede hoechste Lust, Und alle Naeh und alle Ferne!!!!!!\n"
+ "Befriedigt nicht die tiefbewegte Brust.!!!!!!\n"
+ "DER HERR: Wenn er mir auch nur verworren dient, So werd ich ihn bald in!!!!!!\n"
+ "die Klarheit fuehren. Weiss doch der Gaertner, wenn das Baeumchen gruent, Das!!!!!!\n"
+ "Bluet und Frucht die kuenft'gen Jahre zieren.!!!!!!\n"
+ "MEPHISTOPHELES: Was wettet Ihr? den sollt Ihr noch verlieren! Wenn Ihr!!!!!!\n"
+ "mir die Erlaubnis gebt, Ihn meine Strasse sacht zu fuehren.!!!!!!\n"
+ "DER HERR: Solang er auf der Erde lebt, So lange sei dir's nicht verboten,!!!!!!\n"
+ "Es irrt der Mensch so lang er strebt.!!!!!!\n"
+ "MEPHISTOPHELES: Da dank ich Euch; denn mit den Toten Hab ich mich niemals!!!!!!\n"
+ "gern befangen. Am meisten lieb ich mir die vollen, frischen Wangen. Fuer!!!!!!\n"
+ "einem Leichnam bin ich nicht zu Haus; Mir geht es wie der Katze mit der Maus.!!!!!!\n"
+ "DER HERR: Nun gut, es sei dir ueberlassen! Zieh diesen Geist von seinem!!!!!!\n"
+ "Urquell ab, Und fuehr ihn, kannst du ihn erfassen, Auf deinem Wege mit!!!!!!\n"
+ "herab, Und steh beschaemt, wenn du bekennen musst: Ein guter Mensch, in!!!!!!\n"
+ "seinem dunklen Drange, Ist sich des rechten Weges wohl bewusst.!!!!!!\n"
+ "MEPHISTOPHELES: Schon gut! nur dauert es nicht lange. Mir ist fuer meine!!!!!!\n"
+ "Wette gar nicht bange. Wenn ich zu meinem Zweck gelange, Erlaubt Ihr mir!!!!!!\n"
+ "Triumph aus voller Brust. Staub soll er fressen, und mit Lust, Wie meine!!!!!!\n"
+ "Muhme, die beruehmte Schlange.!!!!!!\n"
+ "DER HERR: Du darfst auch da nur frei erscheinen; Ich habe deinesgleichen!!!!!!\n"
+ "nie gehasst. Von allen Geistern, die verneinen, ist mir der Schalk am!!!!!!\n"
+ "wenigsten zur Last. Des Menschen Taetigkeit kann allzu leicht erschlaffen,!!!!!!\n"
+ "er liebt sich bald die unbedingte Ruh; Drum geb ich gern ihm den Gesellen!!!!!!\n"
+ "zu, Der reizt und wirkt und muss als Teufel schaffen. Doch ihr, die echten!!!!!!\n"
+ "Goettersoehne, Erfreut euch der lebendig reichen Schoene! Das Werdende, das!!!!!!\n"
+ "ewig wirkt und lebt, Umfass euch mit der Liebe holden Schranken, Und was!!!!!!\n"
+ "in schwankender Erscheinung schwebt, Befestigt mit dauernden Gedanken!!!!!!!\n"
+ "(Der Himmel schliesst, die Erzengel verteilen sich.)!!!!!!\n"
+ "MEPHISTOPHELES (allein): Von Zeit zu Zeit seh ich den Alten gern, Und!!!!!!\n"
+ "huete mich, mit ihm zu brechen. Es ist gar huebsch von einem grossen Herrn,!!!!!!\n"
+ "So menschlich mit dem Teufel selbst zu sprechen.!!!!!!";
}
// ===== END =====
// ===== BEGIN java =====
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.cme.v20191029.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class VideoTrackItem extends AbstractModel{
/**
* 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
@SerializedName("SourceType")
@Expose
private String SourceType;
/**
* 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
@SerializedName("SourceMedia")
@Expose
private String SourceMedia;
/**
* 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
@SerializedName("SourceMediaStartTime")
@Expose
private Float SourceMediaStartTime;
/**
* 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
@SerializedName("Duration")
@Expose
private Float Duration;
/**
* 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
@SerializedName("XPos")
@Expose
private String XPos;
/**
* 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
*/
@SerializedName("YPos")
@Expose
private String YPos;
/**
* 视频原点位置,取值有:
<li>Center:坐标原点为中心位置,如画布中心。</li>
默认值 :Center。
*/
@SerializedName("CoordinateOrigin")
@Expose
private String CoordinateOrigin;
/**
* 视频片段的高度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
@SerializedName("Height")
@Expose
private String Height;
/**
* 视频片段的宽度。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li>
<li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li>
<li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li>
<li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li>
<li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li>
*/
@SerializedName("Width")
@Expose
private String Width;
/**
* Get 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
* @return SourceType 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
public String getSourceType() {
return this.SourceType;
}
/**
* Set 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
* @param SourceType 视频媒体来源类型,取值有:
<ul>
<li>VOD :媒体来源于云点播文件 。</li>
<li>CME :视频来源制作云媒体文件。</li>
<li>EXTERNAL :视频来源于媒资绑定。</li>
</ul>
*/
public void setSourceType(String SourceType) {
this.SourceType = SourceType;
}
/**
* Get 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
* @return SourceMedia 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
public String getSourceMedia() {
return this.SourceMedia;
}
/**
* Set 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
* @param SourceMedia 视频片段的媒体文件来源,取值为:
<ul>
<li>当 SourceType 为 VOD 时,为云点播的媒体文件 FileId ,会默认将该 FileId 导入到项目中;</li>
<li>当 SourceType 为 CME 时,为制作云的媒体 ID,项目归属者必须对该云媒资有访问权限;</li>
<li>当 SourceType 为 EXTERNAL 时,为媒资绑定的 Definition 与 MediaKey 中间用冒号分隔合并后的字符串,格式为 Definition:MediaKey 。</li>
</ul>
*/
public void setSourceMedia(String SourceMedia) {
this.SourceMedia = SourceMedia;
}
/**
* Get 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
* @return SourceMediaStartTime 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
public Float getSourceMediaStartTime() {
return this.SourceMediaStartTime;
}
/**
* Set 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
* @param SourceMediaStartTime 视频片段取自媒体文件的起始时间,单位为秒。默认为0。
*/
public void setSourceMediaStartTime(Float SourceMediaStartTime) {
this.SourceMediaStartTime = SourceMediaStartTime;
}
/**
* Get 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
* @return Duration 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
public Float getDuration() {
return this.Duration;
}
/**
* Set 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
* @param Duration 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。
*/
public void setDuration(Float Duration) {
this.Duration = Duration;
}
/**
* Get 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
* @return XPos 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
public String getXPos() {
return this.XPos;
}
/**
* Set 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
* @param XPos 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li>
默认值:0px。
*/
public void setXPos(String XPos) {
this.XPos = XPos;
}
/**
* Get 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
* @return YPos 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
*/
public String getYPos() {
return this.YPos;
}
/**
* Set 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li>
<li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li>
默认值:0px。
* @param YPos 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式:
<li>当字符串以 % 结尾,表示视频片段 YPos 为画布
// ===== END =====
// ===== BEGIN java =====
package com.google.android.gms.internal.ads;
public final class sy extends ez {
public sy(tx txVar, String str, String str2, xp xpVar, int i2, int i3) {
super(txVar, str, str2, xpVar, i2, 3);
}
/* access modifiers changed from: protected */
@Override // com.google.android.gms.internal.ads.ez
public final void a() {
synchronized (this.f4244e) {
gx gxVar = new gx((String) this.f4245f.invoke(null, this.f4241b.a()));
synchronized (this.f4244e) {
this.f4244e.f6028e = Long.valueOf(gxVar.f4456b);
this.f4244e.d0 = Long.valueOf(gxVar.f4457c);
}
}
}
}
// ===== END =====
// ===== BEGIN java =====
/*
* Copyright 2012-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.webservices;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests for {@link WebServicesProperties}.
*
* @author Madhura Bhave
*/
public class WebServicesPropertiesTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private WebServicesProperties properties;
@Test
public void pathMustNotBeEmpty() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("");
}
@Test
public void pathMustHaveLengthGreaterThanOne() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must have length greater than 1");
this.properties.setPath("/");
}
@Test
public void customPathMustBeginWithASlash() {
this.properties = new WebServicesProperties();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Path must start with '/'");
this.properties.setPath("custom");
}
}
// ===== END =====
// ===== BEGIN java =====
package com.watson.propert.tycoon.game.bord;
import com.watson.propert.tycoon.game.entitys.Player;
/** Action that from Cards and Square need implement this interface */
public interface Action {
void run(Player player);
}
// ===== END =====
// ===== BEGIN java =====
package com.battlelancer.seriesguide.jobs.episodes;
import android.content.Context;
import androidx.annotation.NonNull;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.provider.SgEpisode2Numbers;
import com.battlelancer.seriesguide.provider.SgRoomDatabase;
import java.util.List;
public class ShowCollectedJob extends ShowBaseJob {
private final boolean isCollected;
public ShowCollectedJob(long showId, boolean isCollected) {
super(showId, isCollected ? 1 : 0, JobAction.EPISODE_COLLECTION);
this.isCollected = isCollected;
}
@Override
protected boolean applyDatabaseChanges(@NonNull Context context) {
int rowsUpdated = SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.updateCollectedOfShowExcludeSpecials(getShowId(), isCollected);
return rowsUpdated >= 0; // -1 means error.
}
@NonNull
@Override
protected List<SgEpisode2Numbers> getEpisodesForNetworkJob(@NonNull Context context) {
return SgRoomDatabase.getInstance(context).sgEpisode2Helper()
.getEpisodeNumbersOfShow(getShowId());
}
@Override
protected int getPlaysForNetworkJob(int plays) {
return plays; // Collected change does not change plays.
}
@NonNull
@Override
public String getConfirmationText(Context context) {
return context.getString(isCollected
? R.string.action_collection_add : R.string.action_collection_remove);
}
}
// ===== END =====
// ===== BEGIN java =====
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.ibiosim.gui.modelEditor.gcm;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.Species;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.annotation.AnnotationUtility;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.annotation.SBOLAnnotation;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.parser.BioModel;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.SBMLutilities;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.GlobalConstants;
import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.ibiosim.gui.Gui;
import edu.utah.ece.async.ibiosim.gui.modelEditor.sbmlcore.MySpecies;
import edu.utah.ece.async.ibiosim.gui.modelEditor.sbol.SBOLField2;
import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.ModelEditor;
import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.Utils;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyField;
import edu.utah.ece.async.ibiosim.gui.modelEditor.util.PropertyList;
/**
*
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class PromoterPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 5873800942710657929L;
private String[] options = { "Ok", "Cancel" };
private HashMap<String, PropertyField> fields = null;
private SBOLField2 sbolField;
private String selected = "";
private BioModel bioModel = null;
private boolean paramsOnly;
private ModelEditor modelEditor = null;
private Species promoter = null;
private Reaction production = null;
private PropertyList speciesList;
private JComboBox compartBox = null;
private JTextField iIndex = null;
public PromoterPanel(String selected, BioModel bioModel, PropertyList speciesList, boolean paramsOnly, BioModel refGCM,
ModelEditor modelEditor) {
super(new GridLayout(paramsOnly?7:13, 1));
this.selected = selected;
this.bioModel = bioModel;
this.paramsOnly = paramsOnly;
this.modelEditor = modelEditor;
this.speciesList = speciesList;
fields = new HashMap<String, PropertyField>();
Model model = bioModel.getSBMLDocument().getModel();
promoter = model.getSpecies(selected);
PropertyField field = null;
// ID field
String dimInID = SBMLutilities.getDimensionString(promoter);
field = new PropertyField(GlobalConstants.ID, promoter.getId() + dimInID, null, null, Utility.IDDimString, paramsOnly, "default", false);
fields.put(GlobalConstants.ID, field);
if (!paramsOnly) add(field);
// Name field
field = new PropertyField(GlobalConstants.NAME, promoter.getName(), null, null, Utility.NAMEstring, paramsOnly, "default", false);
fields.put(GlobalConstants.NAME, field);
if (!paramsOnly) add(field);
// Type field
JPanel tempPanel = new JPanel();
JLabel tempLabel = new JLabel(GlobalConstants.PORTTYPE);
typeBox = new JComboBox(types);
//typeBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(typeBox);
if (!paramsOnly) add(tempPanel);
if (bioModel.isInput(promoter.getId())) {
typeBox.setSelectedItem(GlobalConstants.INPUT);
} else if (bioModel.isOutput(promoter.getId())) {
typeBox.setSelectedItem(GlobalConstants.OUTPUT);
} else {
typeBox.setSelectedItem(GlobalConstants.INTERNAL);
}
production = bioModel.getProductionReaction(selected);
// compartment field
tempPanel = new JPanel();
tempLabel = new JLabel("Compartment");
compartBox = MySpecies.createCompartmentChoices(bioModel);
compartBox.setSelectedItem(promoter.getCompartment());
compartBox.addActionListener(this);
tempPanel.setLayout(new GridLayout(1, 2));
tempPanel.add(tempLabel);
tempPanel.add(compartBox);
if (!paramsOnly) add(tempPanel);
// indices field
tempPanel = new JPanel(new GridLayout(1, 2));
iIndex = new JTextField(20);
String freshIndex = SBMLutilities.getIndicesString(promoter, "compartment");
iIndex.setText(freshIndex);
tempPanel.add(new JLabel("Compartment Indices"));
tempPanel.add(iIndex);
if (!paramsOnly) add(tempPanel);
// promoter count
String origString = "default";
String defaultValue = bioModel.getParameter(GlobalConstants.PROMOTER_COUNT_STRING);
String formatString = Utility.NUMstring;
if (paramsOnly) {
if (refGCM.getSBMLDocument().getModel().getSpecies(promoter.getId()).getInitialAmount() !=
model.getParameter(GlobalConstants.PROMOTER_COUNT_STRING).getValue()) {
defaultValue = ""+refGCM.getSBMLDocument().getModel().getSpecies(promoter.getId()).getInitialAmount();
origString = "custom";
}
formatString = Utility.SWEEPstring;
}
field = new PropertyField(GlobalConstants.PROMOTER_COUNT_STRING,
bioModel.getParameter(GlobalConstants.PROMOTER_COUNT_STRING), origString,
defaultValue, formatString, paramsOnly, origString, false);
String sweep = AnnotationUtility.parseSweepAnnotation(promoter);
if (sweep != null) {
field.setValue(sweep);
field.setCustom();
} else if (!defaultValue.equals(""+promoter.getInitialAmount())) {
field.setValue(""+promoter.getInitialAmount());
field.setCustom();
}
fields.put(GlobalConstants.PROMOTER_COUNT_STRING, field);
add(field);
// RNAP binding
origString = "default";
defaultValue = bioModel.getParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING) + "/" +
bioModel.getParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
formatString = Utility.SLASHstring;
if (paramsOnly) {
/*
defaultValue = refGCM.getParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING)+"/"+
refGCM.getParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING); */
if (production != null) {
Reaction refProd = refGCM.getSBMLDocument().getModel().getReaction(production.getId());
LocalParameter ko_f = refProd.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
LocalParameter ko_r = refProd.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
if (ko_f != null && ko_r != null) {
defaultValue = ko_f.getValue()+"/"+ko_r.getValue();
origString = "custom";
}
}
formatString = Utility.SLASHSWEEPstring;
}
field = new PropertyField(GlobalConstants.RNAP_BINDING_STRING, defaultValue, origString, defaultValue, formatString, paramsOnly,
origString, false);
if (production != null) {
LocalParameter ko_f = production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING);
LocalParameter ko_r = production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING);
sweep = AnnotationUtility.parseSweepAnnotation(ko_f);
if (sweep != null) {
field.setValue(sweep);
field.se
// ===== END =====
// ===== BEGIN java =====
package org.basex.query.value.item;
import static org.basex.data.DataText.*;
import org.basex.query.expr.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* String item ({@code xs:string}, {@code xs:normalizedString}, {@code xs:language},
* etc.).
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public class Str extends AStr {
/** Zero-length string. */
public static final Str ZERO = new Str(Token.EMPTY);
/** String data. */
final byte[] val;
/**
* Constructor.
* @param v value
*/
private Str(final byte[] v) {
this(v, AtomType.STR);
}
/**
* Constructor.
* @param v value
* @param t data type
*/
public Str(final byte[] v, final AtomType t) {
super(t);
val = v;
}
/**
* Returns an instance of this class.
* @param v value
* @return instance
*/
public static Str get(final byte[] v) {
return v.length == 0 ? ZERO : new Str(v);
}
/**
* Returns an instance of this class.
* @param v object (will be converted to token)
* @return instance
*/
public static Str get(final Object v) {
return get(Token.token(v.toString()));
}
@Override
public final byte[] string(final InputInfo ii) {
return val;
}
/**
* Returns the string value.
* @return string value
*/
public final byte[] string() {
return val;
}
@Override
public final boolean sameAs(final Expr cmp) {
if(!(cmp instanceof Str)) return false;
final Str i = (Str) cmp;
return type == i.type && Token.eq(val, i.val);
}
@Override
public final String toJava() {
return Token.string(val);
}
@Override
public final String toString() {
final ByteList tb = new ByteList();
tb.add('"');
for(final byte v : val) {
if(v == '&') tb.add(E_AMP);
else tb.add(v);
if(v == '"') tb.add(v);
}
return tb.add('"').toString();
}
}
// ===== END =====
// ===== BEGIN java =====
package senntyou.sbs.mbg.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class AdminRolePermissionRelation implements Serializable {
private Long id;
private Long roleId;
private Long permissionId;
/**
* 创建时间
*
* @mbg.generated
*/
@ApiModelProperty(value = "创建时间")
private Date createTime;
/**
* 更新时间
*
* @mbg.generated
*/
@ApiModelProperty(value = "更新时间")
private Date updateTime;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
this.permissionId = permissionId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", roleId=").append(roleId);
sb.append(", permissionId=").append(permissionId);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
// ===== END =====
// ===== BEGIN java =====
package top.jfunc.http.component;
import top.jfunc.http.request.HttpRequest;
import java.io.IOException;
/**
* 封装真正执行的一步
* @see RequestExecutor
* @author xiongshiyan at 2020/1/6 , contact me with email [email protected] or phone 15208384257
*/
@Deprecated
public interface RequestSender<Request , Response> {
/**
* Request发起请求,得到响应Response
* @param request Request
* @param httpRequest HttpRequest
* @return Response
* @throws IOException IOException
*/
Response send(Request request , HttpRequest httpRequest) throws IOException;
}
// ===== END =====
// ===== BEGIN java =====
package org.gradle.fairy.tale.formula;
import org.gradle.actors.Actor;
import org.gradle.actors.Group;
import org.gradle.fairy.tale.Tale;
import org.gradle.fairy.tale.formula.events.Event;
import org.gradle.fairy.tale.formula.events.IntransativeEvent;
import org.gradle.fairy.tale.formula.events.TransitiveEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Represents a fairy tale.
*/
public class FairyTale implements Tale {
private final List<Actor> actors;
private final List<Event> events;
private FairyTale(List<Actor> actors, List<Event> events) {
this.actors = actors;
this.events = events;
}
@Override
public void tell() {
StringBuilder builder = new StringBuilder("Once upon a time, there lived ");
for (int i=0; i < actors.size(); i++) {
if (i == actors.size() - 1 && i != 0) {
builder.append("and ");
}
builder.append(actors.get(i));
if (i != actors.size() - 1 && actors.size() > 1) {
builder.append(", ");
}
}
builder.append(".").append(System.getProperty("line.separator"));
for (Event event : events) {
builder.append(event).append(System.getProperty("line.separator"));
}
builder.append("And they all lived happily ever after.")
.append(System.getProperty("line.separator"))
.append(System.getProperty("line.separator"));
System.out.print(builder.toString());
}
public static Weaver getWeaver() {
return new Weaver(new HashSet<>(), new HashSet<>(), new ArrayList<>());
}
public static class Weaver {
private final Set<Actor> actorSet;
private final Set<Actor> groupActors;
private final List<Event> events;
private Weaver(Set<Actor> actorSet, Set<Actor> groupActors, List<Event> events) {
this.actorSet = actorSet;
this.groupActors = groupActors;
this.events = events;
}
public Tale weave() {
List<Actor> actors = new ArrayList<>();
actors.addAll(actorSet);
return new FairyTale(actors, events);
}
public Weaver record(Actor actor, String action) {
addActorOrGroup(actor);
events.add(new IntransativeEvent(actor, action));
return this;
}
public Weaver record(Actor actor, String action, Actor object) {
addActorOrGroup(actor);
addActorOrGroup(object);
events.add(new TransitiveEvent(actor, action, object));
return this;
}
private void addActorOrGroup(Actor actor) {
if (actor instanceof Group) {
for(Actor a : (Group) actor) {
actorSet.remove(a);
groupActors.add(a);
}
}
if (!groupActors.contains(actor)) {
actorSet.add(actor);
}
}
}
}
// ===== END =====
// ===== BEGIN java =====
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.directconnect.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.directconnect.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DirectConnectGatewayAttachment JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DirectConnectGatewayAttachmentJsonUnmarshaller implements Unmarshaller<DirectConnectGatewayAttachment, JsonUnmarshallerContext> {
public DirectConnectGatewayAttachment unmarshall(JsonUnmarshallerContext context) throws Exception {
DirectConnectGatewayAttachment directConnectGatewayAttachment = new DirectConnectGatewayAttachment();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("directConnectGatewayId", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setDirectConnectGatewayId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceId", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceRegion", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceRegion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("virtualInterfaceOwnerAccount", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setVirtualInterfaceOwnerAccount(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("attachmentState", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setAttachmentState(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("attachmentType", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setAttachmentType(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("stateChangeError", targetDepth)) {
context.nextToken();
directConnectGatewayAttachment.setStateChangeError(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return directConnectGatewayAttachment;
}
private static DirectConnectGatewayAttachmentJsonUnmarshaller instance;
public static DirectConnectGatewayAttachmentJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DirectConnectGatewayAttachmentJsonUnmarshaller();
return instance;
}
}
// ===== END =====
// ===== BEGIN java =====
// Template Source: IBaseEntityReferenceRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.AndroidForWorkTrustedRootCertificate;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.models.extensions.AndroidForWorkTrustedRootCertificate;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Android For Work Trusted Root Certificate Reference Request Builder.
*/
public interface IAndroidForWorkTrustedRootCertificateReferenceRequestBuilder extends IRequestBuilder {
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the IAndroidForWorkTrustedRootCertificateReferenceRequest instance
*/
IAndroidForWorkTrustedRootCertificateReferenceRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions);
/**
* Creates the request with specific options instead of the existing options
*
* @param requestOptions the options for this request
* @return the IAndroidForWorkTrustedRootCertificateReferenceRequest instance
*/
IAndroidForWorkTrustedRootCertificateReferenceRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions);
}
// ===== END =====
// ===== BEGIN java =====
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
package storagetesting;
public interface StorageTest
{
boolean test();
}
// ===== END =====
// ===== BEGIN java =====
/*
* MIT License
*
* Copyright (c) 2018 octopusdownloader
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.octopus.dialogs.newdownload;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.stage.Stage;
import org.octopus.alerts.CommonAlerts;
import org.octopus.downloads.DownloadInfo;
public class AddNewDownloadDialog extends Dialog<DownloadInfo> {
private ButtonType downloadButtonType;
private AddNewDownloadController controller;
public AddNewDownloadDialog() {
setTitle("Add new download");
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/scenes/dialogs/new-download-dialog.fxml"));
Parent root = loader.load();
controller = loader.getController();
controller.setRoot((Stage) getDialogPane().getScene().getWindow());
downloadButtonType = new ButtonType("Download", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
getDialogPane().getButtonTypes().addAll(downloadButtonType, cancelButtonType);
getDialogPane().setContent(root);
} catch (Exception e) {
Alert alert = CommonAlerts.StackTraceAlert("Error", "Something went wrong", e.getMessage(), e);
alert.showAndWait();
System.exit(1);
}
// TODO validation
setResultConverter(buttonType -> {
if (buttonType == downloadButtonType) {
return new DownloadInfo(controller.getAddress(), controller.getBaseDirectory(), controller.getName());
}
return null;
});
}
}
// ===== END =====
// ===== BEGIN java =====
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.vector.expressions;
import java.util.Arrays;
import org.apache.hadoop.hive.ql.exec.vector.ColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.metadata.HiveException;
/**
* This expression evaluates to true if the given input columns is null.
* The boolean output is stored in the specified output column.
*/
public class IsNull extends VectorExpression {
private static final long serialVersionUID = 1L;
private final int colNum;
public IsNull(int colNum, int outputColumnNum) {
super(outputColumnNum);
this.colNum = colNum;
}
public IsNull() {
super();
// Dummy final assignments.
colNum = -1;
}
@Override
public void evaluate(VectorizedRowBatch batch) throws HiveException {
if (childExpressions != null) {
super.evaluateChildren(batch);
}
ColumnVector inputColVector = batch.cols[colNum];
int[] sel = batch.selected;
boolean[] inputIsNull = inputColVector.isNull;
int n = batch.size;
LongColumnVector outputColVector = (LongColumnVector) batch.cols[outputColumnNum];
long[] outputVector = outputColVector.vector;
boolean[] outputIsNull = outputColVector.isNull;
if (n <= 0) {
// Nothing to do, this is EOF
return;
}
// We do not need to do a column reset since we are carefully changing the output.
outputColVector.isRepeating = false;
if (inputColVector.noNulls) {
outputColVector.isRepeating = true;
outputIsNull[0] = false;
outputVector[0] = 0;
} else if (inputColVector.isRepeating) {
outputColVector.isRepeating = true;
outputIsNull[0] = false;
outputVector[0] = inputIsNull[0] ? 1 : 0;
} else {
/*
* Since we have a result for all rows, we don't need to do conditional NULL maintenance or
* turn off noNulls..
*/
if (batch.selectedInUse) {
for (int j = 0; j != n; j++) {
int i = sel[j];
outputIsNull[i] = false;
outputVector[i] = inputIsNull[i] ? 1 : 0;
}
} else {
Arrays.fill(outputIsNull, 0, n, false);
for (int i = 0; i != n; i++) {
outputVector[i] = inputIsNull[i] ? 1 : 0;
}
}
}
}
@Override
public String vectorExpressionParameters() {
return getColumnParamString(0, colNum);
}
@Override
public VectorExpressionDescriptor.Descriptor getDescriptor() {
VectorExpressionDescriptor.Builder b = new VectorExpressionDescriptor.Builder();
b.setMode(VectorExpressionDescriptor.Mode.PROJECTION)
.setNumArguments(1)
.setArgumentTypes(
VectorExpressionDescriptor.ArgumentType.ALL_FAMILY)
.setInputExpressionTypes(
VectorExpressionDescriptor.InputExpressionType.COLUMN);
return b.build();
}
}
// ===== END =====
// ===== BEGIN java =====
package ink.cashflow.abstractfactory.abztract;
public abstract class AbstractWhiteHuman implements Human {
@Override
public void cry() {
System.out.println("白色人种会哭");
}
@Override
public void laugh() {
System.out.println("白色人种会大笑,侵略的笑声");
}
@Override
public void talk() {
System.out.println("白色人种会说话,一般都是但是单字节!");
}
}
// ===== END =====
// ===== BEGIN java =====
/*
* Copyright (c) 2020, 2021 Microsoft Corporation
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Amadeus - initial API and implementation
*
*/
package org.eclipse.dataspaceconnector.iam.daps;
import org.eclipse.dataspaceconnector.common.annotations.IntegrationTest;
import org.eclipse.dataspaceconnector.core.security.fs.FsCertificateResolver;
import org.eclipse.dataspaceconnector.core.security.fs.FsPrivateKeyResolver;
import org.eclipse.dataspaceconnector.junit.launcher.EdcExtension;
import org.eclipse.dataspaceconnector.junit.launcher.MockVault;
import org.eclipse.dataspaceconnector.spi.EdcException;
import org.eclipse.dataspaceconnector.spi.iam.IdentityService;
import org.eclipse.dataspaceconnector.spi.security.CertificateResolver;
import org.eclipse.dataspaceconnector.spi.security.PrivateKeyResolver;
import org.eclipse.dataspaceconnector.spi.security.Vault;
import org.eclipse.dataspaceconnector.spi.system.ConfigurationExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Map;
import java.util.Objects;
import static org.assertj.core.api.Assertions.assertThat;
@IntegrationTest
@ExtendWith(EdcExtension.class)
class DapsIntegrationTest {
private static final String AUDIENCE_IDS_CONNECTORS_ALL = "idsc:IDS_CONNECTORS_ALL";
private static final String CLIENT_ID = "68:99:2E:D4:13:2D:FD:3A:66:6B:85:DE:FB:98:2E:2D:FD:E7:83:D7";
private static final String CLIENT_KEYSTORE_KEY_ALIAS = "1";
private static final String CLIENT_KEYSTORE_PASSWORD = "1234";
private static final String DAPS_URL = "http://localhost:4567";
private final Map<String, String> configuration = Map.of(
"edc.oauth.token.url", DAPS_URL + "/token",
"edc.oauth.client.id", CLIENT_ID,
"edc.oauth.provider.audience", AUDIENCE_IDS_CONNECTORS_ALL,
"edc.oauth.provider.jwks.url", DAPS_URL + "/.well-known/jwks.json",
"edc.oauth.public.key.alias", CLIENT_KEYSTORE_KEY_ALIAS,
"edc.oauth.private.key.alias", CLIENT_KEYSTORE_KEY_ALIAS
);
private static KeyStore readKeystoreFromResources(String fileName, String type, String password) {
var url = Thread.currentThread().getContextClassLoader().getResource(fileName);
Objects.requireNonNull(url);
try {
var ks = KeyStore.getInstance(type);
var fis = new FileInputStream(url.getFile());
ks.load(fis, password.toCharArray());
return ks;
} catch (Exception e) {
throw new EdcException("Failed to load keystore: " + e);
}
}
@Test
void retrieveTokenAndValidate(IdentityService identityService) {
var tokenResult = identityService.obtainClientCredentials("idsc:IDS_CONNECTOR_ATTRIBUTES_ALL");
assertThat(tokenResult.succeeded()).isTrue();
var verificationResult = identityService.verifyJwtToken(tokenResult.getContent().getToken(), AUDIENCE_IDS_CONNECTORS_ALL);
assertThat(verificationResult.succeeded()).isTrue();
}
@BeforeEach
protected void before(EdcExtension extension) {
KeyStore clientKeystore = readKeystoreFromResources("keystore.p12", "PKCS12", CLIENT_KEYSTORE_PASSWORD);
extension.registerSystemExtension(ConfigurationExtension.class, (ConfigurationExtension) configuration::get);
extension.registerServiceMock(Vault.class, new MockVault());
extension.registerServiceMock(PrivateKeyResolver.class, new FsPrivateKeyResolver(CLIENT_KEYSTORE_PASSWORD, clientKeystore));
extension.registerServiceMock(CertificateResolver.class, new FsCertificateResolver(clientKeystore));
}
}
// ===== END =====
// ===== BEGIN java =====
package pl.allegro.tech.hermes.integration.auth;
import avro.shaded.com.google.common.collect.Lists;
import com.google.common.io.Files;
import io.undertow.security.impl.BasicAuthenticationMechanism;
import io.undertow.util.StatusCodes;
import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import pl.allegro.tech.hermes.api.Topic;
import pl.allegro.tech.hermes.common.config.ConfigFactory;
import pl.allegro.tech.hermes.common.config.Configs;
import pl.allegro.tech.hermes.frontend.HermesFrontend;
import pl.allegro.tech.hermes.frontend.server.auth.AuthenticationConfiguration;
import pl.allegro.tech.hermes.integration.IntegrationTest;
import pl.allegro.tech.hermes.test.helper.builder.TopicBuilder;
import pl.allegro.tech.hermes.test.helper.config.MutableConfigFactory;
import pl.allegro.tech.hermes.test.helper.endpoint.HermesPublisher;
import pl.allegro.tech.hermes.test.helper.message.TestMessage;
import pl.allegro.tech.hermes.test.helper.util.Ports;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static pl.allegro.tech.hermes.integration.auth.SingleUserAwareIdentityManager.getHeadersWithAuthentication;
import static pl.allegro.tech.hermes.integration.test.HermesAssertions.assertThat;
public class TopicAuthorisationTest extends IntegrationTest {
public static final int FRONTEND_PORT = Ports.nextAvailable();
public static final String FRONTEND_URL = "http://127.0.0.1:" + FRONTEND_PORT;
private static final String USERNAME = "someUser";
private static final String PASSWORD = "somePassword123";
private static final String MESSAGE = TestMessage.of("hello", "world").body();
private static final String USERNAME2 = "foobar";
protected HermesPublisher publisher;
private HermesFrontend hermesFrontend;
@BeforeClass
public void setup() throws Exception {
ConfigFactory configFactory = new MutableConfigFactory()
.overrideProperty(Configs.FRONTEND_PORT, FRONTEND_PORT)
.overrideProperty(Configs.FRONTEND_SSL_ENABLED, false)
.overrideProperty(Configs.FRONTEND_AUTHENTICATION_MODE, "pro_active")
.overrideProperty(Configs.FRONTEND_AUTHENTICATION_ENABLED, true)
.overrideProperty(Configs.MESSAGES_LOCAL_STORAGE_DIRECTORY, Files.createTempDir().getAbsolutePath());
AuthenticationConfiguration authConfig = new AuthenticationConfiguration(
exchange -> false,
Lists.newArrayList(new BasicAuthenticationMechanism("basicAuthRealm")),
new SingleUserAwareIdentityManager(USERNAME, PASSWORD));
hermesFrontend = HermesFrontend.frontend()
.withBinding(configFactory, ConfigFactory.class)
.withAuthenticationConfiguration(authConfig)
.build();
hermesFrontend.start();
publisher = new HermesPublisher(FRONTEND_URL);
operations.buildTopic("someGroup", "topicWithAuthorization");
}
@AfterClass
public void tearDown() throws InterruptedException {
hermesFrontend.stop();
}
@Test
public void shouldPublishWhenAuthenticated() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("disabled.authenticated")
.build(),
TopicBuilder.topic("enabled.authenticated_1Publisher")
.withPublisher(USERNAME)
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.authenticated_2Publishers")
.withPublisher(USERNAME)
.withPublisher(USERNAME2)
.withAuthEnabled()
.build(),
TopicBuilder.topic("required.authenticated_1Publisher")
.withPublisher(USERNAME)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.authenticated_2Publishers")
.withPublisher(USERNAME)
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
Map<String, String> headers = getHeadersWithAuthentication(USERNAME, PASSWORD);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE, headers);
// then
assertThat(response.getStatusInfo().getFamily()).as(description(topic)).isEqualTo(SUCCESSFUL);
});
}
@Test
public void shouldPublishAsGuestWhenAuthIsNotRequired() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("disabled.guest")
.build(),
TopicBuilder.topic("enabled.guest_0Publishers")
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.guest_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.build()
);
topics.forEach(operations::buildTopic);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE);
// then
assertThat(response.getStatusInfo().getFamily()).as(description(topic)).isEqualTo(SUCCESSFUL);
});
}
@Test
public void shouldNotPublishAsGuestWhenAuthIsRequired() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("required.guest_0Publishers")
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.guest_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
topics.forEach(topic -> {
// when
Response response = publisher.publish(topic.getQualifiedName(), MESSAGE);
// then
assertThat(response.getStatus()).as(description(topic)).isEqualTo(StatusCodes.FORBIDDEN);
});
}
@Test
public void shouldNotPublishWithoutPermissionWhenAuthenticated() {
// given
List<Topic> topics = Arrays.asList(
TopicBuilder.topic("enabled.authenticated_no_permission_0Publishers")
.withAuthEnabled()
.build(),
TopicBuilder.topic("enabled.authenticated_no_permission_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.build(),
TopicBuilder.topic("required.authenticated_no_permission_0Publishers")
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build(),
TopicBuilder.topic("required.authenticated_no_permission_1Publisher")
.withPublisher(USERNAME2)
.withAuthEnabled()
.withUnauthenticatedAccessDisabled()
.build()
);
topics.forEach(operations::buildTopic);
Map<String, String> headers = getHeadersWith
// ===== END =====
// ===== BEGIN java =====
/*
* Copyright 2013, The Sporting Exchange Limited
*
* 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.
*/
// Originally from UpdatedComponentTests/StandardValidation/REST/Rest_Post_MissingMandatory_ListOfComplex_JSON.xls;
package com.betfair.cougar.tests.updatedcomponenttests.standardvalidation.rest;
import com.betfair.testing.utils.cougar.misc.XMLHelpers;
import com.betfair.testing.utils.cougar.assertions.AssertionUtils;
import com.betfair.testing.utils.cougar.beans.HttpCallBean;
import com.betfair.testing.utils.cougar.beans.HttpResponseBean;
import com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum;
import com.betfair.testing.utils.cougar.manager.AccessLogRequirement;
import com.betfair.testing.utils.cougar.manager.CougarManager;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
/**
* Ensure that the correct fault is returned when, a Rest(JSON) Post operation is performed against Cougar, passing a List of complex object in the post body, where the complex object contained in the list has a mandatory field missing
*/
public class RestPostMissingMandatoryListOfComplexJSONTest {
@Test
public void doTest() throws Exception {
// Set up the Http Call Bean to make the request
CougarManager cougarManager1 = CougarManager.getInstance();
HttpCallBean getNewHttpCallBean1 = cougarManager1.getNewHttpCallBean("87.248.113.14");
cougarManager1 = cougarManager1;
// Turn detailed faults off
cougarManager1.setCougarFaultControllerJMXMBeanAttrbiute("DetailedFaults", "false");
getNewHttpCallBean1.setOperationName("listOfComplexOperation");
getNewHttpCallBean1.setServiceName("baseline", "cougarBaseline");
getNewHttpCallBean1.setVersion("v2");
// Set the body param to a list of complex objects where one of the entries is missing mandatory fields
Map map2 = new HashMap();
map2.put("RESTJSON","{\"inputList\": [{\"ComplexObject\":{}}]}");
getNewHttpCallBean1.setPostQueryObjects(map2);
// Get current time for getting log entries later
Timestamp getTimeAsTimeStamp7 = new Timestamp(System.currentTimeMillis());
// Make REST JSON call to the operation requesting an XML response
cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.XML);
// Make REST JSON call to the operation requesting a JSON response
cougarManager1.makeRestCougarHTTPCall(getNewHttpCallBean1, com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum.RESTJSON, com.betfair.testing.utils.cougar.enums.CougarMessageContentTypeEnum.JSON);
// Create the expected response as an XML document (Fault)
XMLHelpers xMLHelpers4 = new XMLHelpers();
Document createAsDocument12 = xMLHelpers4.getXMLObjectFromString("<fault><faultcode>Client</faultcode><faultstring>DSC-0018</faultstring><detail/></fault>");
// Convert the expected response to REST types for comparison with actual responses
Map<CougarMessageProtocolRequestTypeEnum, Object> convertResponseToRestTypes13 = cougarManager1.convertResponseToRestTypes(createAsDocument12, getNewHttpCallBean1);
// Check the 2 responses are as expected (Bad Request)
HttpResponseBean response5 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONXML);
AssertionUtils.multiAssertEquals(convertResponseToRestTypes13.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response5.getResponseObject());
AssertionUtils.multiAssertEquals((int) 400, response5.getHttpStatusCode());
AssertionUtils.multiAssertEquals("Bad Request", response5.getHttpStatusText());
HttpResponseBean response6 = getNewHttpCallBean1.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON);
AssertionUtils.multiAssertEquals(convertResponseToRestTypes13.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response6.getResponseObject());
AssertionUtils.multiAssertEquals((int) 400, response6.getHttpStatusCode());
AssertionUtils.multiAssertEquals("Bad Request", response6.getHttpStatusText());
// generalHelpers.pauseTest(500L);
// Check the log entries are as expected
cougarManager1.verifyAccessLogEntriesAfterDate(getTimeAsTimeStamp7, new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/listOfComplexOperation", "BadRequest"),new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/listOfComplexOperation", "BadRequest") );
}
}
// ===== END =====
// ===== BEGIN java =====
package com.tamsiree.rxkit;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author tamsiree
* @date 2016/1/24
*/
public class RxBarTool {
/**
* 隐藏状态栏
* <p>也就是设置全屏,一定要在setContentView之前调用,否则报错</p>
* <p>此方法Activity可以继承AppCompatActivity</p>
* <p>启动的时候状态栏会显示一下再隐藏,比如QQ的欢迎界面</p>
* <p>在配置文件中Activity加属性android:theme="@android:style/Theme.NoTitleBar.Fullscreen"</p>
* <p>如加了以上配置Activity不能继承AppCompatActivity,会报错</p>
*
* @param activity activity
*/
public static void hideStatusBar(Activity activity) {
noTitle(activity);
FLAG_FULLSCREEN(activity);
}
/**
* 设置透明状态栏(api大于19方可使用)
* <p>可在Activity的onCreat()中调用</p>
* <p>需在顶部控件布局中加入以下属性让内容出现在状态栏之下</p>
* <p>android:clipToPadding="true"</p>
* <p>android:fitsSystemWindows="true"</p>
*
* @param activity activity
*/
public static void setTransparentStatusBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明状态栏
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //透明导航栏
}
}
/**
* 隐藏Title
* 一定要在setContentView之前调用,否则报错
*
* @param activity
*/
public static void setNoTitle(Activity activity) {
activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
public static void noTitle(Activity activity) {
setNoTitle(activity);
}
/**
* 全屏
* 也就是设置全屏,一定要在setContentView之前调用,否则报错
*
* @param activity
*/
public static void FLAG_FULLSCREEN(Activity activity) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* 获取状态栏高度
*
* @param context 上下文
* @return 状态栏高度
*/
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 判断状态栏是否存在
*
* @param activity activity
* @return {@code true}: 存在<br>{@code false}: 不存在
*/
public static boolean isStatusBarExists(Activity activity) {
WindowManager.LayoutParams params = activity.getWindow().getAttributes();
return (params.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
/**
* 获取ActionBar高度
*
* @param activity activity
* @return ActionBar高度
*/
public static int getActionBarHeight(Activity activity) {
TypedValue tv = new TypedValue();
if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
}
return 0;
}
/**
* 显示通知栏
* <p>需添加权限 {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>}</p>
*
* @param context 上下文
* @param isSettingPanel {@code true}: 打开设置<br>{@code false}: 打开通知
*/
public static void showNotificationBar(Context context, boolean isSettingPanel) {
String methodName = (Build.VERSION.SDK_INT <= 16) ? "expand"
: (isSettingPanel ? "expandSettingsPanel" : "expandNotificationsPanel");
invokePanels(context, methodName);
}
/**
* 隐藏通知栏
* <p>需添加权限 {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>}</p>
*
* @param context 上下文
*/
public static void hideNotificationBar(Context context) {
String methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels";
invokePanels(context, methodName);
}
/**
* 反射唤醒通知栏
*
* @param context 上下文
* @param methodName 方法名
*/
private static void invokePanels(Context context, String methodName) {
try {
Object service = context.getSystemService("statusbar");
Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
Method expand = statusBarManager.getMethod(methodName);
expand.invoke(service);
} catch (Exception e) {
e.printStackTrace();
}
}
//==============================================================================================以下设置状态栏相关
/**
* 需要在布局中加入
android:clipToPadding="true"
android:fitsSystemWindows="true"
* 这两行属性
*/
/**
* 修改状态栏为全透明
*
* @param activity
*/
@TargetApi(19)
public static void transparencyBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = activity.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* 修改状态栏颜色,支持4.4以上版本
*
* @param activity
* @param colorId
*/
public static void setStatusBarColor(Activity activity, int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(activity.getResources().getColor(colorId));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//使用SystemBarTint库使4.4版本状态栏变色,需要先将状态栏设置为透明
transparencyBar(activity);
SystemBarTintManager tintManager = new SystemBarTintManager(activity);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(colorId);
}
}
/**
* 设置状态栏黑色字体图标,
* 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
*
* @param activity
* @return 1:MIUUI 2:Flyme 3:android6.0
*/
public static int StatusBarLightMode(Activity activity) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (MIUISetStatusBarLightMode(activity.getWindow(), true)) {
result = 1;
} else if (FlymeSetStatusBarLightMode(activity.getWindow(), true)) {
result = 2;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
result = 3;
}
}
return result;
}
/**
* 已知系统类型时,设置状态栏黑色字体图标。
* 适配4
// ===== END =====
// ===== BEGIN c++ =====
/* Copyright (c) 2020 UATC, LLC
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.
*/
#pragma once
#include "neuropod/internal/memory_utils.hh"
#include "neuropod/internal/tensor_types.hh"
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
namespace neuropod
{
// Device types that are supported in the Neuropod configuration
typedef int NeuropodDeviceType;
namespace DeviceType
{
constexpr int CPU = 0;
constexpr int GPU = 1;
}; // namespace DeviceType
// A struct that stores the value of a dimension
struct Dimension
{
Dimension(int64_t value);
Dimension(std::string symbol);
~Dimension();
bool operator==(const Dimension &other) const;
// The value
// -1 == Any value is allowed (None/null)
// -2 == Symbol
int64_t value;
// The name of this symbol (if it is a symbol)
std::string symbol;
};
// A struct that stores a specification for a tensor
struct TensorSpec
{
TensorSpec(const std::string &name, const std::vector<Dimension> dims, const TensorType type);
~TensorSpec();
const std::string name;
const std::vector<Dimension> dims;
const TensorType type;
};
// A struct that stores the expected inputs and outputs of a model
struct ModelConfig
{
const std::string name;
const std::string platform;
// The requested versions of the platform specified as a semver range
// e.g. `1.13.1` or `> 1.13.1`
// See the following URLs for examples and more info:
// - https://semver.org/
// - https://docs.npmjs.com/misc/semver#ranges
// - https://docs.npmjs.com/misc/semver#advanced-range-syntax
const std::string platform_version_semver;
const std::vector<TensorSpec> inputs;
const std::vector<TensorSpec> outputs;
const std::vector<std::string> custom_ops;
// A map from an input tensor name to a device type
const std::unordered_map<std::string, NeuropodDeviceType> input_tensor_device;
};
std::unique_ptr<ModelConfig> load_model_config(const std::string &neuropod_path);
std::unique_ptr<ModelConfig> load_model_config(std::istream &input_stream);
} // namespace neuropod
// ===== END =====
// ===== BEGIN c++ =====
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcComplexPropertyTemplate.h"
#include "ifcpp/IFC4/include/IfcComplexPropertyTemplateTypeEnum.h"
#include "ifcpp/IFC4/include/IfcGloballyUniqueId.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
#include "ifcpp/IFC4/include/IfcOwnerHistory.h"
#include "ifcpp/IFC4/include/IfcPropertySetTemplate.h"
#include "ifcpp/IFC4/include/IfcPropertyTemplate.h"
#include "ifcpp/IFC4/include/IfcRelAssociates.h"
#include "ifcpp/IFC4/include/IfcRelDeclares.h"
#include "ifcpp/IFC4/include/IfcText.h"
// ENTITY IfcComplexPropertyTemplate
IfcComplexPropertyTemplate::IfcComplexPropertyTemplate() {}
IfcComplexPropertyTemplate::IfcComplexPropertyTemplate( int id ) { m_entity_id = id; }
IfcComplexPropertyTemplate::~IfcComplexPropertyTemplate() {}
shared_ptr<BuildingObject> IfcComplexPropertyTemplate::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcComplexPropertyTemplate> copy_self( new IfcComplexPropertyTemplate() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createBase64Uuid<wchar_t>().data() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_UsageName ) { copy_self->m_UsageName = dynamic_pointer_cast<IfcLabel>( m_UsageName->getDeepCopy(options) ); }
if( m_TemplateType ) { copy_self->m_TemplateType = dynamic_pointer_cast<IfcComplexPropertyTemplateTypeEnum>( m_TemplateType->getDeepCopy(options) ); }
for( size_t ii=0; ii<m_HasPropertyTemplates.size(); ++ii )
{
auto item_ii = m_HasPropertyTemplates[ii];
if( item_ii )
{
copy_self->m_HasPropertyTemplates.push_back( dynamic_pointer_cast<IfcPropertyTemplate>(item_ii->getDeepCopy(options) ) );
}
}
return copy_self;
}
void IfcComplexPropertyTemplate::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCCOMPLEXPROPERTYTEMPLATE" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_UsageName ) { m_UsageName->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_TemplateType ) { m_TemplateType->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
writeEntityList( stream, m_HasPropertyTemplates );
stream << ");";
}
void IfcComplexPropertyTemplate::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcComplexPropertyTemplate::toString() const { return L"IfcComplexPropertyTemplate"; }
void IfcComplexPropertyTemplate::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 7 ){ std::stringstream err; err << "Wrong parameter count for entity IfcComplexPropertyTemplate, expecting 7, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2], map );
m_Description = IfcText::createObjectFromSTEP( args[3], map );
m_UsageName = IfcLabel::createObjectFromSTEP( args[4], map );
m_TemplateType = IfcComplexPropertyTemplateTypeEnum::createObjectFromSTEP( args[5], map );
readEntityReferenceList( args[6], m_HasPropertyTemplates, map );
}
void IfcComplexPropertyTemplate::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )
{
IfcPropertyTemplate::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "UsageName", m_UsageName ) );
vec_attributes.push_back( std::make_pair( "TemplateType", m_TemplateType ) );
if( m_HasPropertyTemplates.size() > 0 )
{
shared_ptr<AttributeObjectVector> HasPropertyTemplates_vec_object( new AttributeObjectVector() );
std::copy( m_HasPropertyTemplates.begin(), m_HasPropertyTemplates.end(), std::back_inserter( HasPropertyTemplates_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "HasPropertyTemplates", HasPropertyTemplates_vec_object ) );
}
}
void IfcComplexPropertyTemplate::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )
{
IfcPropertyTemplate::getAttributesInverse( vec_attributes_inverse );
}
void IfcComplexPropertyTemplate::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcPropertyTemplate::setInverseCounterparts( ptr_self_entity );
shared_ptr<IfcComplexPropertyTemplate> ptr_self = dynamic_pointer_cast<IfcComplexPropertyTemplate>( ptr_self_entity );
if( !ptr_self ) { throw BuildingException( "IfcComplexPropertyTemplate::setInverseCounterparts: type mismatch" ); }
for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i )
{
if( m_HasPropertyTemplates[i] )
{
m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse.push_back( ptr_self );
}
}
}
void IfcComplexPropertyTemplate::unlinkFromInverseCounterparts()
{
IfcPropertyTemplate::unlinkFromInverseCounterparts();
for( size_t i=0; i<m_HasPropertyTemplates.size(); ++i )
{
if( m_HasPropertyTemplates[i] )
{
std::vector<weak_ptr<IfcComplexPropertyTemplate> >& PartOfComplexTemplate_inverse = m_HasPropertyTemplates[i]->m_PartOfComplexTemplate_inverse;
for( auto it_PartOfComplexTemplate_inverse = PartOfComplexTemplate_inverse.begin(); it_PartOfComplexTemplate_inverse != PartOfComplexTemplate_inverse.end(); )
{
weak_ptr<IfcComplexPropertyTemplate> self_candidate_weak = *it_PartOfComplexTemplate_inverse;
if( self_candidate_weak.expired() )
{
++it_PartOfComplexTemplate_inverse;
continue;
}
shared_ptr<IfcComplexPropertyTemplate> self_candidate( *it_PartOfComplexTemplate_inverse );
if( self_candidate.get() == this )
{
it_PartOfComplexTemplate_inverse= PartOfComplexTemplate_inverse.erase( it_PartOfComplexTemplate_inverse );
}
else
{
++it_PartOfComplexTemplate_inverse;
}
}
}
}
}
// ===== END =====
// ===== BEGIN c++ =====
//----------------------------------------------------------------------
// Copyright 2004-2011 Synopsys, Inc.
// Copyright 2010 Mentor Graphics Corporation
// Copyright 2010-2011 Cadence Design Systems, Inc.
// Copyright 2013-2014 NXP B.V.
// All Rights Reserved Worldwide
//
// 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.
//----------------------------------------------------------------------
#include <systemc>
#include <uvm>
#include "tb_env.h"
#include "tb_test.h"
//----------------------------------------------------------------------
// This example demonstrates how to model a register containing
// read-only fields and a register containing write-only fields
// at the same physical address.
//----------------------------------------------------------------------
int sc_main(int, char*[])
{
tb_env* env;
tb_test* test;
env = new tb_env("env");
test = new tb_test("test");
uvm::uvm_root::get()->set_report_verbosity_level(uvm::UVM_FULL);
test->set_report_verbosity_level(uvm::UVM_FULL);
env->set_report_verbosity_level(uvm::UVM_FULL);
uvm::uvm_report_server::get_server()->set_max_quit_count(10);
uvm::run_test();
delete env;
delete test;
return 0;
}
// ===== END =====
// ===== BEGIN c++ =====
#include <bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
typedef long long ll;typedef long double ld;typedef pair<int,int> pii;
#define F first
#define S second
#define PB push_back
#define MP make_pair
const ll mod = 1e9+7, N = 2e6+7, M = 2e6+7, INF = INT_MAX/10;
ll powe(ll x, ll y){ x = x%mod, y=y%(mod-1);ll ans = 1;while(y>0){if (y&1){ans = (1ll * x * ans)%mod;}y>>=1;x = (1ll * x * x)%mod;}return ans;}
//Sum Of the elements of an array
void input_of_array(int arr[],int n)
{
for (int i =0;i<n;i++)
{
cin>>arr[i];
}
}
void rotating_the_array(int arr[], int n)
{
int m;
cin>>m;
for(int i=0;i<m;i++)
{
int temp =arr[0];
for(int j=0;j<n;j++)
{
if(j==n-1)
{
arr[j]=temp;
}
else
{
arr[j]=arr[j+1];
}
}
}
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void solve(){
int arr[100];
int n;
cin>>n;
input_of_array(arr,n);
rotating_the_array(arr,n);
}
signed main(){
fast;
int t = 1;
while(t--){
solve();
}
return 0;
}
// ===== END =====
// ===== BEGIN c++ =====
// Copyright (c) 2011-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/recentrequeststablemodel.h>
#include <qt/bitcoinunits.h>
#include <qt/guiutil.h>
#include <qt/optionsmodel.h>
#include <algorithm>
#include <clientversion.h>
#include <streams.h>
RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) :
QAbstractTableModel(parent), walletModel(parent)
{
nReceiveRequestsMaxId = 0;
// Load entries from wallet
std::vector<std::string> vReceiveRequests;
parent->loadReceiveRequests(vReceiveRequests);
for (const std::string& request : vReceiveRequests)
addNewRequest(request);
/* These columns must match the indices in the ColumnIndex enumeration */
columns << tr("Date") << tr("Label") << tr("Message") << getAmountTitle();
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
RecentRequestsTableModel::~RecentRequestsTableModel()
{
/* Intentionally left empty */
}
int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return list.length();
}
int RecentRequestsTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid() || index.row() >= list.length())
return QVariant();
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
const RecentRequestEntry *rec = &list[index.row()];
switch(index.column())
{
case Date:
return GUIUtil::dateTimeStr(rec->date);
case Label:
if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->recipient.label;
}
case Message:
if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no message)");
}
else
{
return rec->recipient.message;
}
case Amount:
if (rec->recipient.amount == 0 && role == Qt::DisplayRole)
return tr("(no amount requested)");
else if (role == Qt::EditRole)
return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount, false, BitcoinUnits::separatorNever);
else
return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount);
}
}
else if (role == Qt::TextAlignmentRole)
{
if (index.column() == Amount)
return (int)(Qt::AlignRight|Qt::AlignVCenter);
}
return QVariant();
}
bool RecentRequestsTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return true;
}
QVariant RecentRequestsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void RecentRequestsTableModel::updateAmountColumnTitle()
{
columns[Amount] = getAmountTitle();
Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount);
}
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString RecentRequestsTableModel::getAmountTitle()
{
return (this->walletModel->getOptionsModel() != nullptr) ? tr("Requested") + " ("+BitcoinUnits::shortName(this->walletModel->getOptionsModel()->getDisplayUnit()) + ")" : "";
}
QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
return createIndex(row, column);
}
bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
if(count > 0 && row >= 0 && (row+count) <= list.size())
{
for (int i = 0; i < count; ++i)
{
const RecentRequestEntry* rec = &list[row+i];
if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, ""))
return false;
}
beginRemoveRows(parent, row, row + count - 1);
list.erase(list.begin() + row, list.begin() + row + count);
endRemoveRows();
return true;
} else {
return false;
}
}
Qt::ItemFlags RecentRequestsTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
// called when adding a request from the GUI
void RecentRequestsTableModel::addNewRequest(const SendCoinsRecipient &recipient)
{
RecentRequestEntry newEntry;
newEntry.id = ++nReceiveRequestsMaxId;
newEntry.date = QDateTime::currentDateTime();
newEntry.recipient = recipient;
CDataStream ss(SER_DISK, CLIENT_VERSION);
ss << newEntry;
if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str()))
return;
addNewRequest(newEntry);
}
// called from ctor when loading from wallet
void RecentRequestsTableModel::addNewRequest(const std::string &recipient)
{
std::vector<char> data(recipient.begin(), recipient.end());
CDataStream ss(data, SER_DISK, CLIENT_VERSION);
RecentRequestEntry entry;
ss >> entry;
if (entry.id == 0) // should not happen
return;
if (entry.id > nReceiveRequestsMaxId)
nReceiveRequestsMaxId = entry.id;
addNewRequest(entry);
}
// actually add to table in GUI
void RecentRequestsTableModel::addNewRequest(RecentRequestEntry &recipient)
{
beginInsertRows(QModelIndex(), 0, 0);
list.prepend(recipient);
endInsertRows();
}
void RecentRequestsTableModel::sort(int column, Qt::SortOrder order)
{
std::sort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order));
Q_EMIT dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex()));
}
void RecentRequestsTableModel::updateDisplayUnit()
{
updateAmountColumnTitle();
}
bool RecentRequestEntryLessThan::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const
{
RecentRequestEntry *pLeft = &left;
RecentRequestEntry *pRight = &right;
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch(column)
{
case RecentRequestsTableModel::Date:
return pLeft->date.toTime_t() < pRight->date.toTime_t();
case RecentRequestsTableModel::Label:
return pLeft->recipient.label < pRight->recipient.label;
case RecentRequestsTableModel::Message:
return pLeft->recipient.message < pRight->recipient.message;
case RecentRequestsTableModel::Amount:
return pLeft->recipient.amount < pRight->recipient.amount;
default:
return pLeft->id < pRight->id;
}
}
// ===== END =====
// ===== BEGIN c++ =====
//HEADER_GOES_HERE
#include "../types.h"
int invflag;
void *pInvCels;
int drawsbarflag; // idb
int sgdwLastTime; // check name
const InvXY InvRect[73] =
{
{ 452, 31 }, // helmet
{ 480, 31 }, // helmet
{ 452, 59 }, // helmet
{ 480, 59 }, // helmet
{ 365, 205 }, // left ring
{ 567, 205 }, // right ring
{ 524, 59 }, // amulet
{ 337, 104 }, // left hand
{ 366, 104 }, // left hand
{ 337, 132 }, // left hand
{ 366, 132 }, // left hand
{ 337, 160 }, // left hand
{ 366, 160 }, // left hand
{ 567, 104 }, // right hand
{ 596, 104 }, // right hand
{ 567, 132 }, // right hand
{ 596, 132 }, // right hand
{ 567, 160 }, // right hand
{ 596, 160 }, // right hand
{ 452, 104 }, // chest
{ 480, 104 }, // chest
{ 452, 132 }, // chest
{ 480, 132 }, // chest
{ 452, 160 }, // chest
{ 480, 160 }, // chest
{ 337, 250 }, // inv row 1
{ 366, 250 }, // inv row 1
{ 394, 250 }, // inv row 1
{ 423, 250 }, // inv row 1
{ 451, 250 }, // inv row 1
{ 480, 250 }, // inv row 1
{ 509, 250 }, // inv row 1
{ 538, 250 }, // inv row 1
{ 567, 250 }, // inv row 1
{ 596, 250 }, // inv row 1
{ 337, 279 }, // inv row 2
{ 366, 279 }, // inv row 2
{ 394, 279 }, // inv row 2
{ 423, 279 }, // inv row 2
{ 451, 279 }, // inv row 2
{ 480, 279 }, // inv row 2
{ 509, 279 }, // inv row 2
{ 538, 279 }, // inv row 2
{ 567, 279 }, // inv row 2
{ 596, 279 }, // inv row 2
{ 337, 308 }, // inv row 3
{ 366, 308 }, // inv row 3
{ 394, 308 }, // inv row 3
{ 423, 308 }, // inv row 3
{ 451, 308 }, // inv row 3
{ 480, 308 }, // inv row 3
{ 509, 308 }, // inv row 3
{ 538, 308 }, // inv row 3
{ 567, 308 }, // inv row 3
{ 596, 308 }, // inv row 3
{ 337, 336 }, // inv row 4
{ 366, 336 }, // inv row 4
{ 394, 336 }, // inv row 4
{ 423, 336 }, // inv row 4
{ 451, 336 }, // inv row 4
{ 480, 336 }, // inv row 4
{ 509, 336 }, // inv row 4
{ 538, 336 }, // inv row 4
{ 567, 336 }, // inv row 4
{ 596, 336 }, // inv row 4
{ 205, 385 }, // belt
{ 234, 385 }, // belt
{ 263, 385 }, // belt
{ 292, 385 }, // belt
{ 321, 385 }, // belt
{ 350, 385 }, // belt
{ 379, 385 }, // belt
{ 408, 385 } // belt
};
/* data */
int AP2x2Tbl[10] = { 8, 28, 6, 26, 4, 24, 2, 22, 0, 20 }; // weak
void __cdecl FreeInvGFX()
{
void *invCels = pInvCels;
pInvCels = NULL;
mem_free_dbg(invCels);
}
void __cdecl InitInv()
{
if ( plr[myplr]._pClass == PC_WARRIOR )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv.CEL", 0);
}
else if ( plr[myplr]._pClass == PC_ROGUE )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv_rog.CEL", 0);
}
else if ( plr[myplr]._pClass == PC_SORCERER )
{
pInvCels = LoadFileInMem("Data\\Inv\\Inv_Sor.CEL", 0);
}
invflag = 0;
drawsbarflag = 0;
}
void __fastcall InvDrawSlotBack(int X, int Y, int W, int H)
{
unsigned char *v4; // edi
int v5; // edx
int v6; // ecx
unsigned char v7; // al
unsigned char v8; // al
v4 = (unsigned char *)gpBuffer + screen_y_times_768[Y] + X;
v5 = (unsigned short)H;
do
{
v6 = (unsigned short)W;
do
{
v7 = *v4;
if ( *v4 < 0xB0u )
goto LABEL_9;
if ( v7 > 0xBFu )
{
if ( v7 < 0xF0u )
goto LABEL_9;
v8 = v7 - 80;
}
else
{
v8 = v7 - 16;
}
*v4 = v8;
LABEL_9:
++v4;
--v6;
}
while ( v6 );
v4 = &v4[-(unsigned short)W - 768];
--v5;
}
while ( v5 );
}
void __cdecl DrawInv()
{
BOOL invtest[40];
CelDecodeOnly(384, 511, pInvCels, 1, 320);
if ( plr[myplr].InvBody[INVLOC_HEAD]._itype != ITYPE_NONE )
{
InvDrawSlotBack(517, 219, 2 * INV_SLOT_SIZE_PX, 2 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_HEAD]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_HEAD )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_HEAD]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 517, 219, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_HEAD]._iStatFlag )
{
CelDrawHdrOnly(517, 219, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(517, 219, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(432, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_RING_LEFT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_RING_LEFT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 432, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_RING_LEFT]._iStatFlag )
{
CelDrawHdrOnly(432, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(432, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(633, 365, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_RING_RIGHT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_RING_RIGHT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 633, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_RING_RIGHT]._iStatFlag )
{
CelDrawHdrOnly(633, 365, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(633, 365, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_AMULET]._itype != ITYPE_NONE )
{
InvDrawSlotBack(589, 220, INV_SLOT_SIZE_PX, INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_AMULET]._iCurs + 12;
int frame_width = InvItemWidth[frame];
if ( pcursinvitem == INVITEM_AMULET )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_AMULET]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, 589, 220, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_AMULET]._iStatFlag )
{
CelDrawHdrOnly(589, 220, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(589, 220, (char *)pCursCels, frame, frame_width, 0, 8, 1);
}
}
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._itype != ITYPE_NONE )
{
InvDrawSlotBack(401, 320, 2 * INV_SLOT_SIZE_PX, 3 * INV_SLOT_SIZE_PX);
int frame = plr[myplr].InvBody[INVLOC_HAND_LEFT]._iCurs + 12;
int frame_width = InvItemWidth[frame];
// calc item offsets for weapons smaller than 2x3 slots
int screen_x = frame_width == INV_SLOT_SIZE_PX ? 415 : 401;
int screen_y = InvItemHeight[frame] == (3 * INV_SLOT_SIZE_PX) ? 320 : 306;
if ( pcursinvitem == INVITEM_HAND_LEFT )
{
int colour = 197;
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iMagical )
{
colour = 181;
}
if ( !plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag )
{
colour = 229;
}
CelDecodeClr(colour, screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
if ( plr[myplr].InvBody[INVLOC_HAND_LEFT]._iStatFlag )
{
CelDrawHdrOnly(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8);
}
else
{
CelDrawHdrLightRed(screen_x, screen_y, (char *)pCursCels, frame, frame_width, 0, 8, 1);
// ===== END =====
// ===== BEGIN c++ =====
#include <boost/metaparse/one_of_c.hpp>
// ===== END =====
// ===== BEGIN c++ =====
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The nativecoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include "chainparams.h"
#include "primitives/transaction.h"
#include <QSettings>
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(N8V);
unitlist.append(mN8V);
unitlist.append(uN8V);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch (unit) {
case N8V:
case mN8V:
case uN8V:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch (unit) {
case N8V:
return QString("NativeCoin");
case mN8V:
return QString("mNativeCoin");
case uN8V:
return QString::fromUtf8("uNativeCoin");
default:
return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case N8V:
return QString("N8V");
case mN8V:
return QString("mN8V");
case uN8V:
return QString::fromUtf8("μN8V");
default:
return QString("???");
}
} else {
switch (unit) {
case N8V:
return QString("tN8V");
case mN8V:
return QString("mtN8V");
case uN8V:
return QString::fromUtf8("μtN8V");
default:
return QString("???");
}
}
}
QString BitcoinUnits::description(int unit)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case N8V:
return QString("N8V");
case mN8V:
return QString("Milli-N8V (1 / 1" THIN_SP_UTF8 "000)");
case uN8V:
return QString("Micro-N8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
} else {
switch (unit) {
case N8V:
return QString("TestN8Vs");
case mN8V:
return QString("Milli-TestN8V (1 / 1" THIN_SP_UTF8 "000)");
case uN8V:
return QString("Micro-TestN8V (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch (unit) {
case N8V:
return 100000000;
case mN8V:
return 100000;
case uN8V:
return 100;
default:
return 100000000;
}
}
int BitcoinUnits::decimals(int unit)
{
switch (unit) {
case N8V:
return 8;
case mN8V:
return 5;
case uN8V:
return 2;
default:
return 0;
}
}
QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if (!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 n = (qint64)nIn;
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-style thin space separators as these are locale independent and can't be
// confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
//-------------------------------------------------------------------------------//
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
if (num_decimals <= 0)
return quotient_str;
return quotient_str + QString(".") + remainder_str;
}
// TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to
// TODO: determine whether the output is used in a plain text context
// TODO: or an HTML context (and replace with
// TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully
// TODO: there aren't instances where the result could be used in
// TODO: either context.
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QSettings settings;
int digits = settings.value("digits").toInt();
QString result = format(unit, amount, plussign, separators);
if (decimals(unit) > digits) result.chop(decimals(unit) - digits);
return result + QString(" ") + name(unit);
}
QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(floorWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out)
{
if (!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).split(".");
if (parts.size() > 2) {
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if (parts.size() > 1) {
decimals = parts[1];
}
if (decimals.size() > num_decimals) {
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if (str.size() > 18) {
return false; // Longer numbers will exceed 63 bits
}
CAmount retvalue(str.toLongLong(&ok));
if (val_out) {
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit)) {
amountTitle += " (" + BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex& index, int role) const
{
int row = index.row();
if (row >= 0 && row < unitlist.size()) {
Unit unit = unitlist.at(row);
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case
// ===== END =====
// ===== BEGIN c++ =====
/*
* This file is part of Matrix.
*
* See the COPYRIGHT file at the top-level directory of this distribution
* for details of code ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <doctest/doctest.h>
#include <Matrix/matrix.h>
TEST_SUITE_BEGIN("test_associative_multiplication");
TEST_CASE("small_ones_matrix")
{
using namespace linalg;
Matrix<int> A{5, 5, 1};
Matrix<int> B{5, 5, 1};
Matrix<int> C{5, 5, 1};
Matrix<int> D{5, 5, 25};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("small_matrix")
{
using namespace linalg;
Matrix<int> A{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> B{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> C{{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix<int> D{{{468, 576, 684}, {1062, 1305, 1548}, {1656, 2034, 2412}}};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("medium_matrix")
{
using namespace linalg;
Matrix<int> A{100, 100, 6};
Matrix<int> B{100, 100, 2};
Matrix<int> C{100, 100, 8};
Matrix<int> D{100, 100, 960000};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_CASE("huge_matrix")
{
using namespace linalg;
Matrix<int> A{1000, 1000, 9};
Matrix<int> B{1000, 1000, 7};
Matrix<int> C{1000, 1000, 1};
Matrix<int> D{1000, 1000, 63000000};
CHECK(isSame(D, A * B * C) == 1);
}
TEST_SUITE_END();
// ===== END =====
// ===== BEGIN c++ =====
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2017-2020 The Qtum Core developers
// Copyright (c) 2020 The BCS Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/system.h>
#include <chainparamsbase.h>
#include <random.h>
#include <serialize.h>
#include <util/strencodings.h>
#include <regex>
#include <iomanip>
#include <stdarg.h>
#if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#include <pthread.h>
#include <pthread_np.h>
#endif
#ifndef WIN32
// for posix_fallocate
#ifdef __linux__
#ifdef _POSIX_C_SOURCE
#undef _POSIX_C_SOURCE
#endif
#define _POSIX_C_SOURCE 200112L
#endif // __linux__
#include <algorithm>
#include <fcntl.h>
#include <sched.h>
#include <sys/resource.h>
#include <sys/stat.h>
#else
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <codecvt>
#include <io.h> /* for _commit */
#include <shellapi.h>
#include <shlobj.h>
#endif
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#ifdef HAVE_MALLOPT_ARENA_MAX
#include <malloc.h>
#endif
#include <thread>
// Application startup time (used for uptime calculation)
const int64_t nStartupTime = GetTime();
const char * const BITCOIN_CONF_FILENAME = "bcs.conf";
ArgsManager gArgs;
/** A map that contains all the currently held directory locks. After
* successful locking, these will be held here until the global destructor
* cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
* is called.
*/
static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks;
/** Mutex to protect dir_locks. */
static std::mutex cs_dir_locks;
bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only, bool try_lock)
{
std::lock_guard<std::mutex> ulock(cs_dir_locks);
fs::path pathLockFile = directory / lockfile_name;
// If a lock for this directory already exists in the map, don't try to re-lock it
if (dir_locks.count(pathLockFile.string())) {
return true;
}
// Create empty lock file if it doesn't exist.
FILE* file = fsbridge::fopen(pathLockFile, "a");
if (file) fclose(file);
auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
if (try_lock && !lock->TryLock()) {
return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
}
if (!probe_only) {
// Lock successful and we're not just probing, put it into the map
dir_locks.emplace(pathLockFile.string(), std::move(lock));
}
return true;
}
void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
{
std::lock_guard<std::mutex> lock(cs_dir_locks);
dir_locks.erase((directory / lockfile_name).string());
}
void ReleaseDirectoryLocks()
{
std::lock_guard<std::mutex> ulock(cs_dir_locks);
dir_locks.clear();
}
bool DirIsWritable(const fs::path& directory)
{
fs::path tmpFile = directory / fs::unique_path();
FILE* file = fsbridge::fopen(tmpFile, "a");
if (!file) return false;
fclose(file);
remove(tmpFile);
return true;
}
/**
* Interpret a string argument as a boolean.
*
* The definition of atoi() requires that non-numeric string values like "foo",
* return 0. This means that if a user unintentionally supplies a non-integer
* argument here, the return value is always false. This means that -foo=false
* does what the user probably expects, but -foo=true is well defined but does
* not do what they probably expected.
*
* The return value of atoi() is undefined when given input not representable as
* an int. On most systems this means string value between "-2147483648" and
* "2147483647" are well defined (this method will return true). Setting
* -txindex=2147483648 on most systems, however, is probably undefined.
*
* For a more extensive discussion of this topic (and a wide range of opinions
* on the Right Way to change this code), see PR12713.
*/
static bool InterpretBool(const std::string& strValue)
{
if (strValue.empty())
return true;
return (atoi(strValue) != 0);
}
/** Internal helper functions for ArgsManager */
class ArgsManagerHelper {
public:
typedef std::map<std::string, std::vector<std::string>> MapArgs;
/** Determine whether to use config settings in the default section,
* See also comments around ArgsManager::ArgsManager() below. */
static inline bool UseDefaultSection(const ArgsManager& am, const std::string& arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
{
return (am.m_network == CBaseChainParams::MAIN || am.m_network_only_args.count(arg) == 0);
}
/** Convert regular argument into the network-specific setting */
static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg)
{
assert(arg.length() > 1 && arg[0] == '-');
return "-" + am.m_network + "." + arg.substr(1);
}
/** Find arguments in a map and add them to a vector */
static inline void AddArgs(std::vector<std::string>& res, const MapArgs& map_args, const std::string& arg)
{
auto it = map_args.find(arg);
if (it != map_args.end()) {
res.insert(res.end(), it->second.begin(), it->second.end());
}
}
/** Return true/false if an argument is set in a map, and also
* return the first (or last) of the possibly multiple values it has
*/
static inline std::pair<bool,std::string> GetArgHelper(const MapArgs& map_args, const std::string& arg, bool getLast = false)
{
auto it = map_args.find(arg);
if (it == map_args.end() || it->second.empty()) {
return std::make_pair(false, std::string());
}
if (getLast) {
return std::make_pair(true, it->second.back());
} else {
return std::make_pair(true, it->second.front());
}
}
/* Get the string value of an argument, returning a pair of a boolean
* indicating the argument was found, and the value for the argument
* if it was found (or the empty string if not found).
*/
static inline std::pair<bool,std::string> GetArg(const ArgsManager &am, const std::string& arg)
{
LOCK(am.cs_args);
std::pair<bool,std::string> found_result(false, std::string());
// We pass "true" to GetArgHelper in order to return the last
// argument value seen from the command line (so "bitcoind -foo=bar
// -foo=baz" gives GetArg(am,"foo")=={true,"baz"}
found_result = GetArgHelper(am.m_override_args, arg, true);
if (found_result.first) {
return found_result;
}
// But in contrast we return the first argument seen in a config file,
// so "foo=bar \n foo=baz" in the config file gives
// GetArg(am,"foo")={true,"bar"}
if (!am.m_network.empty()) {
found_result = GetArgHelper(am.m_config_args, NetworkArg(am, arg));
if (found_result.first) {
return found_result;
}
}
if (UseDefaultSection(am, arg)) {
found_result = GetArgHelper(am.m_config_args, arg);
if (found_result.first) {
return found_result;
}
}
return found_result;
}
/* Special test for -testnet and -regtest args, because we
* don't want to be confused by craziness like "[regtest] testnet=1"
*/
static inline bool GetNetBoolArg(const ArgsManager &am, const std::string& net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
{
std::pair<bool,std::string> found_result(
// ===== END =====
// ===== BEGIN c++ =====
/*
* Copyright (C) 2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "gtest/gtest.h"
#include "usm_linked_list/usm_linked_list.hpp"
#include "test_harness/test_harness.hpp"
TEST(UsmLinkedListSystemTests,
ApplicationReturnsSkipStatusGivenHelpMessageIsRequested) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"--help"};
EXPECT_EQ(compute_samples::Application::Status::SKIP,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenHostUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"host"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenDeviceUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"device"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests, GivenSharedUsmThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"shared"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
HWTEST(UsmLinkedListSystemTests,
GivenCustomListSizeThenApplicationReturnsOKStatus) {
compute_samples::UsmLinkedListApplication application;
std::vector<std::string> command_line = {"host", "--size", "1024"};
EXPECT_EQ(compute_samples::Application::Status::OK,
application.run(command_line));
}
// ===== END =====
// ===== BEGIN c++ =====
// Copyright (C) 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a wchar_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsStringLiteralTo(
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::o
// ===== END =====
// ===== BEGIN c++ =====
#ifndef CONNECT___SERVER__HPP
#define CONNECT___SERVER__HPP
/* $Id: server.hpp 364724 2012-05-30 14:57:38Z ivanovp $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Aaron Ucko, Victor Joukov, Denis Vakatov
*
*/
/// @file server.hpp
/// Framework to create multithreaded network servers with thread-per-request
/// scheduling.
#include <connect/impl/thread_pool_for_server.hpp>
#include <connect/ncbi_conn_stream.hpp>
#include <connect/ncbi_conn_exception.hpp>
#include <connect/ncbi_socket.hpp>
/** @addtogroup ThreadedServer
*
* @{
*/
BEGIN_NCBI_SCOPE
class IServer_ConnectionFactory;
class IServer_ConnectionBase;
struct SServer_Parameters;
class CServer_ConnectionPool;
class CServer_Connection;
/// Extended copy of the type EIO_Event allowing to distinguish between
/// connection closing from client and from ourselves
enum EServIO_Event {
eServIO_Open = 0x00,
eServIO_Read = 0x01,
eServIO_Write = 0x02,
eServIO_ReadWrite = 0x03, /**< eIO_Read | eIO_Write */
eServIO_ClientClose = 0x04,
eServIO_OurClose = 0x08,
eServIO_Inactivity = 0x10,
eServIO_Delete = 0x20
};
/// Transform EIO_Event type to EServIO_Event
inline EServIO_Event
IOEventToServIOEvent(EIO_Event event)
{
return (EServIO_Event) event;
}
class CNetCacheServer;
/////////////////////////////////////////////////////////////////////////////
///
/// CServer::
///
/// Thread-pool based server. On every event it allocates one of threads
/// from pool to serve the event, thereby making possible to serve large
/// number of concurrent connections efficiently. You need to subclass it
/// only if you want to provide gentle shutdown ability (override
/// ShutdownRequested) or process data in main thread on timeout (override
/// ProcessTimeout and set parameter accept_timeout to non-zero value).
///
class NCBI_XCONNECT_EXPORT CServer : protected CConnIniter
{
public:
// 'ctors
CServer(void);
virtual ~CServer();
/// Register a listener
void AddListener(IServer_ConnectionFactory* factory,
unsigned short port);
///
void SetParameters(const SServer_Parameters& new_params);
///
void GetParameters(SServer_Parameters* params);
/// Start listening before the main loop. If called, tries
/// to listen on all requested ports for all listeners, correcting
/// errors by calling listeners' OnFailure
void StartListening(void);
/// Enter the main loop
void Run(void);
/// Submit request to be executed by the server thread pool
void SubmitRequest(const CRef<CStdRequest>& request);
/// Mark connection as deferred for processing, i.e. do not poll on it
/// and wait when IsReadyToProcess() will return true.
void DeferConnectionProcessing(IServer_ConnectionBase* conn);
void DeferConnectionProcessing(CSocket* sock);
/// Close connection. Method should be called only when closing is
/// initiated by server itself, because it will generate then event
/// eServIO_OurClose.
///
/// @sa EServIO_Event
void CloseConnection(CSocket* sock);
/// Add externally created connection to the connection pool which server
/// polls on. Throws exception if pool is full.
/// NOTE: events to this connection can come theoretically even
/// NOTE: if connection gets some error or its peer closes it then conn
/// object will be deleted after processing OnClose event. If you don't
/// want that you have to call RemoveConnectionFromPool while handling
/// OnClose.
void AddConnectionToPool(CServer_Connection* conn);
/// Remove externally created connection from pool.
void RemoveConnectionFromPool(CServer_Connection* conn);
/// Force poll cycle to make another iteration.
/// Should be called if IsReadyToProcess() for some connection handler
/// became true.
void WakeUpPollCycle(void);
/// Set custom suffix to use on all threads in the server's pool.
/// Value can be set only before call to Run(), any change of the value
/// after call to Run() will be ignored.
void SetCustomThreadSuffix(const string& suffix)
{ m_ThreadSuffix = suffix; }
protected:
/// Initialize the server
///
/// Called by Run method before poll cycle.
virtual void Init();
/// Cleanup the server
///
/// Called by Run method after poll cycle when all processing threads
/// are stopped, but before releasing listening ports. Here you're still
/// guaranteed that another instance running on the same set of ports will
/// fail at StartListening point.
virtual void Exit();
/// Runs synchronously when no socket activity has occurred in a
/// while (as determined by m_AcceptTimeout).
/// @sa m_Parameters->accept_timeout
virtual void ProcessTimeout(void) { }
/// Runs synchronously between iterations.
/// @return
/// whether to shut down service and return from Run.
virtual bool ShutdownRequested(void) { return false; }
private:
void x_AddRequests(const vector<CRef<CStdRequest> >& reqs);
void x_DoRun(void);
friend class CNetCacheServer;
CPoolOfThreads_ForServer* GetThreadPool(void) { return m_ThreadPool.get(); }
auto_ptr<CPoolOfThreads_ForServer> m_ThreadPool;
SServer_Parameters* m_Parameters;
CServer_ConnectionPool* m_ConnectionPool;
string m_ThreadSuffix;
};
/////////////////////////////////////////////////////////////////////////////
///
/// Error codes for OnOverflow method in IServer_ConnectionHandler
enum EOverflowReason
{
eOR_Unknown = 0,
eOR_ConnectionPoolFull,
eOR_RequestQueueFull,
eOR_UnpollableSocket
};
/////////////////////////////////////////////////////////////////////////////
///
/// IServer_ConnectionHandler::
///
/// Implement this interface to provide server functionality.
///
class NCBI_XCONNECT_EXPORT IServer_ConnectionHandler
{
public:
virtual ~IServer_ConnectionHandler() { }
/// Following three methods are guaranteed to be called NOT
/// at the same time as On*, so if you implement them
/// you should not guard the variables which they can use with
/// mutexes.
/// @param alarm_time
/// Set this parameter to a pointer to a CTime object to recieve
/// an OnTimer event at the moment in time specified by this object.
/// @return
/// Returns the set of events for which Poll should check.
virtual EIO_Event GetEventsToPollFor(const CTime** /*alarm_time*/) const
{ return eIO_Read; }
/// Returns the timeout for this connection
virtual const STimeout* GetTimeout(void)
{ return kDefaultTimeout; }
/// Returns connection handler's perception of whether
// ===== END =====
// ===== BEGIN c++ =====
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find minimum time required to rot all oranges.
int orangesRotting(vector<vector<int>>& grid) {
// Code here
int n = grid.size();
int m = grid[0].size();
// BFS traversal
// stores index of rotten oranges
queue<pair<int,int>> rotten;
// first count total oranges in grid and push the rotten
// into the queue to be processed
int totOranges = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
// if cell not empty
if(grid[i][j]!=0){
totOranges++;
// if rotten push to queue
if(grid[i][j]==2) rotten.push({i,j});
}
}
}
int mx[] = { 0,0,-1,1};
int my[] = {-1,1, 0,0};
// count of total oranges rotted or will rot
int cntRot = 0, days = 0;
while(!rotten.empty()){
// getting number of oranges rotten each day
int k = rotten.size();
cntRot += k;
while(k--){
int x = rotten.front().first, y = rotten.front().second;
rotten.pop();
// traversing all 4 directions from current node
for(int i=0;i<4;i++){
int nx = x+mx[i], ny = y+my[i];
// if index out of bound or orange not present
// or rotten from before then ignore
if(nx<0 or ny<0 or nx>=n or ny>=m or grid[nx][ny]!=1)
continue;
// else rot the fresh orange and push to queue
grid[nx][ny] = 2;
rotten.push({nx,ny});
}
}
// at end of day we check if rotten isn't empty
// means another day is required to rot oranges
// increasing day to rot all fresh oranges
if(!rotten.empty()) days++;
}
// now check if all oranges in grid have rotted or not
// then return number of days else not possible return -1
return (totOranges==cntRot)?days:-1;
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n, m;
cin >> n >> m;
vector<vector<int>>grid(n, vector<int>(m, -1));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> grid[i][j];
}
}
Solution obj;
int ans = obj.orangesRotting(grid);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends
// ===== END =====
// ===== BEGIN c++ =====
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode *node) {
if (!node) {
return 0;
}
else if (!node -> left & !node -> right) {
return 1;
}
int left = getHeight(node -> left), right = getHeight(node -> right);
if (left == -1 | right == -1) {
return -1;
}
else if (abs(left - right) <= 1) {
return max(left, right) + 1;
}
else {
return -1;
}
}
bool isBalanced(TreeNode *root) {
return !(getHeight(root) == -1);
}
};
// ===== END =====
// ===== BEGIN c++ =====
#include <check.h>
#include <stdint.h>
#include "signals.h"
#include "diagnostics.h"
#include "lights.h"
#include "config.h"
#include "pipeline.h"
#include "power.h"
namespace diagnostics = openxc::diagnostics;
namespace usb = openxc::interface::usb;
using openxc::pipeline::Pipeline;
using openxc::signals::getCanBuses;
using openxc::signals::getCanBusCount;
using openxc::config::getConfiguration;
extern openxc::lights::RGB LIGHT_A_LAST_COLOR;
extern unsigned long FAKE_TIME;
// TODO this should be refactored out of vi_firmware.cpp, and include a header
// file so we don't have to use extern.
extern void receiveCan(Pipeline* pipeline, CanBus* bus);
extern void checkBusActivity();
extern void initializeVehicleInterface();
extern void firmwareLoop();
static bool canQueueEmpty(int bus) {
return QUEUE_EMPTY(CanMessage, &getCanBuses()[bus].sendQueue);
}
void setup() {
initializeVehicleInterface();
fail_unless(canQueueEmpty(0));
}
CanMessage message = {
id: 0x1,
format: CanMessageFormat::STANDARD,
data: {0x1, 0x2}
};
START_TEST (test_update_data_lights_can_active)
{
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
checkBusActivity();
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.blue));
}
END_TEST
START_TEST (test_update_data_lights_can_inactive)
{
checkBusActivity();
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.red));
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
FAKE_TIME += (openxc::can::CAN_ACTIVE_TIMEOUT_S * 1000) * 2;
}
END_TEST
START_TEST (test_update_data_lights_suspend)
{
CanBus* bus = &getCanBuses()[0];
QUEUE_PUSH(CanMessage, &bus->receiveQueue, message);
receiveCan(&getConfiguration()->pipeline, bus);
FAKE_TIME += (openxc::can::CAN_ACTIVE_TIMEOUT_S * 1000) * 2;
checkBusActivity();
if(getConfiguration()->powerManagement == openxc::config::PowerManagement::ALWAYS_ON) {
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.red));
} else {
ck_assert(openxc::lights::colors_equal(LIGHT_A_LAST_COLOR,
openxc::lights::COLORS.black));
}
}
END_TEST
START_TEST (test_loop)
{
firmwareLoop();
}
END_TEST
Suite* suite(void) {
Suite* s = suite_create("firmware");
TCase *tc_core = tcase_create("core");
tcase_add_checked_fixture(tc_core, setup, NULL);
tcase_add_test(tc_core, test_update_data_lights_can_active);
tcase_add_test(tc_core, test_update_data_lights_can_inactive);
tcase_add_test(tc_core, test_update_data_lights_suspend);
tcase_add_test(tc_core, test_loop);
suite_add_tcase(s, tc_core);
return s;
}
int main(void) {
int numberFailed;
Suite* s = suite();
SRunner *sr = srunner_create(s);
// Don't fork so we can actually use gdb
srunner_set_fork_status(sr, CK_NOFORK);
srunner_run_all(sr, CK_NORMAL);
numberFailed = srunner_ntests_failed(sr);
srunner_free(sr);
return (numberFailed == 0) ? 0 : 1;
}
// ===== END =====
// ===== BEGIN c++ =====
/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2020 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "unit_test_framework.h"
#include <string>
#include <array>
#include <algorithm>
#include "etl/string.h"
#include "etl/fnv_1.h"
#undef STR
#define STR(x) x
namespace
{
bool compares_agree(int result1, int result2)
{
return ((result1 < 0) && (result2 < 0)) ||
((result1 == 0) && (result2 == 0)) ||
((result1 > 0) && (result2 > 0));
}
SUITE(test_string_char)
{
static constexpr size_t SIZE = 11UL;
static constexpr size_t SIZE_L = 52UL;
static constexpr size_t SIZE_S = 4UL;
using Text = etl::string_ext;
using IText = etl::istring;
using TextT = etl::string<SIZE>;
using Compare_Text = std::string;
using value_t = Text::value_type;
using TextBuffer = std::array<IText::value_type, SIZE + 1>;
using TextBufferL = std::array<IText::value_type, SIZE_L + 1>;
using TextBufferS = std::array<IText::value_type, SIZE_S + 1>;
Compare_Text initial_text;
Compare_Text less_text;
Compare_Text greater_text;
Compare_Text shorter_text;
Compare_Text different_text;
Compare_Text insert_text;
Compare_Text longer_text;
Compare_Text short_text;
const value_t* pinitial_text = STR("Hello World");
value_t array_text[12];
value_t* p_text = array_text;
//*************************************************************************
template <typename T1, typename T2>
bool Equal(const T1& compare_text, const T2& text)
{
return (compare_text.size() == text.size()) && std::equal(text.begin(), text.end(), compare_text.begin());
}
//*************************************************************************
struct SetupFixture
{
SetupFixture()
{
initial_text = STR("Hello World");
insert_text = STR("Insert");
less_text = STR("Hello Vorld");
greater_text = STR("Hello Xorld");
shorter_text = STR("Hello Worl");
different_text = STR("Byee Planet");
longer_text = STR("Hello World There");
short_text = STR("Hello");
std::copy(pinitial_text, pinitial_text + etl::strlen(pinitial_text), array_text);
}
};
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK_EQUAL(text.size(), size_t(0));
CHECK(text.empty());
CHECK_EQUAL(SIZE, text.capacity());
CHECK_EQUAL(SIZE, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_buffer_and_size)
{
size_t length = etl::strlen(p_text);
Text text(p_text, length + 1);
CHECK_EQUAL(0U, text.size());
CHECK(text.empty());
CHECK_EQUAL(length, text.capacity());
CHECK_EQUAL(length, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_buffer_text_and_size)
{
Text text(p_text, p_text, etl::strlen(p_text) + 1);
CHECK_EQUAL(text.size(), etl::strlen(p_text));
CHECK(!text.empty());
CHECK_EQUAL(etl::strlen(p_text), text.capacity());
CHECK_EQUAL(etl::strlen(p_text), text.max_size());
CHECK(text.begin() != text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_array_buffer)
{
Text text(array_text, std::size(array_text));
CHECK_EQUAL(0U, text.size());
CHECK(text.empty());
CHECK_EQUAL(std::size(array_text) - 1, text.capacity());
CHECK_EQUAL(std::size(array_text) - 1, text.max_size());
CHECK(text.begin() == text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_default_constructor_use_array_buffer_text)
{
Text text(array_text, array_text, std::size(array_text));
CHECK_EQUAL(text.size(), etl::strlen(array_text));
CHECK(!text.empty());
CHECK_EQUAL(std::size(array_text) - 1, text.capacity());
CHECK_EQUAL(std::size(array_text) - 1, text.max_size());
CHECK(text.begin() != text.end());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST(test_iterator_comparison_empty)
{
TextBuffer buffer;
Text text(buffer.data(), buffer.size());
CHECK(text.begin() == text.end());
CHECK(text.cbegin() == text.cend());
CHECK(text.rbegin() == text.rend());
CHECK(text.crbegin() == text.crend());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_value)
{
const size_t INITIAL_SIZE = 5UL;
const value_t INITIAL_VALUE = STR('A');
TextBuffer buffer;
Compare_Text compare_text(INITIAL_SIZE, INITIAL_VALUE);
Text text(INITIAL_SIZE, INITIAL_VALUE, buffer.data(), buffer.size());
CHECK(text.size() == INITIAL_SIZE);
CHECK(!text.empty());
bool is_equal = Equal(compare_text, text);
CHECK(is_equal);
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(!text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_size_excess)
{
TextBuffer buffer;
Text text(buffer.size() + 1, STR('A'), buffer.data(), buffer.size());
CHECK_EQUAL(buffer.size() - 1, text.size());
#if ETL_HAS_STRING_TRUNCATION_CHECKS
CHECK(text.is_truncated());
#endif
}
//*************************************************************************
TEST_FIXTURE(SetupFixture, test_constructor_char_pointer)
{
TextBuffer buffer;
Compare_Text compare_text(initial_text.c_str());
Text text(initial_text.c_str(), buffer.data(), buffer.size());
CHECK(!text.empty());
// ===== END =====
// ===== BEGIN c =====
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.01.0622 */
/* @@MIDL_FILE_HEADING( ) */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 500
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif /* __RPCNDR_H_VERSION__ */
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __openservice_h__
#define __openservice_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __IOpenServiceActivityInput_FWD_DEFINED__
#define __IOpenServiceActivityInput_FWD_DEFINED__
typedef interface IOpenServiceActivityInput IOpenServiceActivityInput;
#endif /* __IOpenServiceActivityInput_FWD_DEFINED__ */
#ifndef __IOpenServiceActivityOutputContext_FWD_DEFINED__
#define __IOpenServiceActivityOutputContext_FWD_DEFINED__
typedef interface IOpenServiceActivityOutputContext IOpenServiceActivityOutputContext;
#endif /* __IOpenServiceActivityOutputContext_FWD_DEFINED__ */
#ifndef __IOpenService_FWD_DEFINED__
#define __IOpenService_FWD_DEFINED__
typedef interface IOpenService IOpenService;
#endif /* __IOpenService_FWD_DEFINED__ */
#ifndef __IOpenServiceManager_FWD_DEFINED__
#define __IOpenServiceManager_FWD_DEFINED__
typedef interface IOpenServiceManager IOpenServiceManager;
#endif /* __IOpenServiceManager_FWD_DEFINED__ */
#ifndef __OpenServiceManager_FWD_DEFINED__
#define __OpenServiceManager_FWD_DEFINED__
#ifdef __cplusplus
typedef class OpenServiceManager OpenServiceManager;
#else
typedef struct OpenServiceManager OpenServiceManager;
#endif /* __cplusplus */
#endif /* __OpenServiceManager_FWD_DEFINED__ */
#ifndef __OpenServiceActivityManager_FWD_DEFINED__
#define __OpenServiceActivityManager_FWD_DEFINED__
#ifdef __cplusplus
typedef class OpenServiceActivityManager OpenServiceActivityManager;
#else
typedef struct OpenServiceActivityManager OpenServiceActivityManager;
#endif /* __cplusplus */
#endif /* __OpenServiceActivityManager_FWD_DEFINED__ */
#ifndef __IOpenServiceActivity_FWD_DEFINED__
#define __IOpenServiceActivity_FWD_DEFINED__
typedef interface IOpenServiceActivity IOpenServiceActivity;
#endif /* __IOpenServiceActivity_FWD_DEFINED__ */
#ifndef __IEnumOpenServiceActivity_FWD_DEFINED__
#define __IEnumOpenServiceActivity_FWD_DEFINED__
typedef interface IEnumOpenServiceActivity IEnumOpenServiceActivity;
#endif /* __IEnumOpenServiceActivity_FWD_DEFINED__ */
#ifndef __IOpenServiceActivityCategory_FWD_DEFINED__
#define __IOpenServiceActivityCategory_FWD_DEFINED__
typedef interface IOpenServiceActivityCategory IOpenServiceActivityCategory;
#endif /* __IOpenServiceActivityCategory_FWD_DEFINED__ */
#ifndef __IEnumOpenServiceActivityCategory_FWD_DEFINED__
#define __IEnumOpenServiceActivityCategory_FWD_DEFINED__
typedef interface IEnumOpenServiceActivityCategory IEnumOpenServiceActivityCategory;
#endif /* __IEnumOpenServiceActivityCategory_FWD_DEFINED__ */
#ifndef __IOpenServiceActivityManager_FWD_DEFINED__
#define __IOpenServiceActivityManager_FWD_DEFINED__
typedef interface IOpenServiceActivityManager IOpenServiceActivityManager;
#endif /* __IOpenServiceActivityManager_FWD_DEFINED__ */
/* header files for imported files */
#include "objidl.h"
#include "oleidl.h"
#include "mshtml.h"
#include "exdisp.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_openservice_0000_0000 */
/* [local] */
//=--------------------------------------------------------------------------=
// openservice.h
//=--------------------------------------------------------------------------=
// (C) Copyright Microsoft Corporation. All Rights Reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//=--------------------------------------------------------------------------=
#include <winapifamily.h>
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
typedef
enum OpenServiceErrors
{
OS_E_NOTFOUND = 0x80030002,
OS_E_NOTSUPPORTED = 0x80004021,
OS_E_CANCELLED = 0x80002ef1,
OS_E_GPDISABLED = 0xc00d0bdc
} OpenServiceErrors;
typedef
enum OpenServiceActivityContentType
{
ActivityContentNone = -1,
ActivityContentDocument = ( ActivityContentNone + 1 ) ,
ActivityContentSelection = ( ActivityContentDocument + 1 ) ,
ActivityContentLink = ( ActivityContentSelection + 1 ) ,
ActivityContentCount = ( ActivityContentLink + 1 )
} OpenServiceActivityContentType;
extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_openservice_0000_0000_v0_0_s_ifspec;
#ifndef __IOpenServiceActivityInput_INTERFACE_DEFINED__
#define __IOpenServiceActivityInput_INTERFACE_DEFINED__
/* interface IOpenServiceActivityInput */
/* [unique][uuid][object] */
EXTERN_C const IID IID_IOpenServiceActivityInput;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("75cb4db9-6da0-4da3-83ce-422b6a433346")
IOpenServiceActivityInput : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetVariable(
/* [in] */ __RPC__in LPCWSTR pwzVariableName,
/* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType,
/* [out] */ __RPC__deref_out_opt BSTR *pbstrVariableContent) = 0;
virtual HRESULT STDMETHODCALLTYPE HasVariable(
/* [in] */ __RPC__in LPCWSTR pwzVariableName,
/* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType,
/* [out] */ __RPC__out BOOL *pfHasVariable) = 0;
virtual HRESULT STDMETHODCALLTYPE GetType(
/* [out] */ __RPC__out OpenServiceActivityContentType *pType) = 0;
};
#else /* C style interface */
typedef struct IOpenServiceActivityInputVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in IOpenServiceActivityInput * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in IOpenServiceActivityInput * This);
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in IOpenServiceActivityInput * This);
HRESULT ( STDMETHODCALLTYPE *GetVariable )(
__RPC__in IOpenServiceActivityInput * This,
/* [in] */ __RPC__in LPCWSTR pwzVariableName,
/* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType,
/* [out] */ __RPC__deref_out_opt BSTR *pbstrVariableContent);
HRESULT ( STDMETHODCALLTYPE *HasVariable )(
__RPC__in IOpenServiceActivityInput * This,
/* [in] */ __RPC__in LPCWSTR pwzVariableName,
/* [unique][in] */ __RPC__in_opt LPCWSTR pwzVariableType,
/* [out] */ __RPC__out BOOL *pfHasVariable);
HRESULT ( STDMETHODCALLTYPE *GetType )(
__RPC__in IOpenServiceActivityInput * This,
/* [out] */ __RPC__out OpenServiceActivityContentType *pType);
END_INTERFACE
} IOpenServiceActivityInputVtbl;
interface IOpenServiceActivityInput
{
CONST_VTBL struct IOpenServiceActivityInputVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IOpenServiceActivityInput_QueryInterface(This,riid,ppvObject
// ===== END =====
// ===== BEGIN c =====
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:38:26 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/VideosUI.framework/VideosUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <VideosUI/VUIMediaItem.h>
#import <libobjc.A.dylib/VUIPlistMediaEntityImageLoadParamsCreating.h>
@class VUIPlistMediaDatabaseItem;
@interface VUIPlistMediaItem : VUIMediaItem <VUIPlistMediaEntityImageLoadParamsCreating> {
VUIPlistMediaDatabaseItem* _databaseItem;
}
@property (nonatomic,retain) VUIPlistMediaDatabaseItem * databaseItem; //@synthesize databaseItem=_databaseItem - In the implementation block
-(id)isLocal;
-(id)assetType;
-(id)showTitle;
-(id)seasonNumber;
-(id)showIdentifier;
-(id)playedState;
-(id)seasonIdentifier;
-(id)imageLoadParamsWithImageType:(unsigned long long)arg1 ;
-(id)initWithMediaLibrary:(id)arg1 identifier:(id)arg2 requestedProperties:(id)arg3 kind:(id)arg4 ;
-(id)initWithMediaLibrary:(id)arg1 databaseItem:(id)arg2 requestedProperties:(id)arg3 ;
-(id)previewFrameImageIdentifier;
-(id)seasonTitle;
-(id)coverArtImageIdentifier;
-(id)_valueForPropertyDescriptor:(id)arg1 ;
-(VUIPlistMediaDatabaseItem *)databaseItem;
-(void)setDatabaseItem:(VUIPlistMediaDatabaseItem *)arg1 ;
@end
// ===== END =====
// ===== BEGIN c =====
//
// Weeks.h
// JodaTime
//
// Created by Christian Fruth on 28.04.14.
// Copyright (c) 2014 Boxx IT Solutions GmbH. All rights reserved.
//
# import "Period.h"
@class LocalDate;
@interface Weeks : Period
@property (nonatomic, readonly) NSInteger weeks;
+ (instancetype)ZERO;
+ (instancetype)ONE;
+ (instancetype)weeks:(NSInteger)weeks;
+ (instancetype)weeksBetween:(LocalDate *)startDate and:(LocalDate *)stopDate;
- (Weeks *)plus:(Weeks *)aWeeks;
- (Weeks *)minus:(Weeks *)aWeeks;
- (BOOL)isEqualToWeeks:(Weeks *)aDays;
- (NSComparisonResult)compare:(Weeks *)aDays;
@end
// ===== END =====
// ===== BEGIN c =====
//
// files.h
//
// classes and functions for dealing with files
//
// Copyright Peter Andrews 2015 @ CSHL
//
#ifndef LONGMEM_FILES_H_
#define LONGMEM_FILES_H_
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string> // Placed before cstring, no error, why?
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <limits>
#include <map>
#include <sstream>
#include <thread>
#include <utility>
#include <vector>
#include "error.h"
#ifndef MAP_POPULATE
#define MAP_POPULATE 0
#endif
namespace paa {
extern bool read_ahead;
extern bool memory_mapped;
// A safe file name
inline std::string safe_file_name(const std::string & name) {
if (name.empty()) return "";
std::istringstream stream{name.c_str()};
char c;
std::string result{""};
while (stream.get(c)) if (isalnum(c) || c == '.') result += c;
return result;
}
// Get file extension, if exists
inline std::string extension(const std::string & file_name) {
const size_t pos{file_name.find_last_of('.')};
if (pos == std::string::npos) return "";
return file_name.substr(pos);
}
// Grab file contents as a string
inline std::string file_string(const std::string & name) {
std::ifstream css{name.c_str()};
std::string result;
char c;
while (css.get(c)) result += c;
return result;
}
// Files and directories
inline uint64_t file_size(const std::string & file_name) {
struct stat st;
if (stat(file_name.c_str(), &st)) {
return 0;
}
return static_cast<uint64_t>(st.st_size);
}
inline void mkdir(const std::string & dir_name) {
if (::mkdir(dir_name.c_str(),
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) &&
errno != EEXIST)
throw Error("Problem creating directory") << dir_name;
}
inline std::string get_cwd() {
constexpr uint64_t Ksize{1024};
char buffer[Ksize];
if (getcwd(buffer, Ksize) == nullptr)
throw Error("Problem getting current working directory");
return std::string(buffer);
}
inline void symlink(const std::string & target, const std::string & linkpath) {
#ifdef __CYGWIN__
throw Error("Cannot do symlink under cygwin");
#else
if (::symlink(target.c_str(), linkpath.c_str()) && errno != EEXIST)
throw Error("Problem creating symbilic link") << linkpath << "to" << target;
#endif
}
inline bool readable(const std::string & file) {
return !access(file.c_str(), R_OK);
}
inline void unlink(const std::string & file, const bool complain = false) {
if (::unlink(file.c_str()) && complain) {
throw Error("Could not unlink file") << file;
}
}
inline uint64_t get_block_size(const std::string name) {
struct stat sb;
if (stat(name.c_str(), &sb) == -1) {
perror("stat");
throw Error("stat call failure for") << name;
}
return sb.st_blksize;
}
inline std::string get_next_file(const std::string & name,
const std::string ext) {
static std::map<std::string, unsigned int> last_indexes;
for (unsigned int i{last_indexes[name + ext] + 1}; ; ++i) {
const std::string test{name + "." + std::to_string(i) + "." + ext};
if (!readable(test)) {
last_indexes[name] = i;
return test;
}
}
}
// Read Specific columns from disk
class Columns {
public:
Columns(const std::string & file_name, const uint64_t size_hint,
const std::string & columns, const bool header) {
// Get list of desired column names or numbers
std::istringstream column_input{columns.c_str()};
std::string column_spec;
while (getline(column_input, column_spec, ',')) {
// column spec is either name or name:type
std::istringstream spec_stream{column_spec.c_str()};
std::string column_name{};
std::string column_type{};
getline(spec_stream, column_name, ':');
if (spec_stream) {
spec_stream >> column_type;
}
column_names.push_back(column_name);
column_types.push_back(column_type);
}
// Input file name
std::ifstream input{file_name.c_str()};
if (!input) throw Error("Could not open input file") << file_name;
// Process header, or just use column numbers passed
using ColumnLookup = std::pair<unsigned int, unsigned int>;
const std::vector<ColumnLookup> column_numbers{
[this, header, columns, &input] () {
std::vector<ColumnLookup> result;
if (header) {
// Column names are strings
std::string header_line;
getline(input, header_line);
std::string column_name;
std::istringstream header_stream{header_line.c_str()};
unsigned int column{0};
while (header_stream >> column_name) {
const std::vector<std::string>::const_iterator found{
find(column_names.begin(), column_names.end(), column_name)};
if (found != column_names.end())
result.emplace_back(column, found - column_names.begin());
++column;
}
} else {
// Column names are numbers, starting with 1
for (unsigned int c{0}; c != column_names.size(); ++c) {
result.emplace_back(static_cast<unsigned int>(
stoul(column_names[c]) - 1), c);
column_names[c] = std::string(header ? "" : "column ") +
column_names[c];
}
sort(result.begin(), result.end(),
[](const ColumnLookup & lhs, const ColumnLookup & rhs) {
return lhs.first < rhs.first;
});
}
if (column_names.size() != result.size()) {
throw Error("Could not find all columns specified in")
<< columns;
}
return result;
}()};
if (0) {
std::cerr << "Parse:" << std::endl;
for (const std::pair<unsigned int, unsigned int> & lu : column_numbers) {
std::cerr << column_names[lu.second]
<< " " << lu.first << " " << lu.second << std::endl;
}
}
// Reserve space for data
data.resize(column_names.size());
for (unsigned int c{0}; c != data.size(); ++c) {
data.reserve(size_hint);
}
// Read in data line by line
std::string line;
std::string text;
double value{0};
while (getline(input, line)) {
std::istringstream stream{line.c_str()};
std::vector<ColumnLookup>::const_iterator nc{column_numbers.begin()};
unsigned int c{0};
while (stream) {
if (nc != column_numbers.end() && nc->first == c) {
if (stream >> value) data[nc++->second].push_back(value);
} else {
stream >> text;
}
++c;
}
}
if (0) std::cerr << "Read " << data[0].size()
<< " lines from " << file_name << std::endl;
}
const std::string & name(unsigned int c) const { return column_names[c]; }
const std::string & type(unsigned int c) const { return column_types[c]; }
uint64_t n_rows() const { return n_cols() ? data[0].size() : 0; }
unsigned int n_cols() const { return static_cast<unsigned int>(data.size()); }
const std::vector<double> & operator[](const unsigned int c) const {
return data[c];
}
private:
std::vector<std::string> column_names{};
std::vector<std::string> column_types{};
std::vector<std::vector<double>> data{};
};
// class FileVector {};
// Iterator for file-based vector
template<class Type, template <class ...> class Container>
class VectorIterator {
public:
// iterator properties
using value_type = Type;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
using iterator_category = std::random_access_iterator_tag;
// constructor
VectorIterator(const Container<Type> & file_, const uint64_t current_) :
file{&file_}, current{current_} { }
// null iterator construction
explicit VectorIterator(const void *) :
file{nullptr}, current{static_cast<uint64_t>(-1)} { }
// value access
cons
// ===== END =====
// ===== BEGIN c =====
#ifndef __SUB_TRACK_FILTER_H__
#define __SUB_TRACK_FILTER_H__
#include "abstractreader.h"
class SubTrackFilter
{
public:
SubTrackFilter(int pid) : m_srcPID(pid) {}
virtual ~SubTrackFilter() {}
static int pidToSubPid(int pid, int subPid) { return (pid << 16) + subPid; }
static bool isSubTrack(int pid) { return pid >= 65536; }
bool isSupportedTrack(int pid) const { return m_srcPID == pid; }
virtual int demuxPacket(DemuxedData& demuxedData, const PIDSet& acceptedPIDs, AVPacket& avPacket) = 0;
protected:
int m_srcPID;
};
#endif // __SUB_TRACK_FILTER_H__
// ===== END =====
// ===== BEGIN c =====
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_CORE_CONFIG_H_INCLUDED
#define RIPPLE_CORE_CONFIG_H_INCLUDED
#include <ripple/basics/BasicConfig.h>
#include <ripple/basics/base_uint.h>
#include <ripple/protocol/SystemParameters.h> // VFALCO Breaks levelization
#include <ripple/beast/net/IPEndpoint.h>
#include <beast/core/string.hpp>
#include <ripple/beast/utility/Journal.h>
#include <boost/asio/ip/tcp.hpp> // VFALCO FIX: This include should not be here
#include <boost/filesystem.hpp> // VFALCO FIX: This include should not be here
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <cstdint>
#include <map>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>
namespace ripple {
using namespace std::chrono_literals;
class Rules;
//------------------------------------------------------------------------------
enum SizedItemName
{
siSweepInterval,
siNodeCacheSize,
siNodeCacheAge,
siTreeCacheSize,
siTreeCacheAge,
siSLECacheSize,
siSLECacheAge,
siLedgerSize,
siLedgerAge,
siLedgerFetch,
siHashNodeDBCache,
siTxnDBCache,
siLgrDBCache,
};
struct SizedItem
{
SizedItemName item;
int sizes[5];
};
// This entire derived class is deprecated.
// For new config information use the style implied
// in the base class. For existing config information
// try to refactor code to use the new style.
//
class Config : public BasicConfig
{
public:
// Settings related to the configuration file location and directories
static char const* const configFileName;
static char const* const databaseDirName;
static char const* const validatorsFileName;
/** Returns the full path and filename of the debug log file. */
boost::filesystem::path getDebugLogFile () const;
/** Returns the full path and filename of the entropy seed file. */
boost::filesystem::path getEntropyFile () const;
private:
boost::filesystem::path CONFIG_FILE;
boost::filesystem::path CONFIG_DIR;
boost::filesystem::path DEBUG_LOGFILE;
void load ();
beast::Journal j_;
bool QUIET = false; // Minimize logging verbosity.
bool SILENT = false; // No output to console after startup.
/** Operate in stand-alone mode.
In stand alone mode:
- Peer connections are not attempted or accepted
- The ledger is not advanced automatically.
- If no ledger is loaded, the default ledger with the root
account is created.
*/
bool RUN_STANDALONE = false;
public:
bool doImport = false;
bool valShards = false;
bool ELB_SUPPORT = false;
std::vector<std::string> IPS; // Peer IPs from rippled.cfg.
std::vector<std::string> IPS_FIXED; // Fixed Peer IPs from rippled.cfg.
std::vector<std::string> SNTP_SERVERS; // SNTP servers from rippled.cfg.
enum StartUpType
{
FRESH,
NORMAL,
LOAD,
LOAD_FILE,
REPLAY,
NETWORK
};
StartUpType START_UP = NORMAL;
bool START_VALID = false;
std::string START_LEDGER;
// Network parameters
int const TRANSACTION_FEE_BASE = 10; // The number of fee units a reference transaction costs
// Note: The following parameters do not relate to the UNL or trust at all
std::size_t NETWORK_QUORUM = 0; // Minimum number of nodes to consider the network present
// Peer networking parameters
bool PEER_PRIVATE = false; // True to ask peers not to relay current IP.
int PEERS_MAX = 0;
std::chrono::seconds WEBSOCKET_PING_FREQ = 5min;
// Path searching
int PATH_SEARCH_OLD = 7;
int PATH_SEARCH = 7;
int PATH_SEARCH_FAST = 2;
int PATH_SEARCH_MAX = 10;
// Validation
boost::optional<std::size_t> VALIDATION_QUORUM; // validations to consider ledger authoritative
std::uint64_t FEE_DEFAULT = 10;
std::uint64_t FEE_ACCOUNT_RESERVE = 200*SYSTEM_CURRENCY_PARTS;
std::uint64_t FEE_OWNER_RESERVE = 50*SYSTEM_CURRENCY_PARTS;
std::uint64_t FEE_OFFER = 10;
// Node storage configuration
std::uint32_t LEDGER_HISTORY = 256;
std::uint32_t FETCH_DEPTH = 1000000000;
int NODE_SIZE = 0;
bool SSL_VERIFY = true;
std::string SSL_VERIFY_FILE;
std::string SSL_VERIFY_DIR;
// Thread pool configuration
std::size_t WORKERS = 0;
// These override the command line client settings
boost::optional<boost::asio::ip::address_v4> rpc_ip;
boost::optional<std::uint16_t> rpc_port;
std::unordered_set<uint256, beast::uhash<>> features;
public:
Config() = default;
int getSize (SizedItemName) const;
/* Be very careful to make sure these bool params
are in the right order. */
void setup (std::string const& strConf, bool bQuiet,
bool bSilent, bool bStandalone);
void setupControl (bool bQuiet,
bool bSilent, bool bStandalone);
/**
* Load the config from the contents of the string.
*
* @param fileContents String representing the config contents.
*/
void loadFromString (std::string const& fileContents);
bool quiet() const { return QUIET; }
bool silent() const { return SILENT; }
bool standalone() const { return RUN_STANDALONE; }
};
} // ripple
#endif
// ===== END =====
// ===== BEGIN c =====
/*
* i2c.c
*
* Created on: 26/ott/2015
* Author: nicola
*/
// Function used to setup I2C1, that is P0.19 and P0.20 on LPC1769
// That's useful because an I2C-E2PROM 24LC64 is already present on evaluation board
//
#include "lpc1769.h"
#include "i2c.h"
unsigned char I2Cbuffer[I2C_BUFFER_LEN]; // I2C data buffer
unsigned char* I2CbufferPtr; // I2C buffer pointer
int I2CbufferCnt; // I2C buffer counter
int I2CrptStartPos; // I2C Repeated Start position
// I2C1 Interrupt request handler
void I2C1_IRQHandler(void)
{
unsigned int I2C_Status=0;
I2C_Status = I2C1STAT; // load I2C1 status register value
switch(I2C_Status)
{
case START: // START condition or
I2CbufferPtr = I2Cbuffer; // reset buffer pointer
case REP_START: // repeated START condition has been transmitted
I2C1DAT = *I2CbufferPtr; // load SLA+R/W to I2C1DAT
I2CbufferCnt--; // update buffer counter
I2C1CONCLR = (1<<5); // clear I2C STA flag
break;
////////////////////// Master transmitter mode
case SLA_W_ACK: // SLA+W has been transmitted; ACK has been received
case DATA_W_ACK: // Data byte in I2DAT has been transmitted; ACK has been received
if(I2CbufferCnt>0) // check buffer counter value
{
I2CbufferPtr++; // update buffer pointer
if(I2CbufferCnt!=I2CrptStartPos)
{
I2C1DAT = *I2CbufferPtr; // load data byte to I2C1DAT
I2CbufferCnt--; // update buffer counter
}
else
I2C1CONSET |= (1<<5); // set I2C START flag (REPEATED START)
}
else
I2C1CONSET = (1<<4); // set I2C STOP flag
break;
case SLA_W_NACK: // SLA+W has been transmitted; NOT ACK has been received
case DATA_W_NACK: // Data byte in I2DAT has been transmitted; NOT ACK has been received
I2C1CONSET = (1<<4); // set I2C STOP flag
break;
////////////////////////////////////
////////////////////// Master receiver mode
case SLA_R_ACK: // SLA+R has been transmitted; ACK has been received
I2CbufferPtr++; // update buffer pointer
break;
case DATA_R_ACK: // Data byte has been received; ACK has been returned
if(I2CbufferCnt>1) // check buffer counter value
I2C1CONSET = (1<<2); // set I2C AA flag
else
I2C1CONCLR = (1<<2); // clear I2C AA flag
*I2CbufferPtr = I2C1DAT; // load I2C1DAT to data byte
I2CbufferCnt--; // update buffer counter
break;
case DATA_R_NACK: // Data byte has been received; NOT ACK has been returned
*I2CbufferPtr = I2C1DAT; // load I2C1DAT to data byte
I2CbufferCnt--; // update buffer counter
case SLA_R_NACK: // SLA+R has been transmitted; NOT ACK has been received
I2C1CONSET = (1<<4); // set I2C STOP flag
break;
////////////////////////////////////
case NO_RELEVANT: // No relevant information available; SI = 0
break;
default: // undefined status
I2C1CONSET = (1<<4); // set I2C STOP flag
}
I2C1CONCLR = (1<<3); // clear I2C interrupt flag
return;
}
// I2C1 setup function
int setupI2C1()
{
PINSEL1 |= (0b1111 << 6); // set bit PINSEL1[9:6] at 0b1111 so that P0.19 act as SDA1 and P0.20 as SCL1
PINMODE1 |= (0b1010 << 6); // set bit PINMODE1[9:6] at 0b1010 so that P0.19 and P0.20 have neither pull-up nor pull-down
PINMODE_OD0 |= (0b11 << 19); // set bit PINMODE_OD0[20:19] at 0b11 so that P0.19 and P0.20 are open drain
ISER0 |= (0b1 << 11); // set ISER0[11] so that ISE_I2C1 interrupt is enabled
IPR2 |= (0b10000 << 27); // set IPR2[31:27] at 0b10000 so that IP_I2C1 has priority 0x10 (middle priority)
I2C1SCLH = I2C1SCLL = ((CORE_CLK/4)/I2C_STD_FREQ)/2; // check equation(13) at page 457 of User Manual
I2C1CONSET |= (1<<6); // set I2EN to enable I2C1 interface
return 0;
}
// I2C1 start function
int startI2C1()
{
I2C1CONSET |= (1<<5); // set I2C START flag
return 0;
}
// ===== END =====
// ===== BEGIN c =====
//
// Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include "JSBSourceWriter.h"
using namespace Atomic;
namespace ToolCore
{
class JSBPackage;
class JSBClass;
class JSBPackageWriter : public JSBSourceWriter
{
public:
virtual void GenerateSource();
virtual void PostProcess() {}
protected:
JSBPackageWriter(JSBPackage* package);
JSBPackage* package_;
};
}
// ===== END =====
// ===== BEGIN c =====
//
// UIImage+Util.h
// iosapp
//
// Created by ChanAetern on 2/13/15.
// Copyright (c) 2015 oschina. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (Util)
- (UIImage *)imageMaskedWithColor:(UIColor *)maskColor;
- (UIImage *)cropToRect:(CGRect)rect;
@end
// ===== END =====
// ===== BEGIN c =====
/*
* Microsoft Advanced Streaming Format demuxer
* Copyright (c) 2014 Alexandra Hájková
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/attributes.h"
#include "libavutil/avstring.h"
#include "libavutil/bswap.h"
#include "libavutil/common.h"
#include "libavutil/dict.h"
#include "libavutil/internal.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/time_internal.h"
#include "avformat.h"
#include "avio_internal.h"
#include "avlanguage.h"
#include "id3v2.h"
#include "internal.h"
#include "riff.h"
#include "asf.h"
#include "asfcrypt.h"
#define ASF_BOOL 0x2
#define ASF_WORD 0x5
#define ASF_GUID 0x6
#define ASF_DWORD 0x3
#define ASF_QWORD 0x4
#define ASF_UNICODE 0x0
#define ASF_FLAG_BROADCAST 0x1
#define ASF_BYTE_ARRAY 0x1
#define ASF_TYPE_AUDIO 0x2
#define ASF_TYPE_VIDEO 0x1
#define ASF_STREAM_NUM 0x7F
#define ASF_MAX_STREAMS 128
#define BMP_HEADER_SIZE 40
#define ASF_NUM_OF_PAYLOADS 0x3F
#define ASF_ERROR_CORRECTION_LENGTH_TYPE 0x60
#define ASF_PACKET_ERROR_CORRECTION_DATA_SIZE 0x2
typedef struct GUIDParseTable {
const char *name;
ff_asf_guid guid;
int (*read_object)(AVFormatContext *, const struct GUIDParseTable *);
int is_subobject;
} GUIDParseTable;
typedef struct ASFPacket {
AVPacket avpkt;
int64_t dts;
uint32_t frame_num; // ASF payloads with the same number are parts of the same frame
int flags;
int data_size;
int duration;
int size_left;
uint8_t stream_index;
} ASFPacket;
typedef struct ASFStream {
uint8_t stream_index; // from packet header
int index; // stream index in AVFormatContext, set in asf_read_stream_properties
int type;
int indexed; // added index entries from the Simple Index Object or not
int8_t span; // for deinterleaving
uint16_t virtual_pkt_len;
uint16_t virtual_chunk_len;
int16_t lang_idx;
ASFPacket pkt;
} ASFStream;
typedef struct ASFStreamData{
char langs[32];
AVDictionary *asf_met; // for storing per-stream metadata
AVRational aspect_ratio;
} ASFStreamData;
typedef struct ASFContext {
int data_reached;
int is_simple_index; // is simple index present or not 1/0
int is_header;
uint64_t preroll;
uint64_t nb_packets; // ASF packets
uint32_t packet_size;
int64_t send_time;
int duration;
uint32_t b_flags; // flags with broadcast flag
uint32_t prop_flags; // file properties object flags
uint64_t data_size; // data object size
uint64_t unknown_size; // size of the unknown object
int64_t offset; // offset of the current object
int64_t data_offset;
int64_t first_packet_offset; // packet offset
int64_t unknown_offset; // for top level header objects or subobjects without specified behavior
// ASF file must not contain more than 128 streams according to the specification
ASFStream *asf_st[ASF_MAX_STREAMS];
ASFStreamData asf_sd[ASF_MAX_STREAMS];
int nb_streams;
int stream_index; // from packet header, for the subpayload case
// packet parameters
uint64_t sub_header_offset; // offset of subpayload header
int64_t sub_dts;
uint8_t dts_delta; // for subpayloads
uint32_t packet_size_internal; // packet size stored inside ASFPacket, can be 0
int64_t packet_offset; // offset of the current packet inside Data Object
uint32_t pad_len; // padding after payload
uint32_t rep_data_len;
// packet state
uint64_t sub_left; // subpayloads left or not
unsigned int nb_sub; // number of subpayloads read so far from the current ASF packet
uint16_t mult_sub_len; // total length of subpayloads array inside multiple payload
uint64_t nb_mult_left; // multiple payloads left
int return_subpayload;
enum {
PARSE_PACKET_HEADER,
READ_SINGLE,
READ_MULTI,
READ_MULTI_SUB
} state;
} ASFContext;
static int detect_unknown_subobject(AVFormatContext *s, int64_t offset, int64_t size);
static const GUIDParseTable *find_guid(ff_asf_guid guid);
static int asf_probe(AVProbeData *pd)
{
/* check file header */
if (!ff_guidcmp(pd->buf, &ff_asf_header))
return AVPROBE_SCORE_MAX/2;
else
return 0;
}
static void swap_guid(ff_asf_guid guid)
{
FFSWAP(unsigned char, guid[0], guid[3]);
FFSWAP(unsigned char, guid[1], guid[2]);
FFSWAP(unsigned char, guid[4], guid[5]);
FFSWAP(unsigned char, guid[6], guid[7]);
}
static void align_position(AVIOContext *pb, int64_t offset, uint64_t size)
{
if (size < INT64_MAX - offset && avio_tell(pb) != offset + size)
avio_seek(pb, offset + size, SEEK_SET);
}
static int asf_read_unknown(AVFormatContext *s, const GUIDParseTable *g)
{
ASFContext *asf = s->priv_data;
AVIOContext *pb = s->pb;
uint64_t size = avio_rl64(pb);
int ret;
if (size > INT64_MAX)
return AVERROR_INVALIDDATA;
if (asf->is_header)
asf->unknown_size = size;
asf->is_header = 0;
if (!g->is_subobject) {
if (!(ret = strcmp(g->name, "Header Extension")))
avio_skip(pb, 22); // skip reserved fields and Data Size
if ((ret = detect_unknown_subobject(s, asf->unknown_offset,
asf->unknown_size)) < 0)
return ret;
} else {
if (size < 24) {
av_log(s, AV_LOG_ERROR, "Too small size %"PRIu64" (< 24).\n", size);
return AVERROR_INVALIDDATA;
}
avio_skip(pb, size - 24);
}
return 0;
}
static int get_asf_string(AVIOContext *pb, int maxlen, char *buf, int buflen)
{
char *q = buf;
int ret = 0;
if (buflen <= 0)
return AVERROR(EINVAL);
while (ret + 1 < maxlen) {
uint8_t tmp;
uint32_t ch;
GET_UTF16(ch, (ret += 2) <= maxlen ? avio_rl16(pb) : 0, break;);
PUT_UTF8(ch, tmp, if (q - buf < buflen - 1) *q++ = tmp;)
}
*q = 0;
return ret;
}
static int asf_read_marker(AVFormatContext *s, const GUIDParseTable *g)
{
ASFContext *asf = s->priv_data;
AVIOContext *pb = s->pb;
uint64_t size = avio_rl64(pb);
int i, nb_markers, ret;
size_t len;
char name[1024];
avio_skip(pb, 8);
avio_skip(pb, 8); // skip reserved GUID
nb_markers = avio_rl32(pb);
avio_skip(pb, 2); // skip reserved field
len = avio_rl16(pb);
for (i = 0; i < len; i++)
avio_skip(pb, 1);
for (i = 0; i < nb_markers; i++) {
int64_t pts;
avio_skip(pb, 8);
pts = avio_rl64(pb);
pts -= asf->preroll * 10000;
avio_skip(pb, 2); // entry length
avio_skip(pb, 4); // send time
avio_skip(pb, 4); // flags
len = avio_rl32(pb);
if ((ret = avio_get_str16le(pb, len, name,
sizeof(name))) < len)
avio_skip(pb, len - ret);
avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pts,
// ===== END =====
// ===== BEGIN c =====
#ifndef STDIO_H
#define STDIO_H
#include "os_type.h"
class STDIO
{
private:
uint8 *screen;
public:
STDIO();
// 初始化函数
void initialize();
// 打印字符c,颜色color到位置(x,y)
void print(uint x, uint y, uint8 c, uint8 color);
// 打印字符c,颜色color到光标位置
void print(uint8 c, uint8 color);
// 打印字符c,颜色默认到光标位置
void print(uint8 c);
// 移动光标到一维位置
void moveCursor(uint position);
// 移动光标到二维位置
void moveCursor(uint x, uint y);
// 获取光标位置
uint getCursor();
private:
// 滚屏
void rollUp();
};
#endif
// ===== END =====
// ===== BEGIN c =====
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:38:54 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/WorkflowKit.framework/WorkflowKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <WorkflowKit/WorkflowKit-Structs.h>
#import <libobjc.A.dylib/NSCopying.h>
#import <libobjc.A.dylib/WFParameterState.h>
@protocol WFParameterState;
@class NSString;
@interface WFPropertyListParameterValue : NSObject <NSCopying, WFParameterState> {
long long _valueType;
id<WFParameterState> _state;
}
@property (nonatomic,readonly) long long valueType; //@synthesize valueType=_valueType - In the implementation block
@property (nonatomic,readonly) id<WFParameterState> state; //@synthesize state=_state - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(Class)classForValueType:(long long)arg1 ;
+(id)defaultStateForValueType:(long long)arg1 ;
+(Class)processedClassForValueType:(long long)arg1 ;
+(id)localizedTitleForValueType:(long long)arg1 ;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)copyWithZone:(NSZone*)arg1 ;
-(id)initWithArray:(id)arg1 ;
-(id)initWithObject:(id)arg1 ;
-(id)initWithString:(id)arg1 ;
-(id)initWithDictionary:(id)arg1 ;
-(id<WFParameterState>)state;
-(id)serializedRepresentation;
-(long long)valueType;
-(id)initWithNumber:(id)arg1 ;
-(void)processWithContext:(id)arg1 userInputRequiredHandler:(/*^block*/id)arg2 valueHandler:(/*^block*/id)arg3 ;
-(id)containedVariables;
-(id)initWithSerializedRepresentation:(id)arg1 variableProvider:(id)arg2 parameter:(id)arg3 ;
-(id)initWithType:(long long)arg1 state:(id)arg2 ;
-(id)initWithStringState:(id)arg1 ;
-(id)initWithDictionaryState:(id)arg1 ;
-(id)initWithArrayState:(id)arg1 ;
-(id)initWithNumberState:(id)arg1 ;
-(id)initWithBooleanState:(id)arg1 ;
-(id)initWithBoolean:(id)arg1 ;
@end
// ===== END =====
// ===== BEGIN c =====
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#pragma once
#include <folly/Benchmark.h>
#include <folly/Format.h>
#include <folly/container/Enumerate.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <chrono>
#include "clients/storage/GraphStorageClient.h"
#include "clients/storage/InternalStorageClient.h"
#include "codec/RowWriterV2.h"
#include "common/base/Base.h"
#include "common/expression/ConstantExpression.h"
#include "common/meta/SchemaManager.h"
#include "common/utils/NebulaKeyUtils.h"
#include "kvstore/LogEncoder.h"
#include "storage/transaction/TransactionUtils.h"
namespace nebula {
namespace storage {
struct TossTestUtils {
static std::vector<nebula::Value> genSingleVal(int n) {
boost::uuids::random_generator gen;
std::vector<nebula::Value> ret(2);
ret[0].setInt(n);
ret[1].setStr(boost::uuids::to_string(gen()));
return ret;
}
static std::vector<std::vector<nebula::Value>> genValues(size_t num) {
boost::uuids::random_generator gen;
std::vector<std::vector<nebula::Value>> ret(num);
for (auto i = 0U; i != num; ++i) {
ret[i].resize(2);
int32_t n = 1024 * (1 + i);
ret[i][0].setInt(n);
ret[i][1].setStr(boost::uuids::to_string(gen()));
}
return ret;
}
static std::string dumpDataSet(const DataSet& ds) {
std::stringstream oss;
for (auto&& it : folly::enumerate(ds.colNames)) {
oss << "\ncolNames[" << it.index << "]=" << *it;
}
oss << "\n";
oss << dumpRows(ds.rows);
return oss.str();
}
static std::string concatValues(const std::vector<nebula::Value>& vals) {
if (vals.empty()) {
return "";
}
std::ostringstream oss;
for (auto& val : vals) {
oss << val << ',';
}
std::string ret = oss.str();
return ret.substr(0, ret.size() - 1);
}
static std::string dumpValues(const std::vector<Value>& vals) {
std::stringstream oss;
oss << "vals.size() = " << vals.size() << "\n";
for (auto& val : vals) {
oss << val.toString() << "\n";
}
return oss.str();
}
static std::string dumpRows(const std::vector<Row>& rows) {
std::stringstream oss;
oss << "rows.size() = " << rows.size() << "\n";
for (auto& row : rows) {
oss << "row.size()=" << row.size() << "\n";
oss << row.toString() << "\n";
}
return oss.str();
}
static std::string hexVid(int64_t vid) {
std::string str(reinterpret_cast<char*>(&vid), sizeof(int64_t));
return folly::hexlify(str);
}
static std::string hexEdgeId(const cpp2::EdgeKey& ek) {
return hexVid(ek.get_src().getInt()) + hexVid(ek.get_dst().getInt());
}
static std::vector<std::string> splitNeiResults(std::vector<std::string>& svec) {
std::vector<std::string> ret;
for (auto& str : svec) {
auto sub = splitNeiResult(str);
ret.insert(ret.end(), sub.begin(), sub.end());
}
return ret;
}
static bool compareSize(const std::vector<std::string>& svec, size_t expect) {
auto equalSize = svec.size() == expect;
if (!equalSize) {
LOG(INFO) << "compareSize failed: expect=" << expect;
print_svec(svec);
}
return equalSize;
}
static std::vector<std::string> splitNeiResult(folly::StringPiece str) {
std::vector<std::string> ret;
auto begin = str.begin();
auto end = str.end();
if (str.startsWith("[[")) {
begin++;
begin++;
}
if (str.endsWith("]]")) {
end--;
end--;
}
str.assign(begin, end);
folly::split("],[", str, ret);
if (ret.size() == 1U && ret.back() == "__EMPTY__") {
ret.clear();
}
return ret;
}
static void print_svec(const std::vector<std::string>& svec) {
LOG(INFO) << "svec.size()=" << svec.size();
for (auto& str : svec) {
LOG(INFO) << str;
}
}
static cpp2::NewEdge toVertexIdEdge(const cpp2::NewEdge& e) {
cpp2::NewEdge ret(e);
(*ret.key_ref())
.set_src(std::string(reinterpret_cast<const char*>(&e.get_key().get_src().getInt()), 8));
(*ret.key_ref())
.set_dst(std::string(reinterpret_cast<const char*>(&e.get_key().get_dst().getInt()), 8));
return ret;
}
static cpp2::EdgeKey makeEdgeKeyS(const cpp2::EdgeKey& input) {
if (input.src.type() == Value::Type::STRING) {
return input;
}
cpp2::EdgeKey ret(input);
ret.set_src(std::string(reinterpret_cast<const char*>(&input.get_src().getInt()), 8));
ret.set_dst(std::string(reinterpret_cast<const char*>(&input.get_dst().getInt()), 8));
return ret;
}
static std::vector<nebula::Value> makeISValue(int64_t iVal) {
boost::uuids::random_generator gen;
std::vector<nebula::Value> vals(2);
vals[0].setInt(iVal);
vals[1].setStr(boost::uuids::to_string(gen()));
return vals;
}
// generate a vector of values, 1st is ant i64, 2nd is a random string.
static std::vector<std::vector<nebula::Value>> genISValues(size_t num) {
std::vector<std::vector<nebula::Value>> ret;
for (auto i = 0U; i != num; ++i) {
int32_t n = 1024 * (1 + i);
ret.emplace_back(makeISValue(n));
}
return ret;
}
// generate num different edges with same dst
// the first src is dst + 1, and increase 1 for each
static std::vector<cpp2::NewEdge> makeNeighborEdges(int64_t dst, int edgeType, size_t num) {
auto values = genISValues(num);
std::vector<cpp2::NewEdge> edges;
auto rank = 0;
for (auto i = 0U; i < num; ++i) {
auto src = dst + i + 1;
auto ekey = makeEdgeKeyI(src, edgeType, rank, dst);
edges.emplace_back();
edges.back().set_key(std::move(ekey));
edges.back().set_props(std::move(values[i]));
}
return edges;
}
static cpp2::NewEdge makeEdge(int64_t src, int edgeType) {
cpp2::NewEdge edge;
edge.set_key(makeEdgeKeyI(src, edgeType, 0, src + 1));
edge.set_props(makeISValue(1024));
return edge;
}
static cpp2::NewEdge makeEdgeS(int64_t src, int edgeType) {
cpp2::NewEdge edge = makeEdge(src, edgeType);
edge.key = makeEdgeKeyS(edge.key);
return edge;
}
static cpp2::NewEdge makeTwinEdge(const cpp2::NewEdge& oldEdge) {
cpp2::NewEdge newEdge(oldEdge);
auto newVal = makeISValue(newEdge.props[0].getInt() + 1024);
newEdge.set_props(newVal);
return newEdge;
}
static std::vector<std::string> makeColNames(size_t n) {
std::vector<std::string> colNames;
for (auto i = 0U; i < n; ++i) {
colNames.emplace_back(folly::sformat("c{}", i + 1));
}
return colNames;
}
static std::vector<meta::cpp2::ColumnDef> makeColDefs(
const std::vector<nebula::cpp2::PropertyType>& types) {
auto N = types.size();
auto colNames = makeColNames(N);
std::vector<meta::cpp2::ColumnDef> columnDefs(N);
for (auto i = 0U; i != N; ++i) {
columnDefs[i].set_name(colNames[i]);
meta::cpp2::ColumnTypeDef colTypeDef;
colTypeDef.set_type(types[i]);
columnDefs[i].set_type(colTypeDef);
columnDefs[i].set_nullable(true);
}
return columnDefs;
}
}; // end TossTestUtils
} // namespace storage
} // namespace nebula
// ===== END =====
// ===== BEGIN c =====
/**
**************************************************************************************
* @file main.c
* @author shaokairu
* @date 2021.7.8
* @brief This file includes the main program body
**************************************************************************************
*/
/* Includes --------------------------------------------------------------------------*/
#include "main.h"
#include "sys.h"
#include "delay.h"
#include "usart.h"
#include "led.h"
#include "adc.h"
#include "key.h"
#include "exti.h"
#include "timer.h"
#include "lcd.h"
#include "plot.h"
#include "fitted.h"
#include "filter.h"
/* Exported variables ------------------------------------------------------------------*/
uint16_t Ladc1=0, Ladc2=0, Ladc3=0;
uint8_t penState = 0; // 0 pen up, 1 pen down
double x, y; // axis position
/**
*@brief The application entry point.
*@param None
*@retval int
*/
int main(void)
{
uint8_t i;
/* MCU Configuration--------------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
Stm32_Clock_Init(RCC_PLL_MUL9);
/* Initialize all configured peripherals */
delay_init(72);
uart_init(115200);
LED_Init();
KEY_Init();
ADC1_Init();
EXTI_Init();
TIM3_Init(719, 199);
LCD_Init();
/* Pragram begin configuration----------------------------------------------------*/
/* Drawing Area Set*/
POINT_COLOR = RED;
LCD_Clear(BLUE);
LCD_Fill( 0, 0, 239, 160, WHITE);
LCD_DrawRectangle( 0, 0, 239, 160); // plot border
LCD_DrawRectangle( 1, 1, 238, 159);
LCD_DrawRectangle( 12, 8, 227, 152); // drawing border
LCD_DrawRectangle( 66, 44, 173, 116); // high-accuracy border
LCD_DrawLine( 0, 80, 239, 80); // centre line
LCD_DrawLine( 119, 0, 119, 160);
/* Drawing Paramter List */
BACK_COLOR = BLUE;
LCD_ShowString( 42, 161,240, 24, 24, "Paramter List");
POINT_COLOR = BROWN;
LCD_DrawRectangle( 14, 185, 225, 315); // border
LCD_DrawRectangle( 15, 186, 224, 314);
LCD_DrawRectangle( 16, 187, 223, 313);
LCD_Fill( 17, 188, 222, 312, WHITE); // background
POINT_COLOR = BLACK;
BACK_COLOR = WHITE;
LCD_ShowString( 20, 190, 240, 16, 16, "ADC1: "); // paramter location
LCD_ShowString( 20, 206, 240, 16, 16, "ADC2: ");
LCD_ShowString( 20, 222, 240, 16, 16, "ADC3: ");
LCD_ShowString( 20, 238, 240, 16, 16, "x: ");
LCD_ShowString( 70, 238, 240, 16, 16, "mm");
LCD_ShowString( 20, 254, 240, 16, 16, "y: ");
LCD_ShowString( 70, 254, 240, 16, 16, "mm");
POINT_COLOR = MAGENTA;
LCD_ShowString( 20, 270, 240, 16, 16, "pen up ");
POINT_COLOR = BLACK;
// draw_point_graph( -7, 0,119, 80, CYAN); // drawing point
/* Infinite loop */
while(1)
{
LCD_ShowNum( 56, 190, Ladc1, 6, 16); // paramter display
LCD_ShowNum( 56, 206, Ladc2, 6, 16);
LCD_ShowNum( 56, 222, Ladc3, 6, 16);
/* detemine whether the pen is down */
POINT_COLOR = MAGENTA;
if(Ladc3 > 695)
{
LCD_ShowString( 20, 270, 240, 16, 16, "pen down");
penState = 1;
}
else
{
LCD_ShowString( 20, 270, 240, 16, 16, "pen up ");
penState = 0;
}
POINT_COLOR = BLACK;
//printf("%d\r\n", Ladc1);
if(penState == 1)
{
delay_ms(500);
x = fitted_position_x(Ladc1 - Ladc3, Ladc2);
y = - fitted_position_y(Ladc1 - Ladc3, Ladc2); // because
printf("%lf,%lf\r\n",x,y);
if(x < 0)
{
LCD_ShowString( 35, 238, 240, 16, 16, "-");
LCD_ShowNum( 40, 238, -x, 3, 16);
}
else
{
LCD_ShowString( 35, 238, 240, 16, 16, " ");
LCD_ShowNum( 40, 238, x, 3, 16);
}
if( y< 0)
{
LCD_ShowString( 40, 254, 240, 16, 16, "-");
LCD_ShowNum( 40, 254, -y, 3, 16);
}
else
{
LCD_ShowString( 40, 254, 240, 16, 16, " ");
LCD_ShowNum( 40, 254, y, 3, 16);
}
draw_point_graph( x, y, 119, 80, BLACK);
}
}
}
/**********************************END OF FILE*****************************************/
// ===== END =====
// ===== BEGIN c =====
#import "OSPlatform.h"
NS_ASSUME_NONNULL_BEGIN
@interface OSImage (QRCode)
+ (OSImage *_Nullable )QRImageWithString:(NSString *)dataString
withSize:(CGSize)requestedSize;
- (NSString *)QRCodeString;
+ (void) QRImageWithString:(NSString*) dataString
scaledSize:(CGSize)requestedSize
completionQueue:(dispatch_queue_t _Nullable)completionQueue
completionBlock:(void (^)(OSImage * _Nullable image))completionBlock;
@end
NS_ASSUME_NONNULL_END
// ===== END =====
// ===== BEGIN c =====
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
//defining the type byte
typedef uint8_t BYTE;
//defining the size of the block
#define block 512
//defining the size of the file name
#define filenamesize 8
bool is_start_of_jpeg(BYTE buffer[]);
int main(int argc, char *argv[])
{
//if it has no command-line argument
if (argc != 2)
{
printf("Missing command-line argument!\n");
return 1;
}
FILE *inside_file = fopen(argv[1], "r");
//if there is no file
if (inside_file == NULL)
{
printf("Missing file!\n");
return 1;
}
BYTE buffer[block];
bool found_first_jpeg = false;
int number_of_files = 0;
FILE *jpeg;
//reading the file and restoring the jpegs
while (fread(buffer, block, 1, inside_file))
{
//starts or close a jpeg file
if (is_start_of_jpeg(buffer))
{
if (!found_first_jpeg)
{
found_first_jpeg = true;
}
else
{
fclose(jpeg);
}
char filename[filenamesize];
sprintf(filename, "%03i.jpg", number_of_files++);
jpeg = fopen(filename, "w");
if (jpeg == NULL)
{
return 1;
}
fwrite(buffer, block, 1, jpeg);
}
//keeps writing in the same jpeg file
else if (found_first_jpeg)
{
fwrite(buffer, block, 1, jpeg);
}
}
fclose(jpeg);
fclose(inside_file);
}
//check if it is the beggining of a jpeg
bool is_start_of_jpeg(BYTE buffer[])
{
return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0;
}
// ===== END =====
// ===== BEGIN c =====
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2018-2019, The Qwertycoin developers
//
// This file is part of Qwertycoin.
//
// Qwertycoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Qwertycoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Qwertycoin. If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <atomic>
#include <functional>
#include <map>
#include <string>
#include <thread>
#include <vector>
#include "BlockingQueue.h"
#include "ConsoleTools.h"
#ifndef _WIN32
#include <sys/select.h>
#endif
namespace Common {
class AsyncConsoleReader {
public:
AsyncConsoleReader();
~AsyncConsoleReader();
void start();
bool getline(std::string& line);
void stop();
bool stopped() const;
void pause();
void unpause();
private:
void consoleThread();
bool waitInput();
std::atomic<bool> m_stop;
std::thread m_thread;
BlockingQueue<std::string> m_queue;
};
class ConsoleHandler {
public:
~ConsoleHandler();
typedef std::function<bool(const std::vector<std::string> &)> ConsoleCommandHandler;
std::string getUsage() const;
void setHandler(const std::string& command, const ConsoleCommandHandler& handler, const std::string& usage = "");
void requestStop();
bool runCommand(const std::vector<std::string>& cmdAndArgs);
void start(bool startThread = true, const std::string& prompt = "", Console::Color promptColor = Console::Color::Default);
void stop();
void wait();
void pause();
void unpause();
private:
typedef std::map<std::string, std::pair<ConsoleCommandHandler, std::string>> CommandHandlersMap;
virtual void handleCommand(const std::string& cmd);
void handlerThread();
std::thread m_thread;
std::string m_prompt;
Console::Color m_promptColor = Console::Color::Default;
CommandHandlersMap m_handlers;
AsyncConsoleReader m_consoleReader;
};
}
// ===== END =====
// ===== BEGIN c =====
//
// RTMeetKitDelegate.h
// RTMeetEngine
//
// Created by EricTao on 16/11/10.
// Copyright © 2016年 EricTao. All rights reserved.
//
#ifndef RTMeetKitDelegate_h
#define RTMeetKitDelegate_h
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#import <AppKit/AppKit.h>
#endif
@protocol RTMeetKitDelegate <NSObject>
@required
/**
加入会议成功的回调
@param strAnyRTCId 会议号(在开发者业务系统中保持唯一的Id);
说明:加入会议成功。
*/
- (void)onRTCJoinMeetOK:(NSString*)strAnyRTCId;
/**
加入会议失败
@param strAnyRTCId 会议号(在开发者业务系统中保持唯一的Id);
@param nCode 状态码,错误原因可查看nCode对应原因;
说明:加入会议失败。
*/
- (void)onRTCJoinMeetFailed:(NSString*)strAnyRTCId withCode:(int)nCode;
/**
离开会议
@param nCode 状态码,错误原因可查看nCode对应原因;
说明:离开会议状态回调。
*/
-(void)onRTCLeaveMeet:(int) nCode;
/**
其他与会者加入(音视频)
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流);
@param strUserId 开发者自己平台的Id;
@param strUserData 开发者自己平台的相关信息(昵称,头像等);
说明:其他与会者进入会议的回调,开发者需调用设置其他与会者视频窗口(setRTCVideoRender)方法。
*/
-(void)onRTCOpenVideoRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData;
/**
其他与会者离开(音视频)
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流);
@param strUserId 开发者自己平台的Id;
说明:其他与会者离开将会回调此方法;需本地移除与会者视频视图。
*/
-(void)onRTCCloseVideoRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId;
/**
用户开启桌面共享
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流);
@param strUserId 开发者自己平台的Id;
@param strUserData 开发者自己平台的相关信息(昵称,头像等);
说明:开发者需调用设置其他与会者视频窗口(setRTCVideoRender)方法
*/
-(void)onRTCOpenScreenRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData;
/**
用户退出桌面共享
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strRTCPubId RTC服务生成流的ID (用于标识与会者发布的流);
@param strUserId 开发者自己平台的Id;
说明:其他与会者离开将会回调此方法;需本地移除屏幕共享窗口。
*/
-(void)onRTCCloseScreenRender:(NSString*)strRTCPeerId withRTCPubId:(NSString *)strRTCPubId withUserId:(NSString*)strUserId;
/**
其他与会者视频窗口的对音视频的操作
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param bAudio yes为打开音频,no为关闭音频
@param bVideo yes为打开视频,no为关闭视频
说明:比如对方关闭了音频,对方关闭了视频
*/
-(void)onRTCAVStatus:(NSString*) strRTCPeerId withAudio:(BOOL)bAudio withVideo:(BOOL)bVideo;
/**
RTC音频检测
@param strRTCPeerId RTC服务生成的与会者标识Id(用于标识与会者用户,每次随机生成)
@param strUserId 连麦者在自己平台的用户Id;
@param nLevel 音频检测音量;(0~100)
@param nTime 音频检测在nTime毫秒内不会再回调该方法(单位:毫秒);
说明:对方关闭音频后(setLocalAudioEnable为NO),该回调将不再回调;对方关闭音频检测后(setAudioActiveCheck为NO),该回调也将不再回调。
*/
-(void)onRTCAudioActive:(NSString*)strRTCPeerId withUserId:(NSString *)strUserId withAudioLevel:(int)nLevel withShowTime:(int)nTime;
/**
视频窗口大小的回调
@param videoView 视频窗口
@param size 视频的分辨率
说明:与会者或者自己视频窗口大小变化的回调。一般处理视频窗口第一针视频显示:美颜相机没有该回调
*/
#if TARGET_OS_IPHONE
-(void) onRTCViewChanged:(UIView*)videoView didChangeVideoSize:(CGSize)size;
#else
#endif
@optional
/**
网络状态
@param strRTCPeerId RTC服务生成的与会者标识Id(用于标识与会者用户,每次随机生成)
@param strUserId 连麦者在自己平台的用户Id;
@param nNetSpeed 网络上行
@param nPacketLost 丢包率
*/
- (void)onRtcNetworkStatus:(NSString*)strRTCPeerId withUserId:(NSString *)strUserId withNetSpeed:(int)nNetSpeed withPacketLost:(int)nPacketLost;
/**
收到消息回调
@param strUserId 发送消息者在自己平台下的Id;
@param strUserName 发送消息者的昵称
@param strUserHeaderUrl 发送者的头像
@param strContent 消息内容
说明:该参数来源均为发送消息时所带参数。
*/
- (void)onRTCUserMessage:(NSString*)strUserId withUserName:(NSString*)strUserName withUserHeader:(NSString*)strUserHeaderUrl withContent:(NSString*)strContent;
/**
主持人上线(只有主持模式下的游客身份登录才有用)
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strUserId 开发者自己平台的Id;
@param strUserData 开发者自己平台的相关信息(昵称,头像等);
*/
- (void)onRTCHosterOnLine:(NSString*)strRTCPeerId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData;
/**
主持人下线(只有主持模式下的游客身份登录才有用)
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
*/
- (void)onRTCHosterOffLine:(NSString*)strRTCPeerId;
/**
1v1开启
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
@param strUserId 开发者自己平台的Id;
@param strUserData 开发者自己平台的相关信息(昵称,头像等);
*/
- (void)onRTCTalkOnlyOn:(NSString*)strRTCPeerId withUserId:(NSString*)strUserId withUserData:(NSString*)strUserData;
/**
1v1关闭
@param strRTCPeerId RTC服务生成的标识Id (用于标识与会者,每次加入会议随机生成);
*/
- (void)onRtcTalkOnlyOff:(NSString*)strRTCPeerId;
/**
检测服务链接与否
@param bOk YES/NO 成功/失败
*/
- (void)onRTCCheckConnectionRealtime:(BOOL)bOk;
@end
#endif /* RTMeetKitDelegate_h */
// ===== END =====
// ===== BEGIN c =====
/*
* The Spread Toolkit.
*
* The contents of this file are subject to the Spread Open-Source
* License, Version 1.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.spread.org/license/
*
* or in the file ``license.txt'' found in this distribution.
*
* Software distributed under the License is distributed on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Creators of Spread are:
* Yair Amir, Michal Miskin-Amir, Jonathan Stanton, John Schultz.
*
* Copyright (C) 1993-2006 Spread Concepts LLC <[email protected]>
*
* All Rights Reserved.
*
* Major Contributor(s):
* ---------------
* Ryan Caudy [email protected] - contributions to process groups.
* Claudiu Danilov [email protected] - scalable wide area support.
* Cristina Nita-Rotaru [email protected] - group communication security.
* Theo Schlossnagle [email protected] - Perl, autoconf, old skiplist.
* Dan Schoenblum [email protected] - Java interface.
*
*/
#ifndef INC_ALARM
#define INC_ALARM
#include <stdio.h>
#include "arch.h"
#define DEBUG 0x00000001
#define EXIT 0x00000002
#define PRINT 0x00000004
/* new type to replace general prints */
#define SYSTEM 0x00000004
#define DATA_LINK 0x00000010
#define NETWORK 0x00000020
#define PROTOCOL 0x00000040
#define SESSION 0x00000080
#define CONF 0x00000100
#define MEMB 0x00000200
#define FLOW_CONTROL 0x00000400
#define STATUS 0x00000800
#define EVENTS 0x00001000
#define GROUPS 0x00002000
#define HOP 0x00004000
#define OBJ_HANDLER 0x00008000
#define MEMORY 0x00010000
#define ROUTE 0x00020000
#define QOS 0x00040000
#define RING 0x00080000
#define TCP_HOP 0x00100000
#define SKIPLIST 0x00200000
#define ACM 0x00400000
#define SECURITY 0x00800000
#define ALL 0xffffffff
#define NONE 0x00000000
/* Priority levels */
#define SPLOG_DEBUG 1 /* Program information that is only useful for debugging.
Will normally be turned off in operation. */
#define SPLOG_INFO 2 /* Program reports information that may be useful for
performance tuning, analysis, or operational checks. */
#define SPLOG_WARNING 3 /* Program encountered a situation that is not erroneous,
but is uncommon and may indicate an error. */
#define SPLOG_ERROR 4 /* Program encountered an error that can be recovered from. */
#define SPLOG_CRITICAL 5 /* Program will not exit, but has only temporarily recovered
and without help may soon fail. */
#define SPLOG_FATAL 6 /* Program will exit() or abort(). */
#define SPLOG_PRINT 7 /* Program should always print this information */
#define SPLOG_PRINT_NODATE 8 /* Program should always print this information, but the datestamp should be omitted. */
#ifdef HAVE_GOOD_VARGS
void Alarmp( int16 priority, int32 type, char *message, ...);
void Alarm( int32 type, char *message, ...);
#else
void Alarm();
#endif
void Alarm_set_output(char *filename);
void Alarm_enable_timestamp(char *format);
void Alarm_disable_timestamp(void);
void Alarm_set_types(int32 mask);
void Alarm_clear_types(int32 mask);
int32 Alarm_get_types(void);
void Alarm_set_priority(int16 priority);
int16 Alarm_get_priority(void);
void Alarm_set_interactive(void);
int Alarm_get_interactive(void);
#define IP1( address ) ( ( 0xFF000000 & (address) ) >> 24 )
#define IP2( address ) ( ( 0x00FF0000 & (address) ) >> 16 )
#define IP3( address ) ( ( 0x0000FF00 & (address) ) >> 8 )
#define IP4( address ) ( ( 0x000000FF & (address) ) )
#endif /* INC_ALARM */
// ===== END =====
// ===== BEGIN c =====
/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef QUECTEL_BG96_H_
#define QUECTEL_BG96_H_
#ifdef TARGET_FF_ARDUINO
#ifndef MBED_CONF_QUECTEL_BG96_TX
#define MBED_CONF_QUECTEL_BG96_TX D1
#endif
#ifndef MBED_CONF_QUECTEL_BG96_RX
#define MBED_CONF_QUECTEL_BG96_RX D0
#endif
#endif /* TARGET_FF_ARDUINO */
#include "DigitalOut.h"
#include "AT_CellularDevice.h"
namespace mbed {
class QUECTEL_BG96 : public AT_CellularDevice {
public:
QUECTEL_BG96(FileHandle *fh, PinName pwr = NC, bool active_high = true, PinName rst = NC);
protected: // AT_CellularDevice
virtual AT_CellularNetwork *open_network_impl(ATHandler &at);
virtual AT_CellularContext *create_context_impl(ATHandler &at, const char *apn, bool cp_req = false, bool nonip_req = false);
virtual AT_CellularInformation *open_information_impl(ATHandler &at);
virtual void set_ready_cb(Callback<void()> callback);
virtual nsapi_error_t hard_power_on();
virtual nsapi_error_t hard_power_off();
virtual nsapi_error_t soft_power_on();
virtual nsapi_error_t init();
public:
void handle_urc(FileHandle *fh);
private:
nsapi_error_t press_power_button(uint32_t timeout);
bool _active_high;
DigitalOut _pwr;
DigitalOut _rst;
};
} // namespace mbed
#endif // QUECTEL_BG96_H_
// ===== END =====
// ===== BEGIN c =====
/*
$info$
category: backend ~ IR to host code generation
tags: backend|shared
$end_info$
*/
#pragma once
#include <FEXCore/Utils/CompilerDefs.h>
#include <cstdint>
#include <string>
namespace FEXCore {
namespace IR {
class IRListView;
class RegisterAllocationData;
}
namespace Core {
struct DebugData;
struct ThreadState;
struct CpuStateFrame;
}
namespace CodeSerialize {
struct CodeObjectFileSection;
}
namespace CPU {
class InterpreterCore;
class JITCore;
class LLVMCore;
class CPUBackend {
public:
virtual ~CPUBackend() = default;
/**
* @return The name of this backend
*/
[[nodiscard]] virtual std::string GetName() = 0;
/**
* @brief Tells this CPUBackend to compile code for the provided IR and DebugData
*
* The returned pointer needs to be long lived and be executable in the host environment
* FEXCore's frontend will store this pointer in to a cache for the current RIP when this was executed
*
* This is a thread specific compilation unit since there is one CPUBackend per guest thread
*
* If NeedsOpDispatch is returning false then IR and DebugData may be null and the expectation is that the code will still compile
* FEXCore::Core::ThreadState* is valid at the time of compilation.
*
* @param IR - IR that maps to the IR for this RIP
* @param DebugData - Debug data that is available for this IR indirectly
*
* @return An executable function pointer that is theoretically compiled from this point.
* Is actually a function pointer of type `void (FEXCore::Core::ThreadState *Thread)
*/
[[nodiscard]] virtual void *CompileCode(uint64_t Entry,
FEXCore::IR::IRListView const *IR,
FEXCore::Core::DebugData *DebugData,
FEXCore::IR::RegisterAllocationData *RAData) = 0;
/**
* @brief Relocates a block of code from the JIT code object cache
*
* @param Entry - RIP of the entry
* @param SerializationData - Serialization data referring to the object cache for `Entry`
*
* @return An executable function pointer relocated from the cache object
*/
[[nodiscard]] virtual void *RelocateJITObjectCode(uint64_t Entry, CodeSerialize::CodeObjectFileSection const *SerializationData) { return nullptr; }
/**
* @brief Function for mapping memory in to the CPUBackend's visible space. Allows setting up virtual mappings if required
*
* @return Currently unused
*/
[[nodiscard]] virtual void *MapRegion(void *HostPtr, uint64_t GuestPtr, uint64_t Size) = 0;
/**
* @brief This is post-setup initialization that is called just before code executino
*
* Guest memory is available at this point and ThreadState is valid
*/
virtual void Initialize() {}
/**
* @brief Lets FEXCore know if this CPUBackend needs IR and DebugData for CompileCode
*
* This is useful if the FEXCore Frontend hits an x86-64 instruction that isn't understood but can continue regardless
*
* This is useful for example, a VM based CPUbackend
*
* @return true if it needs the IR
*/
[[nodiscard]] virtual bool NeedsOpDispatch() = 0;
void ExecuteDispatch(FEXCore::Core::CpuStateFrame *Frame) {
DispatchPtr(Frame);
}
virtual void ClearCache() {}
virtual bool IsAddressInJITCode(uint64_t Address, bool IncludeDispatcher = true) const { return false; }
/**
* @brief Does this CPUBackend need its IR to stick around for correct emulation
*
* This should only be used on the interpreter, all other backends can clear their IR
*/
virtual bool NeedsRetainedIRCopy() const { return false; }
/**
* @brief Clear any relocations after JIT compiling
*/
virtual void ClearRelocations() {}
using AsmDispatch = FEX_NAKED void(*)(FEXCore::Core::CpuStateFrame *Frame);
using JITCallback = FEX_NAKED void(*)(FEXCore::Core::CpuStateFrame *Frame, uint64_t RIP);
JITCallback CallbackPtr{};
protected:
AsmDispatch DispatchPtr{};
};
}
}
// ===== END =====
// ===== BEGIN c =====
#ifndef _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_
#define _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_
#include <jrate/mem/IMemoryArea.h>
#define DISPLAY_SIZE 64
namespace jrate { namespace mem {
class DisplayRefChecker;
typedef DisplayRefChecker DisplayRefChecker_t;
/**
* This class implements a display based memory reference
* checker. For a description of the technique used to
* implement diplay based reference checks please see:
* "A. Corsaro, R. Cytron, Efficient Memory Reference Checks
* in Real-Time Java, LCTES 2003".
*
* @author Angelo Corsaro <[email protected]>
*/
class DisplayRefChecker {
public:
DisplayRefChecker();
template <typename T> DisplayRefChecker(T* ma) {
typeID_ = ma->typeID();
display_[0] = (size_t)this;
depth_ = 0;
}
template <typename T> void init(T* ma) {
typeID_ = ma->typeID();
display_[0] = (size_t)this;
depth_ = 0;
}
~DisplayRefChecker();
public:
bool checkReference(const jrate::mem::DisplayRefChecker& from);
bool checkReference();
public:
void validate(jrate::mem::DisplayRefChecker& parent);
void invalidate();
public:
inline bool isPrimordial() {
return typeID_ & jrate::mem::PRIMORDIAL_MEMORY;
}
private:
int typeID_;
int depth_;
// TODO: Currently the display is statically allocated, we should
// allocate this in the memory area that owns it.
size_t display_[DISPLAY_SIZE];
};
} /* jrate */ } /* mem */
#endif // _JRATE_MEM_DISPLAY_REFERENCE_CHECKER_H_
// ===== END =====
// ===== BEGIN c =====
/**
* (C) Copyright 2017-2019 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.
*
* GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE
* The Government's rights to use, modify, reproduce, release, perform, display,
* or disclose this software are subject to the terms of the Apache License as
* provided in Contract No. B609815.
* Any reproduction of computer software, computer software documentation, or
* portions thereof marked with this legend must also reproduce the markings.
*/
/**
* rdb: Internal Declarations
*/
#ifndef RDB_INTERNAL_H
#define RDB_INTERNAL_H
#include <abt.h>
#include <raft.h>
#include <gurt/hash.h>
#include <daos/lru.h>
#include <daos/rpc.h>
#include "rdb_layout.h"
/* rdb_raft.c (parts required by struct rdb) **********************************/
enum rdb_raft_event_type {
RDB_RAFT_STEP_UP,
RDB_RAFT_STEP_DOWN
};
struct rdb_raft_event {
enum rdb_raft_event_type dre_type;
uint64_t dre_term;
};
/* rdb.c **********************************************************************/
struct rdb {
/* General fields */
d_list_t d_entry; /* in rdb_hash */
uuid_t d_uuid; /* of database */
ABT_mutex d_mutex; /* mainly for using CVs */
int d_ref; /* of callers and RPCs */
ABT_cond d_ref_cv; /* for d_ref decrements */
struct rdb_cbs *d_cbs; /* callers' callbacks */
void *d_arg; /* for d_cbs callbacks */
struct daos_lru_cache *d_kvss; /* rdb_kvs cache */
daos_handle_t d_pool; /* VOS pool */
daos_handle_t d_mc; /* metadata container */
/* rdb_raft fields */
raft_server_t *d_raft;
daos_handle_t d_lc; /* log container */
struct rdb_lc_record d_lc_record; /* of d_lc */
daos_handle_t d_slc; /* staging log container */
struct rdb_lc_record d_slc_record; /* of d_slc */
d_rank_list_t *d_replicas;
uint64_t d_applied; /* last applied index */
uint64_t d_debut; /* first entry in a term */
ABT_cond d_applied_cv; /* for d_applied updates */
struct d_hash_table d_results; /* rdb_raft_result hash */
d_list_t d_requests; /* RPCs waiting for replies */
d_list_t d_replies; /* RPCs received replies */
ABT_cond d_replies_cv; /* for d_replies enqueues */
struct rdb_raft_event d_events[2]; /* rdb_raft_events queue */
int d_nevents; /* d_events queue len from 0 */
ABT_cond d_events_cv; /* for d_events enqueues */
uint64_t d_compact_thres;/* of compactable entries */
ABT_cond d_compact_cv; /* for base updates */
bool d_stop; /* for rdb_stop() */
ABT_thread d_timerd;
ABT_thread d_callbackd;
ABT_thread d_recvd;
ABT_thread d_compactd;
};
/* Current rank */
#define DF_RANK "%u"
static inline d_rank_t
DP_RANK(void)
{
d_rank_t rank;
int rc;
rc = crt_group_rank(NULL, &rank);
D_ASSERTF(rc == 0, "%d\n", rc);
return rank;
}
#define DF_DB DF_UUID"["DF_RANK"]"
#define DP_DB(db) DP_UUID(db->d_uuid), DP_RANK()
/* Number of "base" references that the rdb_stop() path expects to remain */
#define RDB_BASE_REFS 1
int rdb_hash_init(void);
void rdb_hash_fini(void);
void rdb_get(struct rdb *db);
void rdb_put(struct rdb *db);
struct rdb *rdb_lookup(const uuid_t uuid);
/* rdb_raft.c *****************************************************************/
/*
* Per-raft_node_t INSTALLSNAPSHOT state
*
* dis_seq and dis_anchor track the last chunk successfully received by the
* follower.
*/
struct rdb_raft_is {
uint64_t dis_index; /* snapshot index */
uint64_t dis_seq; /* last sequence number */
struct rdb_anchor dis_anchor; /* last anchor */
};
/* Per-raft_node_t data */
struct rdb_raft_node {
d_rank_t dn_rank;
/* Leader fields */
uint64_t dn_term; /* of leader */
struct rdb_raft_is dn_is;
};
int rdb_raft_init(daos_handle_t pool, daos_handle_t mc,
const d_rank_list_t *replicas);
int rdb_raft_start(struct rdb *db);
void rdb_raft_stop(struct rdb *db);
void rdb_raft_resign(struct rdb *db, uint64_t term);
int rdb_raft_verify_leadership(struct rdb *db);
int rdb_raft_append_apply(struct rdb *db, msg_entry_t *mentry, void *result);
int rdb_raft_wait_applied(struct rdb *db, uint64_t index, uint64_t term);
void rdb_requestvote_handler(crt_rpc_t *rpc);
void rdb_appendentries_handler(crt_rpc_t *rpc);
void rdb_installsnapshot_handler(crt_rpc_t *rpc);
void rdb_raft_process_reply(struct rdb *db, raft_node_t *node, crt_rpc_t *rpc);
void rdb_raft_free_request(struct rdb *db, crt_rpc_t *rpc);
/* rdb_rpc.c ******************************************************************/
/*
* RPC operation codes
*
* These are for daos_rpc::dr_opc and DAOS_RPC_OPCODE(opc, ...) rather than
* crt_req_create(..., opc, ...). See src/include/daos/rpc.h.
*/
#define DAOS_RDB_VERSION 1
/* LIST of internal RPCS in form of:
* OPCODE, flags, FMT, handler, corpc_hdlr,
*/
#define RDB_PROTO_SRV_RPC_LIST \
X(RDB_REQUESTVOTE, \
0, &CQF_rdb_requestvote, \
rdb_requestvote_handler, NULL), \
X(RDB_APPENDENTRIES, \
0, &CQF_rdb_appendentries, \
rdb_appendentries_handler, NULL), \
X(RDB_INSTALLSNAPSHOT, \
0, &CQF_rdb_installsnapshot, \
rdb_installsnapshot_handler, NULL)
/* Define for RPC enum population below */
#define X(a, b, c, d, e) a
enum rdb_operation {
RDB_PROTO_SRV_RPC_LIST,
};
#undef X
extern struct crt_proto_format rdb_proto_fmt;
#define DAOS_ISEQ_RDB_OP /* input fields */ \
((uuid_t) (ri_uuid) CRT_VAR)
#define DAOS_OSEQ_RDB_OP /* output fields */ \
((int32_t) (ro_rc) CRT_VAR) \
((uint32_t) (ro_padding) CRT_VAR)
CRT_RPC_DECLARE(rdb_op, DAOS_ISEQ_RDB_OP, DAOS_OSEQ_RDB_OP)
#define DAOS_ISEQ_RDB_REQUESTVOTE /* input fields */ \
((struct rdb_op_in) (rvi_op) CRT_VAR) \
((msg_requestvote_t) (rvi_msg) CRT_VAR)
#define DAOS_OSEQ_RDB_REQUESTVOTE /* output fields */ \
((struct rdb_op_out) (rvo_op) CRT_VAR) \
((msg_requestvote_response_t) (rvo_msg) CRT_VAR)
CRT_RPC_DECLARE(rdb_requestvote, DAOS_ISEQ_RDB_REQUESTVOTE,
DAOS_OSEQ_RDB_REQUESTVOTE)
#define DAOS_ISEQ_RDB_APPENDENTRIES /* input fields */ \
((struct rdb_op_in) (aei_op) CRT_VAR) \
((msg_appendentries_t) (aei_msg) CRT_VAR)
#define DAOS_OSEQ_RDB_APPENDENTRIES /* output fields */ \
((struct rdb_op_out) (aeo_op) CRT_VAR) \
((msg_appendentries_response_t) (aeo_msg) CRT_VAR)
CRT_RPC_DECLARE(rdb_appendentries, DAOS_ISEQ_RDB_APPENDENTRIES,
DAOS_OSEQ_RDB_APPENDENTRIES)
struct rdb_local {
daos_iov_t rl_kds_iov; /* isi_kds buffer */
daos_iov_t rl_data_iov; /* isi_data buffer */
};
#define DAOS_ISEQ_RDB_INSTALLSNAPSHOT /* input fields */ \
((struct rdb_op_in) (isi_op) CRT_VAR) \
((msg_installsnapshot_t) (isi_msg) CRT_VAR) \
((uint32_t) (isi_padding) CRT_VAR) \
/* chunk sequence number */ \
((uint64_t) (isi_seq) CRT_VAR) \
/* chunk anchor */ \
((struct rdb_anchor) (isi_anchor) CRT_VAR) \
/* daos_key_desc_t[] */ \
((crt_bulk_t) (isi_kds) CRT_VAR) \
/* described by isi_kds */ \
((crt_bulk_t) (isi_data) CRT_VAR) \
/* Local fields (not sent over the network) */ \
((struct rdb_local) (isi_local) CRT_VAR)
#define DAOS_OSEQ_RDB_INSTALLSNAPSHOT /* output fields */ \
((struct rdb_op_out) (iso_op) CRT_VAR) \
((msg_installsnapshot_response_t) (iso_msg) CRT_VAR) \
((uint32_t) (iso_padding) CRT_VAR) \
/* chunk saved? */ \
((uint64_t) (iso_success) CRT_VAR) \
/* last seq number */ \
((uint64_t) (iso_seq) CRT_VAR) \
/* last anchor */ \
((struct rdb_anchor) (iso_anchor) CRT_VAR)
CRT_RPC_DECLARE(rdb_installsnapshot, DAOS_ISEQ_RDB_INSTALLSNAPSHOT,
DAOS_OSEQ_RDB_INS
// ===== END =====
// ===== BEGIN go =====
package main
import (
"context"
"flag"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
type pconsumer struct {
quit chan struct{}
done chan struct{}
recs chan []*kgo.Record
}
var (
brokers = flag.String("b", "", "comma delimited brokers to consume from")
topic = flag.String("t", "", "topic to consume")
group = flag.String("g", "", "group to consume in")
)
func (pc *pconsumer) consume(topic string, partition int32, cl *kgo.Client) {
fmt.Printf("Starting consume for t %s p %d\n", topic, partition)
for {
select {
case <-pc.quit:
pc.done <- struct{}{}
fmt.Printf("Closing consume for t %s p %d\n", topic, partition)
return
case recs := <-pc.recs:
// Mimick work to happen before committing records
time.Sleep(time.Duration(rand.Intn(150)+100) * time.Millisecond)
fmt.Printf("Some sort of work done, about to commit t %s p %d\n", topic, partition)
err := cl.CommitRecords(context.Background(), recs...)
if err != nil {
fmt.Printf("Error when committing offsets to kafka err: %v t: %s p: %d offset %d\n", err, topic, partition, recs[len(recs)-1].Offset+1)
}
}
}
}
type splitConsume struct {
mu sync.Mutex // gaurds assigning / losing vs. polling
consumers map[string]map[int32]pconsumer
}
func (s *splitConsume) assigned(_ context.Context, cl *kgo.Client, assigned map[string][]int32) {
s.mu.Lock()
defer s.mu.Unlock()
for topic, partitions := range assigned {
if s.consumers[topic] == nil {
s.consumers[topic] = make(map[int32]pconsumer)
}
for _, partition := range partitions {
pc := pconsumer{
quit: make(chan struct{}),
done: make(chan struct{}),
recs: make(chan []*kgo.Record),
}
s.consumers[topic][partition] = pc
go pc.consume(topic, partition, cl)
}
}
}
func (s *splitConsume) lost(_ context.Context, cl *kgo.Client, lost map[string][]int32) {
s.mu.Lock()
defer s.mu.Unlock()
for topic, partitions := range lost {
ptopics := s.consumers[topic]
for _, partition := range partitions {
pc := ptopics[partition]
delete(ptopics, partition)
if len(ptopics) == 0 {
delete(s.consumers, topic)
}
close(pc.quit)
fmt.Printf("Waiting for work to finish t %s p %d\n", topic, partition)
<-pc.done
}
}
}
func main() {
rand.Seed(time.Now().Unix())
flag.Parse()
if len(*group) == 0 {
fmt.Println("missing required group")
return
}
if len(*topic) == 0 {
fmt.Println("missing required topic")
return
}
s := &splitConsume{
consumers: make(map[string]map[int32]pconsumer),
}
opts := []kgo.Opt{
kgo.SeedBrokers(strings.Split(*brokers, ",")...),
kgo.ConsumerGroup(*group),
kgo.ConsumeTopics(*topic),
kgo.OnPartitionsAssigned(s.assigned),
kgo.OnPartitionsRevoked(s.lost),
kgo.OnPartitionsLost(s.lost),
kgo.DisableAutoCommit(),
kgo.BlockRebalanceOnPoll(),
}
cl, err := kgo.NewClient(opts...)
if err != nil {
panic(err)
}
// Check connectivity to cluster
err = cl.Ping(context.Background())
if err != nil {
panic(err)
}
s.poll(cl)
}
func (s *splitConsume) poll(cl *kgo.Client) {
for {
fetches := cl.PollRecords(context.Background(), 10000)
if fetches.IsClientClosed() {
return
}
fetches.EachError(func(_ string, _ int32, err error) {
panic(err)
})
fetches.EachTopic(func(t kgo.FetchTopic) {
s.mu.Lock()
tconsumers := s.consumers[t.Topic]
s.mu.Unlock()
if tconsumers == nil {
return
}
t.EachPartition(func(p kgo.FetchPartition) {
pc, ok := tconsumers[p.Partition]
if !ok {
return
}
select {
case pc.recs <- p.Records:
case <-pc.quit:
}
})
})
s.mu.Lock()
cl.AllowRebalance()
s.mu.Unlock()
}
}
// ===== END =====
// ===== BEGIN go =====
package mtcpclient
import (
"fmt"
"math"
"strconv"
"time"
"github.com/dachad/tcpgoon/tcpclient"
)
func collectConnectionsStatus(connectionsStatusRegistry *GroupOfConnections, statusChannel <-chan tcpclient.Connection) {
concurrentEstablished := 0
for {
newConnectionStatusReported := <-statusChannel
concurrentEstablished = updateConcurrentEstablished(concurrentEstablished, newConnectionStatusReported, connectionsStatusRegistry)
connectionsStatusRegistry.connections[newConnectionStatusReported.ID] = newConnectionStatusReported
}
}
func updateConcurrentEstablished(concurrentEstablished int, newConnectionStatusReported tcpclient.Connection, connectionsStatusRegistry *GroupOfConnections) int {
if tcpclient.IsOk(newConnectionStatusReported) {
concurrentEstablished++
connectionsStatusRegistry.metrics.maxConcurrentEstablished = int(math.Max(float64(concurrentEstablished),
float64(connectionsStatusRegistry.metrics.maxConcurrentEstablished)))
} else if tcpclient.IsOk(connectionsStatusRegistry.connections[newConnectionStatusReported.ID]) {
concurrentEstablished--
}
return concurrentEstablished
}
// ReportConnectionsStatus keeps printing on screen the summary of connections states
func ReportConnectionsStatus(gc GroupOfConnections, intervalBetweenUpdates int) {
for {
fmt.Println(gc)
if intervalBetweenUpdates == 0 {
break
}
time.Sleep(time.Duration(intervalBetweenUpdates) * time.Second)
}
}
// StartBackgroundReporting starts some goroutines (so it's not blocking) to capture and report data from the tcpclient
// routines. It initializes and returns the channel that will be used for these communications
func StartBackgroundReporting(numberConnections int, rinterval int) (chan tcpclient.Connection, *GroupOfConnections) {
// A connection may report up to 3 messages: Dialing -> Established -> Closed
const maxMessagesWeMayGetPerConnection = 3
connStatusCh := make(chan tcpclient.Connection, numberConnections*maxMessagesWeMayGetPerConnection)
connStatusTracker := newGroupOfConnections(numberConnections)
go ReportConnectionsStatus(*connStatusTracker, rinterval)
go collectConnectionsStatus(connStatusTracker, connStatusCh)
return connStatusCh, connStatusTracker
}
// FinalMetricsReport creates the final reporting summary
func FinalMetricsReport(gc GroupOfConnections) (output string) {
// Report Established Connections
output += "--- tcpgoon execution statistics ---\n" +
"Total established connections: " +
strconv.Itoa(len(gc.getConnectionsThatWentWell(true).connections)) + "\n" +
"Max concurrent established connections: " +
strconv.Itoa(gc.metrics.maxConcurrentEstablished) + "\n" +
"Number of established connections on closure: " +
strconv.Itoa(len(gc.getConnectionsThatAreOk().connections)) + "\n"
if gc.atLeastOneConnectionOK() {
output += gc.getConnectionsThatWentWell(true).pingStyleReport(successfulExecution)
}
if gc.AtLeastOneConnectionInError() {
output += gc.getConnectionsThatWentWell(false).pingStyleReport(failedExecution)
}
return output
}
// ===== END =====
// ===== BEGIN go =====
package pcf_handler
import (
"gofree5gc/lib/openapi/models"
"gofree5gc/src/pcf/logger"
"gofree5gc/src/pcf/pcf_handler/pcf_message"
"gofree5gc/src/pcf/pcf_producer"
"time"
"github.com/sirupsen/logrus"
)
var HandlerLog *logrus.Entry
func init() {
// init Pool
HandlerLog = logger.HandlerLog
}
func Handle() {
for {
select {
case msg, ok := <-pcf_message.PCFChannel:
if ok {
switch msg.Event {
case pcf_message.EventBDTPolicyCreate:
pcf_producer.CreateBDTPolicyContext(msg.HttpChannel, msg.HTTPRequest.Body.(models.BdtReqData))
case pcf_message.EventBDTPolicyGet:
bdtPolicyId := msg.HTTPRequest.Params["bdtPolicyId"]
pcf_producer.GetBDTPolicyContext(msg.HttpChannel, bdtPolicyId)
case pcf_message.EventBDTPolicyUpdate:
bdtPolicyId := msg.HTTPRequest.Params["bdtPolicyId"]
pcf_producer.UpdateBDTPolicyContext(msg.HttpChannel, bdtPolicyId, msg.HTTPRequest.Body.(models.BdtPolicyDataPatch))
case pcf_message.EventPostAppSessions:
pcf_producer.PostAppSessionsContext(msg.HttpChannel, msg.HTTPRequest.Body.(models.AppSessionContext))
case pcf_message.EventGetAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.GetAppSessionContext(msg.HttpChannel, appSessionId)
case pcf_message.EventDeleteAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.DeleteAppSessionContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(*models.EventsSubscReqData))
case pcf_message.EventModAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.ModAppSessionContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(models.AppSessionContextUpdateData))
case pcf_message.EventDeleteEventsSubsc:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.DeleteEventsSubscContext(msg.HttpChannel, appSessionId)
case pcf_message.EventUpdateEventsSubsc:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.UpdateEventsSubscContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(models.EventsSubscReqData))
case pcf_message.EventAMPolicyGet:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.GetPoliciesPolAssoId(msg.HttpChannel, PolAssoId)
case pcf_message.EventAMPolicyDelete:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.DeletePoliciesPolAssoId(msg.HttpChannel, PolAssoId)
case pcf_message.EventAMPolicyCreate:
pcf_producer.PostPolicies(msg.HttpChannel, msg.HTTPRequest.Body.(models.PolicyAssociationRequest))
case pcf_message.EventAMPolicyUpdate:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.UpdatePostPoliciesPolAssoId(msg.HttpChannel, PolAssoId, msg.HTTPRequest.Body.(models.PolicyAssociationUpdateRequest))
case pcf_message.EventSMPolicyCreate:
pcf_producer.CreateSmPolicy(msg.HttpChannel, msg.HTTPRequest.Body.(models.SmPolicyContextData))
case pcf_message.EventSMPolicyGet:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.GetSmPolicyContext(msg.HttpChannel, smPolicyId)
case pcf_message.EventSMPolicyUpdate:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.UpdateSmPolicyContext(msg.HttpChannel, smPolicyId, msg.HTTPRequest.Body.(models.SmPolicyUpdateContextData))
case pcf_message.EventSMPolicyDelete:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.DeleteSmPolicyContext(msg.HttpChannel, smPolicyId)
case pcf_message.EventSMPolicyNotify:
ReqURI := msg.HTTPRequest.Params["ReqURI"]
pcf_producer.HandleSmPolicyNotify(msg.HttpChannel, ReqURI, msg.HTTPRequest.Body.(models.PolicyDataChangeNotification))
// TODO: http event dispatcher
default:
HandlerLog.Warnf("Event[%s] has not implemented", msg.Event)
}
} else {
HandlerLog.Errorln("Channel closed!")
}
case <-time.After(time.Second * 1):
}
}
}
// ===== END =====
// ===== BEGIN go =====
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
v1beta1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1beta1"
"github.com/rook/rook/pkg/client/clientset/versioned/scheme"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
rest "k8s.io/client-go/rest"
)
type CephV1beta1Interface interface {
RESTClient() rest.Interface
ClustersGetter
FilesystemsGetter
ObjectStoresGetter
PoolsGetter
}
// CephV1beta1Client is used to interact with features provided by the ceph.rook.io group.
type CephV1beta1Client struct {
restClient rest.Interface
}
func (c *CephV1beta1Client) Clusters(namespace string) ClusterInterface {
return newClusters(c, namespace)
}
func (c *CephV1beta1Client) Filesystems(namespace string) FilesystemInterface {
return newFilesystems(c, namespace)
}
func (c *CephV1beta1Client) ObjectStores(namespace string) ObjectStoreInterface {
return newObjectStores(c, namespace)
}
func (c *CephV1beta1Client) Pools(namespace string) PoolInterface {
return newPools(c, namespace)
}
// NewForConfig creates a new CephV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*CephV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &CephV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new CephV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *CephV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new CephV1beta1Client for the given RESTClient.
func New(c rest.Interface) *CephV1beta1Client {
return &CephV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *CephV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
// ===== END =====
// ===== BEGIN go =====
/*
* This file is part of the KubeVirt 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.
*
* Copyright 2018 Red Hat, Inc.
*
*/
package mutators
import (
"encoding/json"
"fmt"
rt "runtime"
"k8s.io/utils/pointer"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
admissionv1 "k8s.io/api/admission/v1"
v12 "k8s.io/api/authentication/v1"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/resource"
k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/cache"
"kubevirt.io/client-go/api"
v1 "kubevirt.io/api/core/v1"
"kubevirt.io/kubevirt/pkg/testutils"
utiltypes "kubevirt.io/kubevirt/pkg/util/types"
"kubevirt.io/kubevirt/pkg/virt-api/webhooks"
virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
nodelabellerutil "kubevirt.io/kubevirt/pkg/virt-handler/node-labeller/util"
"kubevirt.io/kubevirt/pkg/virt-operator/resource/generate/rbac"
)
var privilegedUser = fmt.Sprintf("%s:%s:%s:%s", "system", "serviceaccount", "kubevirt", rbac.ControllerServiceAccountName)
var _ = Describe("VirtualMachineInstance Mutator", func() {
var vmi *v1.VirtualMachineInstance
var preset *v1.VirtualMachineInstancePreset
var presetInformer cache.SharedIndexInformer
var namespaceLimit *k8sv1.LimitRange
var namespaceLimitInformer cache.SharedIndexInformer
var kvInformer cache.SharedIndexInformer
var mutator *VMIsMutator
memoryLimit := "128M"
cpuModelFromConfig := "Haswell"
machineTypeFromConfig := "pc-q35-3.0"
cpuReq := resource.MustParse("800m")
admitVMI := func() *admissionv1.AdmissionResponse {
vmiBytes, err := json.Marshal(vmi)
Expect(err).ToNot(HaveOccurred())
By("Creating the test admissions review from the VMI")
ar := &admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
Operation: admissionv1.Create,
Resource: k8smetav1.GroupVersionResource{Group: v1.VirtualMachineInstanceGroupVersionKind.Group, Version: v1.VirtualMachineInstanceGroupVersionKind.Version, Resource: "virtualmachineinstances"},
Object: runtime.RawExtension{
Raw: vmiBytes,
},
},
}
By("Mutating the VMI")
return mutator.Mutate(ar)
}
getMetaSpecStatusFromAdmit := func() (*k8smetav1.ObjectMeta, *v1.VirtualMachineInstanceSpec, *v1.VirtualMachineInstanceStatus) {
resp := admitVMI()
Expect(resp.Allowed).To(BeTrue())
By("Getting the VMI spec from the response")
vmiSpec := &v1.VirtualMachineInstanceSpec{}
vmiMeta := &k8smetav1.ObjectMeta{}
vmiStatus := &v1.VirtualMachineInstanceStatus{}
patch := []utiltypes.PatchOperation{
{Value: vmiSpec},
{Value: vmiMeta},
{Value: vmiStatus},
}
err := json.Unmarshal(resp.Patch, &patch)
Expect(err).ToNot(HaveOccurred())
Expect(patch).NotTo(BeEmpty())
return vmiMeta, vmiSpec, vmiStatus
}
getVMIStatusFromResponseWithUpdate := func(oldVMI *v1.VirtualMachineInstance, newVMI *v1.VirtualMachineInstance, user string) *v1.VirtualMachineInstanceStatus {
oldVMIBytes, err := json.Marshal(oldVMI)
Expect(err).ToNot(HaveOccurred())
newVMIBytes, err := json.Marshal(newVMI)
Expect(err).ToNot(HaveOccurred())
By("Creating the test admissions review from the VMI")
ar := &admissionv1.AdmissionReview{
Request: &admissionv1.AdmissionRequest{
UserInfo: v12.UserInfo{
Username: user,
},
Operation: admissionv1.Update,
Resource: k8smetav1.GroupVersionResource{Group: v1.VirtualMachineInstanceGroupVersionKind.Group, Version: v1.VirtualMachineInstanceGroupVersionKind.Version, Resource: "virtualmachineinstances"},
Object: runtime.RawExtension{
Raw: newVMIBytes,
},
OldObject: runtime.RawExtension{
Raw: oldVMIBytes,
},
},
}
By("Mutating the VMI")
resp := mutator.Mutate(ar)
Expect(resp.Allowed).To(BeTrue())
By("Getting the VMI spec from the response")
vmiStatus := &v1.VirtualMachineInstanceStatus{}
patch := []utiltypes.PatchOperation{
{Value: vmiStatus},
}
err = json.Unmarshal(resp.Patch, &patch)
Expect(err).ToNot(HaveOccurred())
if len(patch) == 0 {
return &newVMI.Status
}
return vmiStatus
}
BeforeEach(func() {
vmi = &v1.VirtualMachineInstance{
ObjectMeta: k8smetav1.ObjectMeta{
Labels: map[string]string{"test": "test"},
},
Spec: v1.VirtualMachineInstanceSpec{
Domain: v1.DomainSpec{
Resources: v1.ResourceRequirements{},
},
},
}
selector := k8smetav1.LabelSelector{MatchLabels: map[string]string{"test": "test"}}
preset = &v1.VirtualMachineInstancePreset{
ObjectMeta: k8smetav1.ObjectMeta{
Name: "test-preset",
},
Spec: v1.VirtualMachineInstancePresetSpec{
Domain: &v1.DomainSpec{
CPU: &v1.CPU{Cores: 4},
},
Selector: selector,
},
}
presetInformer, _ = testutils.NewFakeInformerFor(&v1.VirtualMachineInstancePreset{})
presetInformer.GetIndexer().Add(preset)
namespaceLimit = &k8sv1.LimitRange{
Spec: k8sv1.LimitRangeSpec{
Limits: []k8sv1.LimitRangeItem{
{
Type: k8sv1.LimitTypeContainer,
Default: k8sv1.ResourceList{
k8sv1.ResourceMemory: resource.MustParse(memoryLimit),
},
},
},
},
}
namespaceLimitInformer, _ = testutils.NewFakeInformerFor(&k8sv1.LimitRange{})
namespaceLimitInformer.GetIndexer().Add(namespaceLimit)
mutator = &VMIsMutator{}
mutator.ClusterConfig, _, kvInformer = testutils.NewFakeClusterConfigUsingKVConfig(&v1.KubeVirtConfiguration{})
mutator.VMIPresetInformer = presetInformer
mutator.NamespaceLimitsInformer = namespaceLimitInformer
})
It("should apply presets on VMI create", func() {
_, vmiSpec, _ := getMetaSpecStatusFromAdmit()
Expect(vmiSpec.Domain.CPU).ToNot(BeNil())
Expect(vmiSpec.Domain.CPU.Cores).To(Equal(uint32(4)))
})
It("should apply namespace limit ranges on VMI create", func() {
_, vmiSpec, _ := getMetaSpecStatusFromAdmit()
Expect(vmiSpec.Domain.Resources.Limits.Memory().String()).To(Equal(memoryLimit))
})
It("should apply defaults on VMI create", func() {
// no limits wanted on this test, to not copy the limit to requests
mutator.NamespaceLimitsInformer, _ = testutils.NewFakeInformerFor(&k8sv1.LimitRange{})
_, vmiSpec, _ := getMetaSpecStatusFromAdmit()
if webhooks.IsPPC64() {
Expect(vmiSpec.Domain.Machine.Type).To(Equal("pseries"))
Expect(vmiSpec.Domain.CPU.Model).To(Equal(v1.DefaultCPUModel))
} else if webhooks.IsARM64() {
Expect(vmiSpec.Domain.Machine.Type).To(Equal("virt"))
Expect(vmiSpec.Domain.CPU.Model).To(Equal(v1.CPUModeHostPassthrough))
} else {
Expect(vmiSpec.Domain.Machine.Type).To(Equal("q35"))
Expect(vmiSpec.Domain.CPU.Model).To(Equal(v1.DefaultCPUModel))
}
Expect(v1.DefaultCPUModel).To(Equal(v1.CPUModeHostModel))
Expect(vmiSpec.Domain.Resources.Requests.Cpu().IsZero()).To(BeTrue())
// no default for requested memory when no memory is specified
Expect(vmiSpec.Domain.Resources.Requests.Memory().Value()).To(Equal(int64(0)))
})
It("should apply configurable defaults on VMI create", func() {
// no limits wanted on this test, to not copy the limit to requests
mutator.NamespaceLimitsInformer, _ = testutils.NewFakeInformerFor(&k8sv1.LimitRange{})
testutils.UpdateFakeKubeVirtClusterConfig(kvInformer, &v1.KubeVirt{
Spec: v1.KubeVirtSpec{
Configuration: v1.KubeVirtConfiguration{
CPUModel: cpuModelFromConfig,
MachineType: machineTypeFromConfig,
CPURequest: &cpuReq,
},
},
})
_, vmiSpec, _ := getMetaSpecStatusFro
// ===== END =====
// ===== BEGIN go =====
// Copyright 2018 ETH Zurich
//
// 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 main
func br_multi() int {
var failures int
failures += br_peer()
failures += br_child()
failures += br_parent()
failures += child_to_parent()
failures += parent_to_child()
failures += shortcut_child_to_peer()
failures += shortcut_peer_to_child()
failures += shortcut_child_to_child()
failures += revocation_parent_to_child()
return failures
}
func br_peer() int {
var failures int
failures += shortcut_peer_to_internal_host()
failures += shortcut_internal_host_to_peer()
failures += shortcut_peer_to_internal_child()
failures += shortcut_internal_child_to_peer()
failures += revocation_owned_peer()
return failures
}
func br_child() int {
var failures int
failures += child_to_internal_host()
failures += internal_host_to_child()
failures += child_to_internal_parent()
failures += internal_parent_to_child()
failures += shortcut_child_to_internal_peer()
failures += shortcut_internal_peer_to_child()
failures += shortcut_child_to_internal_child()
failures += shortcut_internal_child_to_child()
failures += revocation_child_to_internal_host()
return failures
}
func br_parent() int {
var failures int
failures += parent_to_internal_host()
failures += internal_host_to_parent()
failures += parent_to_internal_child()
failures += internal_child_to_parent()
return failures
}
// ===== END =====
// ===== BEGIN go =====
package auxpow
import (
"io"
"github.com/elastos/Elastos.ELA/auxpow"
"github.com/elastos/Elastos.ELA/common"
ela "github.com/elastos/Elastos.ELA/core/types"
"github.com/elastos/Elastos.ELA/core/types/payload"
)
type SideAuxPow struct {
SideAuxMerkleBranch []common.Uint256
SideAuxMerkleIndex int
SideAuxBlockTx ela.Transaction
MainBlockHeader ela.Header
}
func NewSideAuxPow(sideAuxMerkleBranch []common.Uint256,
sideAuxMerkleIndex int,
sideAuxBlockTx ela.Transaction,
mainBlockHeader ela.Header) *SideAuxPow {
return &SideAuxPow{
SideAuxMerkleBranch: sideAuxMerkleBranch,
SideAuxMerkleIndex: sideAuxMerkleIndex,
SideAuxBlockTx: sideAuxBlockTx,
MainBlockHeader: mainBlockHeader,
}
}
func (sap *SideAuxPow) Serialize(w io.Writer) error {
err := sap.SideAuxBlockTx.Serialize(w)
if err != nil {
return err
}
err = common.WriteUint32(w, uint32(len(sap.SideAuxMerkleBranch)))
if err != nil {
return err
}
for _, branch := range sap.SideAuxMerkleBranch {
err = branch.Serialize(w)
if err != nil {
return err
}
}
err = common.WriteUint32(w, uint32(sap.SideAuxMerkleIndex))
if err != nil {
return err
}
return sap.MainBlockHeader.Serialize(w)
}
func (sap *SideAuxPow) Deserialize(r io.Reader) error {
err := sap.SideAuxBlockTx.Deserialize(r)
if err != nil {
return err
}
count, err := common.ReadUint32(r)
if err != nil {
return err
}
sap.SideAuxMerkleBranch = make([]common.Uint256, 0, count)
for i := uint32(0); i < count; i++ {
var branch common.Uint256
err = branch.Deserialize(r)
if err != nil {
return err
}
sap.SideAuxMerkleBranch = append(sap.SideAuxMerkleBranch, branch)
}
index, err := common.ReadUint32(r)
if err != nil {
return err
}
sap.SideAuxMerkleIndex = int(index)
return sap.MainBlockHeader.Deserialize(r)
}
func (sap *SideAuxPow) SideAuxPowCheck(hashAuxBlock common.Uint256) bool {
mainBlockHeader := sap.MainBlockHeader
mainBlockHeaderHash := mainBlockHeader.Hash()
if !mainBlockHeader.AuxPow.Check(&mainBlockHeaderHash, auxpow.AuxPowChainID) {
return false
}
sideAuxPowMerkleRoot := auxpow.GetMerkleRoot(sap.SideAuxBlockTx.Hash(), sap.SideAuxMerkleBranch, sap.SideAuxMerkleIndex)
if sideAuxPowMerkleRoot != sap.MainBlockHeader.MerkleRoot {
return false
}
payloadData := sap.SideAuxBlockTx.Payload.Data(payload.SideChainPowVersion)
payloadHashData := payloadData[0:32]
payloadHash, err := common.Uint256FromBytes(payloadHashData)
if err != nil {
return false
}
if *payloadHash != hashAuxBlock {
return false
}
return true
}
// ===== END =====
// ===== BEGIN go =====
/*
Copyright (c) 2020 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// IMPORTANT: This file has been generated automatically, refrain from modifying it manually as all
// your changes will be lost when the file is generated again.
package v1 // github.com/openshift-online/ocm-sdk-go/accountsmgmt/v1
// QuotaSummaryListBuilder contains the data and logic needed to build
// 'quota_summary' objects.
type QuotaSummaryListBuilder struct {
items []*QuotaSummaryBuilder
}
// NewQuotaSummaryList creates a new builder of 'quota_summary' objects.
func NewQuotaSummaryList() *QuotaSummaryListBuilder {
return new(QuotaSummaryListBuilder)
}
// Items sets the items of the list.
func (b *QuotaSummaryListBuilder) Items(values ...*QuotaSummaryBuilder) *QuotaSummaryListBuilder {
b.items = make([]*QuotaSummaryBuilder, len(values))
copy(b.items, values)
return b
}
// Copy copies the items of the given list into this builder, discarding any previous items.
func (b *QuotaSummaryListBuilder) Copy(list *QuotaSummaryList) *QuotaSummaryListBuilder {
if list == nil || list.items == nil {
b.items = nil
} else {
b.items = make([]*QuotaSummaryBuilder, len(list.items))
for i, v := range list.items {
b.items[i] = NewQuotaSummary().Copy(v)
}
}
return b
}
// Build creates a list of 'quota_summary' objects using the
// configuration stored in the builder.
func (b *QuotaSummaryListBuilder) Build() (list *QuotaSummaryList, err error) {
items := make([]*QuotaSummary, len(b.items))
for i, item := range b.items {
items[i], err = item.Build()
if err != nil {
return
}
}
list = new(QuotaSummaryList)
list.items = items
return
}
// ===== END =====
// ===== BEGIN go =====
package graph
import (
"io"
"net/http"
"net/url"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/httputils"
"github.com/docker/docker/pkg/progressreader"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/runconfig"
"github.com/docker/docker/utils"
)
type ImageImportConfig struct {
Changes []string
InConfig io.ReadCloser
OutStream io.Writer
ContainerConfig *runconfig.Config
}
func (s *TagStore) Import(src string, repo string, tag string, imageImportConfig *ImageImportConfig) error {
var (
sf = streamformatter.NewJSONStreamFormatter()
archive archive.ArchiveReader
resp *http.Response
)
if src == "-" {
archive = imageImportConfig.InConfig
} else {
u, err := url.Parse(src)
if err != nil {
return err
}
if u.Scheme == "" {
u.Scheme = "http"
u.Host = src
u.Path = ""
}
imageImportConfig.OutStream.Write(sf.FormatStatus("", "Downloading from %s", u))
resp, err = httputils.Download(u.String())
if err != nil {
return err
}
progressReader := progressreader.New(progressreader.Config{
In: resp.Body,
Out: imageImportConfig.OutStream,
Formatter: sf,
Size: int(resp.ContentLength),
NewLines: true,
ID: "",
Action: "Importing",
})
defer progressReader.Close()
archive = progressReader
}
img, err := s.graph.Create(archive, "", "", "Imported from "+src, "", nil, imageImportConfig.ContainerConfig)
if err != nil {
return err
}
// Optionally register the image at REPO/TAG
if repo != "" {
if err := s.Tag(repo, tag, img.ID, true, true); err != nil {
return err
}
}
imageImportConfig.OutStream.Write(sf.FormatStatus("", img.ID))
logID := img.ID
if tag != "" {
logID = utils.ImageReference(logID, tag)
}
s.eventsService.Log("import", logID, "")
return nil
}
// ===== END =====
// ===== BEGIN go =====
/*-
* Copyright 2014 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// from gopkg.in/square/go-jose.v1/cipher
package josecipher
import (
"crypto"
"crypto/ecdsa"
"encoding/binary"
)
// DeriveECDHES derives a shared encryption key using ECDH/ConcatKDF as described in JWE/JWA.
// It is an error to call this function with a private/public key that are not on the same
// curve. Callers must ensure that the keys are valid before calling this function. Output
// size may be at most 1<<16 bytes (64 KiB).
func DeriveECDHES(alg string, apuData, apvData []byte, priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey, size int) []byte {
if size > 1<<16 {
panic("ECDH-ES output size too large, must be less than 1<<16")
}
// algId, partyUInfo, partyVInfo inputs must be prefixed with the length
algID := lengthPrefixed([]byte(alg))
ptyUInfo := lengthPrefixed(apuData)
ptyVInfo := lengthPrefixed(apvData)
// suppPubInfo is the encoded length of the output size in bits
supPubInfo := make([]byte, 4)
binary.BigEndian.PutUint32(supPubInfo, uint32(size)*8)
if !priv.PublicKey.Curve.IsOnCurve(pub.X, pub.Y) {
panic("public key not on same curve as private key")
}
z, _ := priv.PublicKey.Curve.ScalarMult(pub.X, pub.Y, priv.D.Bytes())
reader := NewConcatKDF(crypto.SHA256, z.Bytes(), algID, ptyUInfo, ptyVInfo, supPubInfo, []byte{})
key := make([]byte, size)
// Read on the KDF will never fail
_, _ = reader.Read(key)
return key
}
func lengthPrefixed(data []byte) []byte {
out := make([]byte, len(data)+4)
binary.BigEndian.PutUint32(out, uint32(len(data)))
copy(out[4:], data)
return out
}
// ===== END =====
// ===== BEGIN go =====
package network
// Agent - в рамках данного пакета нас итересуют только имена агентов
type Agent interface {
Name() string
}
// ===== END =====
// ===== BEGIN go =====
/*
* Copyright 2019-20 Joaquim Rocha <[email protected]> and Contributors
*
* 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 control
// WaitCompletion allows a goroutine to request and wait for completion
type WaitCompletion struct {
requested *AtomicBool
waittingChannel chan bool
}
// NewWaitCompletion creates a new WaitCompletion
func NewWaitCompletion() *WaitCompletion {
return &WaitCompletion{
requested: NewAtomicBool(false),
waittingChannel: make(chan bool),
}
}
// Request and waits for completion
func (wc *WaitCompletion) Request() {
wc.requested.Set(true)
<-wc.waittingChannel
}
// WasRequested allows a goroutine if a request was send
func (wc *WaitCompletion) WasRequested() bool {
return wc.requested.Get()
}
// Completed informs that the resquest was completed
func (wc *WaitCompletion) Completed() {
wc.waittingChannel <- true
}
// ===== END =====
// ===== BEGIN go =====
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/correctnesstests/metrics"
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/pmetric"
"github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed"
)
// testHarness listens for datapoints from the receiver to which it is attached
// and when it receives one, it compares it to the datapoint that was previously
// sent out. It then sends the next datapoint, if there is one.
type testHarness struct {
t *testing.T
metricSupplier *metricSupplier
metricIndex *metricsReceivedIndex
sender testbed.MetricDataSender
currPDM pmetric.Metrics
diffConsumer diffConsumer
outOfMetrics bool
allMetricsReceived chan struct{}
}
type diffConsumer interface {
accept(string, []*MetricDiff)
}
func newTestHarness(
t *testing.T,
s *metricSupplier,
mi *metricsReceivedIndex,
ds testbed.MetricDataSender,
diffConsumer diffConsumer,
) *testHarness {
return &testHarness{
t: t,
metricSupplier: s,
metricIndex: mi,
sender: ds,
diffConsumer: diffConsumer,
allMetricsReceived: make(chan struct{}),
}
}
func (h *testHarness) Capabilities() consumer.Capabilities {
return consumer.Capabilities{MutatesData: false}
}
func (h *testHarness) ConsumeMetrics(_ context.Context, pdm pmetric.Metrics) error {
h.compare(pdm)
if h.metricIndex.allReceived() {
close(h.allMetricsReceived)
}
if !h.outOfMetrics {
h.sendNextMetric()
}
return nil
}
func (h *testHarness) compare(pdm pmetric.Metrics) {
pdms := pdm.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()
var diffs []*MetricDiff
for i := 0; i < pdms.Len(); i++ {
pdmRecd := pdms.At(i)
metricName := pdmRecd.Name()
metric, found := h.metricIndex.lookup(metricName)
if !found {
h.diffConsumer.accept(metricName, []*MetricDiff{{
ExpectedValue: metricName,
Msg: "Metric name not found in index",
}})
}
if !metric.received {
metric.received = true
sent := metric.pdm
pdmExpected := sent.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)
diffs = DiffMetric(
diffs,
pdmExpected,
pdmRecd,
)
h.diffConsumer.accept(metricName, diffs)
}
}
}
func (h *testHarness) sendNextMetric() {
h.currPDM, h.outOfMetrics = h.metricSupplier.nextMetrics()
if h.outOfMetrics {
return
}
err := h.sender.ConsumeMetrics(context.Background(), h.currPDM)
require.NoError(h.t, err)
}
// ===== END =====
// ===== BEGIN go =====
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package scheduler
import (
"slowfs/slowfs/units"
"time"
)
// RequestType denotes what type a request is.
type RequestType int64
// Enumeration of different types of requests.
const (
ReadRequest RequestType = iota
WriteRequest
OpenRequest
CloseRequest
FsyncRequest
AllocateRequest
MetadataRequest
)
// Request contains information for all types of requests.
type Request struct {
Type RequestType
Timestamp time.Time
Path string
Start units.NumBytes
Size units.NumBytes
}
// ===== END =====
// ===== BEGIN go =====
package htmlbrelement
import (
"sync"
"syscall/js"
"github.com/realPy/hogosuru/baseobject"
"github.com/realPy/hogosuru/document"
"github.com/realPy/hogosuru/element"
"github.com/realPy/hogosuru/htmlelement"
)
var singleton sync.Once
var htmlbrelementinterface js.Value
//HtmlBrElement struct
type HtmlBRElement struct {
htmlelement.HtmlElement
}
type HtmlBRElementFrom interface {
HtmlBRElement_() HtmlBRElement
}
func (h HtmlBRElement) HtmlBRElement_() HtmlBRElement {
return h
}
func GetInterface() js.Value {
singleton.Do(func() {
var err error
if htmlbrelementinterface, err = baseobject.Get(js.Global(), "HTMLBRElement"); err != nil {
htmlbrelementinterface = js.Undefined()
}
baseobject.Register(htmlbrelementinterface, func(v js.Value) (interface{}, error) {
return NewFromJSObject(v)
})
})
return htmlbrelementinterface
}
func New(d document.Document) (HtmlBRElement, error) {
var err error
var h HtmlBRElement
var e element.Element
if e, err = d.CreateElement("br"); err == nil {
h, err = NewFromElement(e)
}
return h, err
}
func NewFromElement(elem element.Element) (HtmlBRElement, error) {
var h HtmlBRElement
var err error
if hci := GetInterface(); !hci.IsUndefined() {
if elem.BaseObject.JSObject().InstanceOf(hci) {
h.BaseObject = h.SetObject(elem.BaseObject.JSObject())
} else {
err = ErrNotAnHtmlBrElement
}
} else {
err = ErrNotImplemented
}
return h, err
}
func NewFromJSObject(obj js.Value) (HtmlBRElement, error) {
var h HtmlBRElement
var err error
if hci := GetInterface(); !hci.IsUndefined() {
if obj.IsUndefined() || obj.IsNull() {
err = baseobject.ErrUndefinedValue
} else {
if obj.InstanceOf(hci) {
h.BaseObject = h.SetObject(obj)
} else {
err = ErrNotAnHtmlBrElement
}
}
} else {
err = ErrNotImplemented
}
return h, err
}
// ===== END =====
// ===== BEGIN go =====
/*
Copyright The Kubeform 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.
*/
// Code generated by Kubeform. DO NOT EDIT.
package v1alpha1
import (
base "kubeform.dev/kubeform/apis/base/v1alpha1"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +genclient
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`
type AnalysisServicesServer struct {
metav1.TypeMeta `json:",inline,omitempty"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec AnalysisServicesServerSpec `json:"spec,omitempty"`
Status AnalysisServicesServerStatus `json:"status,omitempty"`
}
type AnalysisServicesServerSpecIpv4FirewallRule struct {
Name string `json:"name" tf:"name"`
RangeEnd string `json:"rangeEnd" tf:"range_end"`
RangeStart string `json:"rangeStart" tf:"range_start"`
}
type AnalysisServicesServerSpec struct {
ProviderRef core.LocalObjectReference `json:"providerRef" tf:"-"`
ID string `json:"id,omitempty" tf:"id,omitempty"`
SecretRef *core.LocalObjectReference `json:"secretRef,omitempty" tf:"-"`
// +optional
AdminUsers []string `json:"adminUsers,omitempty" tf:"admin_users,omitempty"`
// +optional
BackupBlobContainerURI string `json:"-" sensitive:"true" tf:"backup_blob_container_uri,omitempty"`
// +optional
EnablePowerBiService bool `json:"enablePowerBiService,omitempty" tf:"enable_power_bi_service,omitempty"`
// +optional
Ipv4FirewallRule []AnalysisServicesServerSpecIpv4FirewallRule `json:"ipv4FirewallRule,omitempty" tf:"ipv4_firewall_rule,omitempty"`
Location string `json:"location" tf:"location"`
Name string `json:"name" tf:"name"`
// +optional
QuerypoolConnectionMode string `json:"querypoolConnectionMode,omitempty" tf:"querypool_connection_mode,omitempty"`
ResourceGroupName string `json:"resourceGroupName" tf:"resource_group_name"`
// +optional
ServerFullName string `json:"serverFullName,omitempty" tf:"server_full_name,omitempty"`
Sku string `json:"sku" tf:"sku"`
// +optional
Tags map[string]string `json:"tags,omitempty" tf:"tags,omitempty"`
}
type AnalysisServicesServerStatus struct {
// Resource generation, which is updated on mutation by the API Server.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// +optional
Output *AnalysisServicesServerSpec `json:"output,omitempty"`
// +optional
State *base.State `json:"state,omitempty"`
// +optional
Phase base.Phase `json:"phase,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// AnalysisServicesServerList is a list of AnalysisServicesServers
type AnalysisServicesServerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
// Items is a list of AnalysisServicesServer CRD objects
Items []AnalysisServicesServer `json:"items,omitempty"`
}
// ===== END =====
// ===== BEGIN go =====
package model
import (
"encoding/json"
"strings"
)
// Request Object
type DeletePolicyAssignmentRequest struct {
PolicyAssignmentId string `json:"policy_assignment_id"`
}
func (o DeletePolicyAssignmentRequest) String() string {
data, err := json.Marshal(o)
if err != nil {
return "DeletePolicyAssignmentRequest struct{}"
}
return strings.Join([]string{"DeletePolicyAssignmentRequest", string(data)}, " ")
}
// ===== END =====
// ===== BEGIN go =====
/*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"errors"
"flag"
"fmt"
"go/types"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"golang.org/x/tools/go/packages"
)
func main() { // nolint:funlen
source := flag.String("source", "../../proto/vtctlservice", "source package")
typeName := flag.String("type", "VtctldClient", "interface type to implement")
implType := flag.String("impl", "gRPCVtctldClient", "type implementing the interface")
pkgName := flag.String("targetpkg", "grpcvtctldclient", "package name to generate code for")
local := flag.Bool("local", false, "generate a local, in-process client rather than a grpcclient")
out := flag.String("out", "", "output destination. leave empty to use stdout")
flag.Parse()
if *source == "" {
panic("-source cannot be empty")
}
if *typeName == "" {
panic("-type cannot be empty")
}
if *implType == "" {
panic("-impl cannot be empty")
}
if *pkgName == "" {
panic("-targetpkg cannot be empty")
}
var output io.Writer = os.Stdout
if *out != "" {
f, err := os.Create(*out)
if err != nil {
panic(err)
}
defer f.Close()
output = f
}
pkg, err := loadPackage(*source)
if err != nil {
panic(err)
}
iface, err := extractSourceInterface(pkg, *typeName)
if err != nil {
panic(fmt.Errorf("error getting %s in %s: %w", *typeName, *source, err))
}
imports := map[string]string{
"context": "context",
}
importNames := []string{}
funcs := make(map[string]*Func, iface.NumExplicitMethods())
funcNames := make([]string, iface.NumExplicitMethods())
for i := 0; i < iface.NumExplicitMethods(); i++ {
m := iface.ExplicitMethod(i)
funcNames[i] = m.Name()
sig, ok := m.Type().(*types.Signature)
if !ok {
panic(fmt.Sprintf("could not derive signature from method %s, have %T", m.FullName(), m.Type()))
}
if sig.Params().Len() != 3 {
panic(fmt.Sprintf("all methods in a grpc client interface should have exactly 3 params; found\n=> %s", sig))
}
if sig.Results().Len() != 2 {
panic(fmt.Sprintf("all methods in a grpc client interface should have exactly 2 results; found\n=> %s", sig))
}
f := &Func{
Name: m.Name(),
}
funcs[f.Name] = f
// The first parameter is always context.Context. The third parameter is
// always a ...grpc.CallOption.
param := sig.Params().At(1)
localType, localImport, pkgPath, err := extractLocalPointerType(param)
if err != nil {
panic(err)
}
f.Param.Name = param.Name()
f.Param.Type = "*" + localImport + "." + localType
if _, ok := imports[localImport]; !ok {
importNames = append(importNames, localImport)
}
imports[localImport] = pkgPath
// (TODO|@amason): check which grpc lib CallOption is imported from in
// this interface; it could be either google.golang.org/grpc or
// github.com/golang/protobuf/grpc, although in vitess we currently
// always use the former.
// The second result is always error.
result := sig.Results().At(0)
localType, localImport, pkgPath, err = extractLocalPointerType(result) // (TODO|@amason): does not work for streaming rpcs
if err != nil {
panic(err)
}
f.Result.Name = result.Name()
f.Result.Type = "*" + localImport + "." + localType
if _, ok := imports[localImport]; !ok {
importNames = append(importNames, localImport)
}
imports[localImport] = pkgPath
}
sort.Strings(importNames)
sort.Strings(funcNames)
def := &ClientInterfaceDef{
PackageName: *pkgName,
Type: *implType,
ClientName: "grpcvtctldclient",
}
if *local {
def.ClientName = "localvtctldclient"
def.Local = true
}
for _, name := range importNames {
imp := &Import{
Path: imports[name],
}
if filepath.Base(imp.Path) != name {
imp.Alias = name
}
def.Imports = append(def.Imports, imp)
}
for _, name := range funcNames {
def.Methods = append(def.Methods, funcs[name])
}
if err := tmpl.Execute(output, def); err != nil {
panic(err)
}
}
// ClientInterfaceDef is a struct providing enough information to generate an
// implementation of a gRPC Client interface.
type ClientInterfaceDef struct {
PackageName string
Type string
Imports []*Import
Methods []*Func
Local bool
ClientName string
}
// Import contains the meta information about a Go import.
type Import struct {
Alias string
Path string
}
// Func is the variable part of a gRPC client interface method (i.e. not the
// context or dialopts arguments, or the error part of the result tuple).
type Func struct {
Name string
Param Param
Result Param
}
// Param represents an element of either a parameter list or result list. It
// contains an optional name, and a package-local type. This struct exists
// purely to power template execution, which is why the Type field is simply a
// bare string.
type Param struct {
Name string
// locally-qualified type, e.g. "grpc.CallOption", and not "google.golang.org/grpc.CallOption".
Type string
}
func loadPackage(source string) (*packages.Package, error) {
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo,
}, source)
if err != nil {
return nil, err
}
if len(pkgs) != 1 {
return nil, errors.New("must specify exactly one package")
}
pkg := pkgs[0]
if len(pkg.Errors) > 0 {
var err error
for _, e := range pkg.Errors {
switch err {
case nil:
err = fmt.Errorf("errors loading package %s: %s", source, e.Error())
default:
err = fmt.Errorf("%w; %s", err, e.Error())
}
}
return nil, err
}
return pkg, nil
}
func extractSourceInterface(pkg *packages.Package, name string) (*types.Interface, error) {
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
return nil, fmt.Errorf("no symbol found with name %s", name)
}
switch t := obj.Type().(type) {
case *types.Named:
iface, ok := t.Underlying().(*types.Interface)
if !ok {
return nil, fmt.Errorf("symbol %s was not an interface but %T", name, t.Underlying())
}
return iface, nil
case *types.Interface:
return t, nil
}
return nil, fmt.Errorf("symbol %s was not an interface but %T", name, obj.Type())
}
var vitessProtoRegexp = regexp.MustCompile(`^vitess.io.*/proto/.*`)
func rewriteProtoImports(pkg *types.Package) string {
if vitessProtoRegexp.MatchString(pkg.Path()) {
return pkg.Name() + "pb"
}
return pkg.Name()
}
func extractLocalPointerType(v *types.Var) (name string, localImport string, pkgPath string, err error) {
ptr, ok := v.Type().(*types.Pointer)
if !ok {
return "", "", "", fmt.Errorf("expected a pointer type for %s, got %v", v.Name(), v.Type())
}
typ, ok := ptr.Elem().(*types.Named)
if !ok {
return "", "", "", fmt.Errorf("expected an underlying named type for %s, got %v", v.Name(), ptr.Elem())
}
name = typ.Obj().Name()
localImport = rewriteProtoImports(typ.Obj().Pkg())
pkgPath = typ.Obj().Pkg().Path()
return name, localImport, pkgPath, nil
}
// ===== END =====
// ===== BEGIN go =====
package opentelemetry
import (
"context"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/propagation"
sdktrace "go.opentelemetry.io/otel/trace"
"google.golang.org/grpc/metadata"
)
// assert that metadataSupplier implements the TextMapCarrier interface
var _ propagation.TextMapCarrier = new(metadataSupplier)
type metadataSupplier struct {
metadata *metadata.MD
}
func (s *metadataSupplier) Get(key string) string {
values := s.metadata.Get(key)
if len(values) == 0 {
return ""
}
return values[0]
}
func (s *metadataSupplier) Set(key, value string) {
s.metadata.Set(key, value)
}
func (s *metadataSupplier) Keys() []string {
out := make([]string, 0, len(*s.metadata))
for key := range *s.metadata {
out = append(out, key)
}
return out
}
// Inject injects the metadata into ctx.
func Inject(ctx context.Context, p propagation.TextMapPropagator, metadata *metadata.MD) {
p.Inject(ctx, &metadataSupplier{
metadata: metadata,
})
}
// Extract extracts the metadata from ctx.
func Extract(ctx context.Context, p propagation.TextMapPropagator, metadata *metadata.MD) (
baggage.Baggage, sdktrace.SpanContext) {
ctx = p.Extract(ctx, &metadataSupplier{
metadata: metadata,
})
return baggage.FromContext(ctx), sdktrace.SpanContextFromContext(ctx)
}
// ===== END =====
// ===== BEGIN go =====
/*
* This file is part of the kubevirt 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.
*
* Copyright 2021 Red Hat, Inc.
*
*/
package network
import (
"context"
"fmt"
expect "github.com/google/goexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
k8sv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "kubevirt.io/client-go/api/v1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/kubevirt/tests"
"kubevirt.io/kubevirt/tests/console"
cd "kubevirt.io/kubevirt/tests/containerdisk"
"kubevirt.io/kubevirt/tests/libnet"
)
var _ = SIGDescribe("[crit:high][vendor:[email protected]][level:component]", func() {
var err error
var virtClient kubecli.KubevirtClient
var vmi *v1.VirtualMachineInstance
BeforeEach(func() {
virtClient, err = kubecli.GetKubevirtClient()
tests.PanicOnError(err)
tests.BeforeTestCleanup()
vmi = tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))
})
Describe("[crit:high][vendor:[email protected]][level:component]Creating a VirtualMachineInstance", func() {
Context("[Serial]when virt-handler is responsive", func() {
It("VMIs with Bridge Networking shouldn't fail after the kubelet restarts", func() {
bridgeVMI := vmi
// Remove the masquerade interface to use the default bridge one
bridgeVMI.Spec.Domain.Devices.Interfaces = nil
bridgeVMI.Spec.Networks = nil
v1.SetDefaults_NetworkInterface(bridgeVMI)
Expect(bridgeVMI.Spec.Domain.Devices.Interfaces).NotTo(BeEmpty())
By("starting a VMI with bridged network on a node")
bridgeVMI, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(bridgeVMI)
Expect(err).To(BeNil(), "Should submit VMI successfully")
// Start a VirtualMachineInstance with bridged networking
nodeName := tests.WaitForSuccessfulVMIStart(bridgeVMI)
tests.VerifyDummyNicForBridgeNetwork(bridgeVMI)
By("restarting kubelet")
pod := renderPkillAllPod("kubelet")
pod.Spec.NodeName = nodeName
_, err = virtClient.CoreV1().Pods(tests.NamespaceTestDefault).Create(context.Background(), pod, metav1.CreateOptions{})
Expect(err).ToNot(HaveOccurred())
By("starting another VMI on the same node, to verify kubelet is running again")
newVMI := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
newVMI.Spec.NodeSelector = map[string]string{"kubernetes.io/hostname": nodeName}
Eventually(func() error {
newVMI, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(newVMI)
Expect(err).To(BeNil())
return nil
}, 100, 10).Should(Succeed(), "Should be able to start a new VM")
By("checking if the VMI with bridged networking is still running, it will verify the CNI didn't cause the pod to be killed")
tests.WaitForSuccessfulVMIStart(bridgeVMI)
})
It("VMIs with Bridge Networking should work with Duplicate Address Detection (DAD)", func() {
bridgeVMI := tests.NewRandomVMIWithEphemeralDiskAndUserdata(cd.ContainerDiskFor(cd.ContainerDiskCirros), "#!/bin/bash\necho 'hello'\n")
// Remove the masquerade interface to use the default bridge one
bridgeVMI.Spec.Domain.Devices.Interfaces = nil
bridgeVMI.Spec.Networks = nil
v1.SetDefaults_NetworkInterface(bridgeVMI)
Expect(bridgeVMI.Spec.Domain.Devices.Interfaces).NotTo(BeEmpty())
By("starting a VMI with bridged network on a node")
bridgeVMI, err = virtClient.VirtualMachineInstance(vmi.Namespace).Create(bridgeVMI)
Expect(err).To(BeNil(), "Should submit VMI successfully")
// Start a VirtualMachineInstance with bridged networking
By("Waiting the VirtualMachineInstance start")
tests.WaitUntilVMIReady(bridgeVMI, console.LoginToCirros)
tests.VerifyDummyNicForBridgeNetwork(bridgeVMI)
// Update the VMI object so we get the IP address
bridgeVMI, err = virtClient.VirtualMachineInstance(bridgeVMI.Namespace).Get(bridgeVMI.Name, &metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
vmIP := libnet.GetVmiPrimaryIpByFamily(bridgeVMI, k8sv1.IPv4Protocol)
dadCommand := fmt.Sprintf("sudo /usr/sbin/arping -D -I eth0 -c 2 %s | grep Received | cut -d ' ' -f 2\n", vmIP)
Expect(console.SafeExpectBatch(bridgeVMI, []expect.Batcher{
&expect.BSnd{S: "\n"},
&expect.BExp{R: console.PromptExpression},
&expect.BSnd{S: dadCommand},
&expect.BExp{R: "0"},
}, 600)).To(Succeed())
})
})
})
})
func renderPkillAllPod(processName string) *k8sv1.Pod {
return tests.RenderPrivilegedPod("vmi-killer", []string{"pkill"}, []string{"-9", processName})
}
// ===== END =====
// ===== BEGIN go =====
package kinesis
import (
"github.com/awslabs/goformation/v4/cloudformation/policies"
)
// Stream_StreamEncryption AWS CloudFormation Resource (AWS::Kinesis::Stream.StreamEncryption)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesis-stream-streamencryption.html
type Stream_StreamEncryption struct {
// EncryptionType AWS CloudFormation Property
// Required: true
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesis-stream-streamencryption.html#cfn-kinesis-stream-streamencryption-encryptiontype
EncryptionType string `json:"EncryptionType,omitempty"`
// KeyId AWS CloudFormation Property
// Required: true
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesis-stream-streamencryption.html#cfn-kinesis-stream-streamencryption-keyid
KeyId string `json:"KeyId,omitempty"`
// AWSCloudFormationDeletionPolicy represents a CloudFormation DeletionPolicy
AWSCloudFormationDeletionPolicy policies.DeletionPolicy `json:"-"`
// AWSCloudFormationDependsOn stores the logical ID of the resources to be created before this resource
AWSCloudFormationDependsOn []string `json:"-"`
// AWSCloudFormationMetadata stores structured data associated with this resource
AWSCloudFormationMetadata map[string]interface{} `json:"-"`
}
// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *Stream_StreamEncryption) AWSCloudFormationType() string {
return "AWS::Kinesis::Stream.StreamEncryption"
}
// ===== END =====
// ===== BEGIN go =====
// +build go1.12
// Note: Some of the packages we benchmark against require go 1.12 so we can only benchmark on go 1.12
package benchmarking
import (
"context"
"fmt"
"strconv"
"sync/atomic"
"testing"
"time"
gohystrix "github.com/afex/hystrix-go/hystrix"
"github.com/edwardhey/circuit/v3"
"github.com/edwardhey/circuit/v3/closers/hystrix"
"github.com/edwardhey/circuit/v3/closers/simplelogic"
"github.com/edwardhey/circuit/v3/metrics/rolling"
iandCircuit "github.com/iand/circuit"
circuitbreaker "github.com/rubyist/circuitbreaker"
"github.com/sony/gobreaker"
"github.com/streadway/handy/breaker"
)
type circuitConfigs struct {
config interface{}
name string
}
type circuitImpls struct {
name string
runner func(b *testing.B, configIn interface{}, concurrent int, funcToRun interface{}, pass bool)
configs []circuitConfigs
funcTypes []interface{}
}
func BenchmarkCiruits(b *testing.B) {
sf := rolling.StatFactory{}
hystrixDefaultStats := sf.CreateConfig("")
hystrixDefaultStats.Merge(circuit.Config{
Execution: circuit.ExecutionConfig{},
})
h := hystrix.Factory{}
hystrixDefaultStats.Merge(h.Configure(""))
concurrents := []int{1, 75}
passesParam := []bool{true, false}
impls := []circuitImpls{
{
name: "cep21-circuit",
runner: circuitRunner,
configs: []circuitConfigs{
{
name: "Hystrix",
config: hystrixDefaultStats,
}, {
name: "Minimal",
config: circuit.Config{
Execution: circuit.ExecutionConfig{
MaxConcurrentRequests: int64(-1),
Timeout: -1,
},
General: circuit.GeneralConfig{
ClosedToOpenFactory: simplelogic.ConsecutiveErrOpenerFactory(simplelogic.ConfigConsecutiveErrOpener{}),
},
},
}, {
name: "UseGo",
config: circuit.Config{
Execution: circuit.ExecutionConfig{
MaxConcurrentRequests: int64(12),
Timeout: -1,
}, General: circuit.GeneralConfig{
CustomConfig: map[interface{}]interface{}{
"use-go": true,
},
},
},
},
},
funcTypes: []interface{}{passesCtx, failsCtx},
},
{
name: "GoHystrix",
runner: goHystrixRunner,
configs: []circuitConfigs{
{
name: "DefaultConfig",
config: gohystrix.CommandConfig{
// I don't *WANT* to pass 100,000 here. It should just work with `concurrent`, but it doesn't.
//MaxConcurrentRequests: concurrent,
MaxConcurrentRequests: 100000,
},
},
},
funcTypes: []interface{}{passes, fails},
},
{
name: "rubyist",
runner: rubyistRunner,
configs: []circuitConfigs{
{
name: "Threshold-10",
config: func() *circuitbreaker.Breaker {
return circuitbreaker.NewThresholdBreaker(10)
},
},
},
funcTypes: []interface{}{passes, fails},
},
{
name: "gobreaker",
runner: gobreakerRunner,
configs: []circuitConfigs{
{
name: "Default",
config: gobreaker.Settings{},
},
},
funcTypes: []interface{}{passesInter, failsInter},
},
{
name: "handy",
runner: handyRunner,
configs: []circuitConfigs{
{
name: "Default",
},
},
funcTypes: []interface{}{nil, nil},
},
{
name: "iand_circuit",
runner: iandCircuitRunner,
configs: []circuitConfigs{
{
name: "Default",
config: &iandCircuit.Breaker{
Concurrency: 75,
},
},
},
funcTypes: []interface{}{passes, fails},
},
}
for _, impl := range impls {
impl := impl
b.Run(impl.name, func(b *testing.B) {
for _, config := range impl.configs {
config := config
b.Run(config.name, func(b *testing.B) {
for _, pass := range passesParam {
pass := pass
var f interface{}
var name string
if pass {
f = impl.funcTypes[0]
name = "passing"
} else {
f = impl.funcTypes[1]
name = "failing"
}
b.Run(name, func(b *testing.B) {
for _, concurrent := range concurrents {
concurrent := concurrent
b.Run(strconv.Itoa(concurrent), func(b *testing.B) {
impl.runner(b, config.config, concurrent, f, pass)
})
}
})
}
})
}
})
}
}
func circuitRunner(b *testing.B, configIn interface{}, concurrent int, funcToRun interface{}, pass bool) {
f := funcToRun.(func(context.Context) error)
h := circuit.Manager{}
config := configIn.(circuit.Config)
config.Execution.MaxConcurrentRequests = int64(concurrent)
c := h.MustCreateCircuit("hello-world", config)
ctx := context.Background()
useExecute := config.General.CustomConfig == nil
genericBenchmarkTesting(b, concurrent, func() error {
if useExecute {
return c.Execute(ctx, f, nil)
}
return c.Go(ctx, f, nil)
}, !pass)
}
func rubyistRunner(b *testing.B, configIn interface{}, concurrent int, funcToRun interface{}, pass bool) {
circ := configIn.(func() *circuitbreaker.Breaker)()
f := funcToRun.(func() error)
ctx := context.Background()
genericBenchmarkTesting(b, concurrent, func() error {
return circ.CallContext(ctx, f, time.Second)
}, !pass)
}
var iCount int64
func goHystrixRunner(b *testing.B, configIn interface{}, concurrent int, funcToRun interface{}, pass bool) {
circuitName := fmt.Sprintf("gocircuit-%d", atomic.AddInt64(&iCount, 1))
config := configIn.(gohystrix.CommandConfig)
gohystrix.ConfigureCommand(circuitName, config)
f := funcToRun.(func() error)
genericBenchmarkTesting(b, concurrent, func() error {
return gohystrix.Do(circuitName, f, nil)
}, !pass)
}
func gobreakerRunner(b *testing.B, configIn interface{}, concurrent int, funcToRun interface{}, pass bool) {
conf := configIn.(gobreaker.Settings)
cb := gobreaker.NewCircuitBreaker(conf)
f := funcToRun.(func() (interface{}, error))
genericBenchmarkTesting(b, concurrent, func() error {
_, err := cb.Execute(f)
return err
}, !pass)
}
func handyRunner(b *testing.B, _ interface{}, concurrent int, _ interface{}, pass bool) {
cb := breaker.NewBreaker(.9)
genericBenchmarkTesting(b, concurrent, func() error {
cb.Allow()
if pass {
cb.Success(time.Second)
return nil
}
cb.Failure(time.Second)
return errFailure
}, !pass)
}
func iandCircuitRunner(b *testing.B, breakerIn interface{}, concurrent int, funcToRun interface{}, pass bool) {
bc := breakerIn.(*iandCircuit.Breaker)
ctx := context.Background()
f := funcToRun.(func() error)
genericBenchmarkTesting(b, concurrent, func() error {
return bc.Do(ctx, f)
}, !pass)
}
// ===== END =====
// ===== BEGIN go =====
package formatter
import (
"reflect"
"strings"
"testing"
"time"
"github.com/hyperhq/hyper-api/types"
"github.com/hyperhq/hypercli/pkg/stringid"
)
func TestContainerPsContext(t *testing.T) {
containerID := stringid.GenerateRandomID()
unix := time.Now().Unix()
var ctx containerContext
cases := []struct {
container types.Container
trunc bool
expValue string
expHeader string
call func() string
}{
{types.Container{ID: containerID}, true, stringid.TruncateID(containerID), containerIDHeader, ctx.ID},
{types.Container{ID: containerID}, false, containerID, containerIDHeader, ctx.ID},
{types.Container{Names: []string{"/foobar_baz"}}, true, "foobar_baz", namesHeader, ctx.Names},
{types.Container{Image: "ubuntu"}, true, "ubuntu", imageHeader, ctx.Image},
{types.Container{Image: "verylongimagename"}, true, "verylongimagename", imageHeader, ctx.Image},
{types.Container{Image: "verylongimagename"}, false, "verylongimagename", imageHeader, ctx.Image},
{types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
true,
"a5a665ff33ec",
imageHeader,
ctx.Image,
},
{types.Container{
Image: "a5a665ff33eced1e0803148700880edab4",
ImageID: "a5a665ff33eced1e0803148700880edab4269067ed77e27737a708d0d293fbf5",
},
false,
"a5a665ff33eced1e0803148700880edab4",
imageHeader,
ctx.Image,
},
{types.Container{Image: ""}, true, "<no image>", imageHeader, ctx.Image},
{types.Container{Command: "sh -c 'ls -la'"}, true, `"sh -c 'ls -la'"`, commandHeader, ctx.Command},
{types.Container{Created: unix}, true, time.Unix(unix, 0).String(), createdAtHeader, ctx.CreatedAt},
{types.Container{Ports: []types.Port{{PrivatePort: 8080, PublicPort: 8080, Type: "tcp"}}}, true, "8080/tcp", portsHeader, ctx.Ports},
{types.Container{Status: "RUNNING"}, true, "RUNNING", statusHeader, ctx.Status},
{types.Container{SizeRw: 10}, true, "10 B", sizeHeader, ctx.Size},
{types.Container{SizeRw: 10, SizeRootFs: 20}, true, "10 B (virtual 20 B)", sizeHeader, ctx.Size},
{types.Container{}, true, "", labelsHeader, ctx.Labels},
{types.Container{Labels: map[string]string{"cpu": "6", "storage": "ssd"}}, true, "cpu=6,storage=ssd", labelsHeader, ctx.Labels},
{types.Container{Created: unix}, true, "Less than a second", runningForHeader, ctx.RunningFor},
}
for _, c := range cases {
ctx = containerContext{c: c.container, trunc: c.trunc}
v := c.call()
if strings.Contains(v, ",") {
compareMultipleValues(t, v, c.expValue)
} else if v != c.expValue {
t.Fatalf("Expected %s, was %s\n", c.expValue, v)
}
h := ctx.fullHeader()
if h != c.expHeader {
t.Fatalf("Expected %s, was %s\n", c.expHeader, h)
}
}
c1 := types.Container{Labels: map[string]string{"com.docker.swarm.swarm-id": "33", "com.docker.swarm.node_name": "ubuntu"}}
ctx = containerContext{c: c1, trunc: true}
sid := ctx.Label("com.docker.swarm.swarm-id")
node := ctx.Label("com.docker.swarm.node_name")
if sid != "33" {
t.Fatalf("Expected 33, was %s\n", sid)
}
if node != "ubuntu" {
t.Fatalf("Expected ubuntu, was %s\n", node)
}
h := ctx.fullHeader()
if h != "SWARM ID\tNODE NAME" {
t.Fatalf("Expected %s, was %s\n", "SWARM ID\tNODE NAME", h)
}
c2 := types.Container{}
ctx = containerContext{c: c2, trunc: true}
label := ctx.Label("anything.really")
if label != "" {
t.Fatalf("Expected an empty string, was %s", label)
}
ctx = containerContext{c: c2, trunc: true}
fullHeader := ctx.fullHeader()
if fullHeader != "" {
t.Fatalf("Expected fullHeader to be empty, was %s", fullHeader)
}
}
func TestImagesContext(t *testing.T) {
imageID := stringid.GenerateRandomID()
unix := time.Now().Unix()
var ctx imageContext
cases := []struct {
imageCtx imageContext
expValue string
expHeader string
call func() string
}{
{imageContext{
i: types.Image{ID: imageID},
trunc: true,
}, stringid.TruncateID(imageID), imageIDHeader, ctx.ID},
{imageContext{
i: types.Image{ID: imageID},
trunc: false,
}, imageID, imageIDHeader, ctx.ID},
{imageContext{
i: types.Image{Size: 10},
trunc: true,
}, "10 B", sizeHeader, ctx.Size},
{imageContext{
i: types.Image{Created: unix},
trunc: true,
}, time.Unix(unix, 0).String(), createdAtHeader, ctx.CreatedAt},
// FIXME
// {imageContext{
// i: types.Image{Created: unix},
// trunc: true,
// }, units.HumanDuration(time.Unix(unix, 0)), createdSinceHeader, ctx.CreatedSince},
{imageContext{
i: types.Image{},
repo: "busybox",
}, "busybox", repositoryHeader, ctx.Repository},
{imageContext{
i: types.Image{},
tag: "latest",
}, "latest", tagHeader, ctx.Tag},
{imageContext{
i: types.Image{},
digest: "sha256:d149ab53f8718e987c3a3024bb8aa0e2caadf6c0328f1d9d850b2a2a67f2819a",
}, "sha256:d149ab53f8718e987c3a3024bb8aa0e2caadf6c0328f1d9d850b2a2a67f2819a", digestHeader, ctx.Digest},
}
for _, c := range cases {
ctx = c.imageCtx
v := c.call()
if strings.Contains(v, ",") {
compareMultipleValues(t, v, c.expValue)
} else if v != c.expValue {
t.Fatalf("Expected %s, was %s\n", c.expValue, v)
}
h := ctx.fullHeader()
if h != c.expHeader {
t.Fatalf("Expected %s, was %s\n", c.expHeader, h)
}
}
}
func compareMultipleValues(t *testing.T, value, expected string) {
// comma-separated values means probably a map input, which won't
// be guaranteed to have the same order as our expected value
// We'll create maps and use reflect.DeepEquals to check instead:
entriesMap := make(map[string]string)
expMap := make(map[string]string)
entries := strings.Split(value, ",")
expectedEntries := strings.Split(expected, ",")
for _, entry := range entries {
keyval := strings.Split(entry, "=")
entriesMap[keyval[0]] = keyval[1]
}
for _, expected := range expectedEntries {
keyval := strings.Split(expected, "=")
expMap[keyval[0]] = keyval[1]
}
if !reflect.DeepEqual(expMap, entriesMap) {
t.Fatalf("Expected entries: %v, got: %v", expected, value)
}
}
// ===== END =====
// ===== BEGIN go =====
package gounity_test
// func TestPingPong(t *testing.T) {
// ctx, err := testutil.NewTestContext()
// assert.Nil(t, err, "failed to setup rest client to mock server")
// defer ctx.TearDown()
// resp, err := ctx.restClient.pingPong(
// ctx.context, http.MethodGet,
// fmt.Sprintf("api/instances/lun/sv_1?compact=true&fields=%s", typeFieldsLun),
// nil, nil)
// assert.Nil(t, err)
// assert.Equal(t, 200, resp.StatusCode)
// }
// func TestDoWithHeaders(t *testing.T) {
// ctx, err := testutil.NewTestContext()
// assert.Nil(t, err, "failed to setup rest client to mock server")
// defer ctx.TearDown()
// instResp := &instanceResp{}
// err = ctx.restClient.DoWithHeaders(
// ctx.context, http.MethodGet,
// fmt.Sprintf("api/instances/lun/sv_1?compact=true&fields=%s", typeFieldsLun),
// nil, nil, instResp)
// assert.Nil(t, err)
// lun := &Lun{}
// err = json.Unmarshal(instResp.Content, lun)
// assert.Nil(t, err)
// assert.Equal(t, "sv_1", lun.Id)
// assert.Equal(t, "pool_1", lun.Pool.Id)
// }
// func TestGet(t *testing.T) {
// ctx, err := testutil.NewTestContext()
// assert.Nil(t, err, "failed to setup rest client to mock server")
// defer ctx.TearDown()
// instResp := &instanceResp{}
// err = ctx.restClient.Get(
// ctx.context,
// fmt.Sprintf("api/instances/lun/sv_1?compact=true&fields=%s", typeFieldsLun),
// nil, instResp)
// assert.Nil(t, err)
// lun := &Lun{}
// err = json.Unmarshal(instResp.Content, lun)
// assert.Nil(t, err)
// assert.Equal(t, "sv_1", lun.Id)
// assert.Equal(t, "pool_1", lun.Pool.Id)
// }
// ===== END =====
// ===== BEGIN go =====
/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resources
import (
"testing"
"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
pav1a1 "github.com/knative/serving/pkg/apis/autoscaling/v1alpha1"
"github.com/knative/serving/pkg/apis/serving"
autoscalingv1 "k8s.io/api/autoscaling/v1"
)
var boolTrue = true
func TestMakeService(t *testing.T) {
pa := &pav1a1.PodAutoscaler{
ObjectMeta: metav1.ObjectMeta{
Namespace: "here",
Name: "with-you",
UID: "2006",
// Those labels are propagated from the Revision->KPA.
Labels: map[string]string{
serving.RevisionLabelKey: "with-you",
serving.RevisionUID: "2009",
},
Annotations: map[string]string{
"a": "b",
},
},
Spec: pav1a1.PodAutoscalerSpec{
ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
APIVersion: "apps/v1",
Kind: "Deployment",
Name: "with-you",
},
ServiceName: "with-you-service",
},
}
selector := map[string]string{"cant": "stop"}
want := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Namespace: "here",
Name: "with-you-metrics",
Labels: map[string]string{
// Those should be propagated.
serving.RevisionLabelKey: "with-you",
serving.RevisionUID: "2009",
kpaLabelKey: "with-you",
},
Annotations: map[string]string{
"a": "b",
},
OwnerReferences: []metav1.OwnerReference{{
APIVersion: pav1a1.SchemeGroupVersion.String(),
Kind: "PodAutoscaler",
Name: "with-you",
UID: "2006",
Controller: &boolTrue,
BlockOwnerDeletion: &boolTrue,
}},
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{{
Name: "metrics",
Protocol: corev1.ProtocolTCP,
Port: 9090,
TargetPort: intstr.FromString("queue-metrics"),
}},
Selector: selector,
},
}
got := MakeMetricsService(pa, selector)
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Metrics K8s Service mismatch (-want, +got) = %v", diff)
}
}
// ===== END =====
// ===== BEGIN go =====
/*******************************************************************************
* Copyright 2021 EdgeSec Ltd
*
* 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 cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "edgeca",
Short: "EdgeCA is an ephemeral certificate authority",
}
// Execute the commands
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// ===== END =====
// ===== BEGIN rust =====
//! An ephemeral in-memory file system, intended mainly for unit tests
use crate::{FileSystem, VfsFileType};
use crate::{SeekAndRead, VfsMetadata};
use crate::{VfsError, VfsResult};
use core::cmp;
use std::collections::HashMap;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::mem::swap;
use std::sync::{Arc, RwLock};
type MemoryFsHandle = Arc<RwLock<MemoryFsImpl>>;
/// An ephemeral in-memory file system, intended mainly for unit tests
pub struct MemoryFS {
handle: MemoryFsHandle,
}
impl Debug for MemoryFS {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("In Memory File System")
}
}
impl MemoryFS {
/// Create a new in-memory filesystem
pub fn new() -> Self {
MemoryFS {
handle: Arc::new(RwLock::new(MemoryFsImpl::new())),
}
}
fn ensure_has_parent(&self, path: &str) -> VfsResult<()> {
let separator = path.rfind('/');
if let Some(index) = separator {
if self.exists(&path[..index])? {
return Ok(());
}
}
Err(VfsError::Other {
message: format!("Parent path of {} does not exist", path),
})
}
}
impl Default for MemoryFS {
fn default() -> Self {
Self::new()
}
}
struct WritableFile {
content: Cursor<Vec<u8>>,
destination: String,
fs: MemoryFsHandle,
}
impl Write for WritableFile {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.content.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.content.flush()
}
}
impl Drop for WritableFile {
fn drop(&mut self) {
let mut content = vec![];
swap(&mut content, self.content.get_mut());
self.fs.write().unwrap().files.insert(
self.destination.clone(),
MemoryFile {
file_type: VfsFileType::File,
content: Arc::new(content),
},
);
}
}
struct ReadableFile {
#[allow(clippy::rc_buffer)] // to allow accessing the same object as writable
content: Arc<Vec<u8>>,
position: u64,
}
impl ReadableFile {
fn len(&self) -> u64 {
self.content.len() as u64 - self.position
}
}
impl Read for ReadableFile {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let amt = cmp::min(buf.len(), self.len() as usize);
if amt == 1 {
buf[0] = self.content[self.position as usize];
} else {
buf[..amt].copy_from_slice(
&self.content.as_slice()[self.position as usize..self.position as usize + amt],
);
}
self.position += amt as u64;
Ok(amt)
}
}
impl Seek for ReadableFile {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
match pos {
SeekFrom::Start(offset) => self.position = offset,
SeekFrom::Current(offset) => self.position = (self.position as i64 + offset) as u64,
SeekFrom::End(offset) => self.position = (self.content.len() as i64 + offset) as u64,
}
Ok(self.position)
}
}
impl FileSystem for MemoryFS {
fn read_dir(&self, path: &str) -> VfsResult<Box<dyn Iterator<Item = String>>> {
let prefix = format!("{}/", path);
let handle = self.handle.read().unwrap();
let mut found_directory = false;
#[allow(clippy::needless_collect)] // need collect to satisfy lifetime requirements
let entries: Vec<_> = handle
.files
.iter()
.filter_map(|(candidate_path, _)| {
if candidate_path == path {
found_directory = true;
}
if candidate_path.starts_with(&prefix) {
let rest = &candidate_path[prefix.len()..];
if !rest.contains('/') {
return Some(rest.to_string());
}
}
None
})
.collect();
if !found_directory {
return Err(VfsError::FileNotFound {
path: path.to_string(),
});
}
Ok(Box::new(entries.into_iter()))
}
fn create_dir(&self, path: &str) -> VfsResult<()> {
self.ensure_has_parent(path)?;
self.handle.write().unwrap().files.insert(
path.to_string(),
MemoryFile {
file_type: VfsFileType::Directory,
content: Default::default(),
},
);
Ok(())
}
fn open_file(&self, path: &str) -> VfsResult<Box<dyn SeekAndRead>> {
let handle = self.handle.read().unwrap();
let file = handle
.files
.get(path)
.ok_or_else(|| VfsError::FileNotFound {
path: path.to_string(),
})?;
ensure_file(file)?;
Ok(Box::new(ReadableFile {
content: file.content.clone(),
position: 0,
}))
}
fn create_file(&self, path: &str) -> VfsResult<Box<dyn Write>> {
self.ensure_has_parent(path)?;
let content = Arc::new(Vec::<u8>::new());
self.handle.write().unwrap().files.insert(
path.to_string(),
MemoryFile {
file_type: VfsFileType::File,
content,
},
);
let writer = WritableFile {
content: Cursor::new(vec![]),
destination: path.to_string(),
fs: self.handle.clone(),
};
Ok(Box::new(writer))
}
fn append_file(&self, path: &str) -> VfsResult<Box<dyn Write>> {
let handle = self.handle.write().unwrap();
let file = &handle.files[path];
let mut content = Cursor::new(file.content.as_ref().clone());
content.seek(SeekFrom::End(0))?;
let writer = WritableFile {
content,
destination: path.to_string(),
fs: self.handle.clone(),
};
Ok(Box::new(writer))
}
fn metadata(&self, path: &str) -> VfsResult<VfsMetadata> {
let guard = self.handle.read().unwrap();
let files = &guard.files;
let file = files.get(path).ok_or_else(|| VfsError::FileNotFound {
path: path.to_string(),
})?;
Ok(VfsMetadata {
file_type: file.file_type,
len: file.content.len() as u64,
})
}
fn exists(&self, path: &str) -> VfsResult<bool> {
Ok(self.handle.read().unwrap().files.contains_key(path))
}
fn remove_file(&self, path: &str) -> VfsResult<()> {
let mut handle = self.handle.write().unwrap();
handle
.files
.remove(path)
.ok_or_else(|| VfsError::FileNotFound {
path: path.to_string(),
})?;
Ok(())
}
fn remove_dir(&self, path: &str) -> VfsResult<()> {
if self.read_dir(path)?.next().is_some() {
return Err(VfsError::Other {
message: "Directory to remove is not empty".to_string(),
});
}
let mut handle = self.handle.write().unwrap();
handle
.files
.remove(path)
.ok_or_else(|| VfsError::FileNotFound {
path: path.to_string(),
})?;
Ok(())
}
}
struct MemoryFsImpl {
files: HashMap<String, MemoryFile>,
}
impl MemoryFsImpl {
pub fn new() -> Self {
let mut files = HashMap::new();
// Add root directory
files.insert(
"".to_string(),
MemoryFile {
file_type: VfsFileType::Directory,
content: Arc::new(vec![]),
},
);
Self { files }
}
}
struct MemoryFile {
file_type: VfsFileType,
#[allow(clippy::rc_buffer)] // to allow accessing the same object as writable
content: Arc<Vec<u8>>,
}
#[cfg(test)]
mod tests {
u
// ===== END =====
// ===== BEGIN rust =====
// Copyright 2021. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{fmt, sync::Arc};
use tari_crypto::tari_utilities::hex::Hex;
use crate::blocks::ChainBlock;
#[derive(Clone, Debug, PartialEq)]
pub enum BlockAddResult {
Ok(Arc<ChainBlock>),
BlockExists,
OrphanBlock,
/// Indicates the new block caused a chain reorg. This contains removed blocks followed by added blocks.
ChainReorg {
added: Vec<Arc<ChainBlock>>,
removed: Vec<Arc<ChainBlock>>,
},
}
impl BlockAddResult {
/// Returns true if the chain was changed (i.e block added or reorged), otherwise false
pub fn was_chain_modified(&self) -> bool {
matches!(self, BlockAddResult::Ok(_) | BlockAddResult::ChainReorg { .. })
}
pub fn is_added(&self) -> bool {
matches!(self, BlockAddResult::Ok(_))
}
pub fn is_chain_reorg(&self) -> bool {
matches!(self, BlockAddResult::ChainReorg { .. })
}
pub fn is_orphaned(&self) -> bool {
matches!(self, BlockAddResult::OrphanBlock)
}
pub fn assert_added(&self) -> ChainBlock {
match self {
BlockAddResult::ChainReorg { added, removed } => panic!(
"Expected added result, but was reorg ({} added, {} removed)",
added.len(),
removed.len()
),
BlockAddResult::Ok(b) => b.as_ref().clone(),
BlockAddResult::BlockExists => panic!("Expected added result, but was BlockExists"),
BlockAddResult::OrphanBlock => panic!("Expected added result, but was OrphanBlock"),
}
}
pub fn assert_orphaned(&self) {
assert!(self.is_orphaned(), "Result was not orphaned");
}
pub fn assert_reorg(&self, num_added: usize, num_removed: usize) {
match self {
BlockAddResult::ChainReorg { added, removed } => {
assert_eq!(num_added, added.len(), "Number of added reorged blocks was different");
assert_eq!(
num_removed,
removed.len(),
"Number of removed reorged blocks was different"
);
},
BlockAddResult::Ok(_) => panic!("Expected reorg result, but was Ok()"),
BlockAddResult::BlockExists => panic!("Expected reorg result, but was BlockExists"),
BlockAddResult::OrphanBlock => panic!("Expected reorg result, but was OrphanBlock"),
}
}
pub fn added_blocks(&self) -> Vec<Arc<ChainBlock>> {
match self {
Self::ChainReorg { added, removed: _ } => added.clone(),
Self::Ok(added) => vec![added.clone()],
_ => vec![],
}
}
pub fn removed_blocks(&self) -> Vec<Arc<ChainBlock>> {
match self {
Self::ChainReorg { added: _, removed } => removed.clone(),
_ => vec![],
}
}
}
impl fmt::Display for BlockAddResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlockAddResult::Ok(block) => {
write!(f, "Block {} at height {} added", block.hash().to_hex(), block.height())
},
BlockAddResult::BlockExists => write!(f, "Block already exists"),
BlockAddResult::OrphanBlock => write!(f, "Block added as orphan"),
BlockAddResult::ChainReorg { added, removed } => write!(
f,
"Reorg from {} ({}) to {}, and {} blocks added ending with {} ({})",
removed.first().map(|r| r.height()).unwrap_or(0),
removed
.first()
.map(|r| r.hash().to_hex())
.unwrap_or_else(|| "None".to_string()),
removed.last().map(|r| r.height()).unwrap_or(0),
added.len(),
added.last().map(|a| a.height()).unwrap_or(0),
added
.last()
.map(|a| a.hash().to_hex())
.unwrap_or_else(|| "None".to_string())
),
}
}
}
// ===== END =====
// ===== BEGIN rust =====
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use crate::Range;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem;
use std::mem::transmute;
use std::ptr;
glib::wrapper! {
#[doc(alias = "AtkValue")]
pub struct Value(Interface<ffi::AtkValue, ffi::AtkValueIface>);
match fn {
type_ => || ffi::atk_value_get_type(),
}
}
impl Value {
pub const NONE: Option<&'static Value> = None;
}
pub trait ValueExt: 'static {
#[doc(alias = "atk_value_get_current_value")]
#[doc(alias = "get_current_value")]
fn current_value(&self) -> glib::Value;
#[doc(alias = "atk_value_get_increment")]
#[doc(alias = "get_increment")]
fn increment(&self) -> f64;
#[doc(alias = "atk_value_get_maximum_value")]
#[doc(alias = "get_maximum_value")]
fn maximum_value(&self) -> glib::Value;
#[doc(alias = "atk_value_get_minimum_increment")]
#[doc(alias = "get_minimum_increment")]
fn minimum_increment(&self) -> glib::Value;
#[doc(alias = "atk_value_get_minimum_value")]
#[doc(alias = "get_minimum_value")]
fn minimum_value(&self) -> glib::Value;
#[doc(alias = "atk_value_get_range")]
#[doc(alias = "get_range")]
fn range(&self) -> Option<Range>;
#[doc(alias = "atk_value_get_sub_ranges")]
#[doc(alias = "get_sub_ranges")]
fn sub_ranges(&self) -> Vec<Range>;
#[doc(alias = "atk_value_get_value_and_text")]
#[doc(alias = "get_value_and_text")]
fn value_and_text(&self) -> (f64, glib::GString);
#[doc(alias = "atk_value_set_current_value")]
fn set_current_value(&self, value: &glib::Value) -> bool;
#[doc(alias = "atk_value_set_value")]
fn set_value(&self, new_value: f64);
#[doc(alias = "value-changed")]
fn connect_value_changed<F: Fn(&Self, f64, &str) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Value>> ValueExt for O {
fn current_value(&self) -> glib::Value {
unsafe {
let mut value = glib::Value::uninitialized();
ffi::atk_value_get_current_value(
self.as_ref().to_glib_none().0,
value.to_glib_none_mut().0,
);
value
}
}
fn increment(&self) -> f64 {
unsafe { ffi::atk_value_get_increment(self.as_ref().to_glib_none().0) }
}
fn maximum_value(&self) -> glib::Value {
unsafe {
let mut value = glib::Value::uninitialized();
ffi::atk_value_get_maximum_value(
self.as_ref().to_glib_none().0,
value.to_glib_none_mut().0,
);
value
}
}
fn minimum_increment(&self) -> glib::Value {
unsafe {
let mut value = glib::Value::uninitialized();
ffi::atk_value_get_minimum_increment(
self.as_ref().to_glib_none().0,
value.to_glib_none_mut().0,
);
value
}
}
fn minimum_value(&self) -> glib::Value {
unsafe {
let mut value = glib::Value::uninitialized();
ffi::atk_value_get_minimum_value(
self.as_ref().to_glib_none().0,
value.to_glib_none_mut().0,
);
value
}
}
fn range(&self) -> Option<Range> {
unsafe { from_glib_full(ffi::atk_value_get_range(self.as_ref().to_glib_none().0)) }
}
fn sub_ranges(&self) -> Vec<Range> {
unsafe {
FromGlibPtrContainer::from_glib_full(ffi::atk_value_get_sub_ranges(
self.as_ref().to_glib_none().0,
))
}
}
fn value_and_text(&self) -> (f64, glib::GString) {
unsafe {
let mut value = mem::MaybeUninit::uninit();
let mut text = ptr::null_mut();
ffi::atk_value_get_value_and_text(
self.as_ref().to_glib_none().0,
value.as_mut_ptr(),
&mut text,
);
(value.assume_init(), from_glib_full(text))
}
}
fn set_current_value(&self, value: &glib::Value) -> bool {
unsafe {
from_glib(ffi::atk_value_set_current_value(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
))
}
}
fn set_value(&self, new_value: f64) {
unsafe {
ffi::atk_value_set_value(self.as_ref().to_glib_none().0, new_value);
}
}
fn connect_value_changed<F: Fn(&Self, f64, &str) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn value_changed_trampoline<
P: IsA<Value>,
F: Fn(&P, f64, &str) + 'static,
>(
this: *mut ffi::AtkValue,
value: libc::c_double,
text: *mut libc::c_char,
f: glib::ffi::gpointer,
) {
let f: &F = &*(f as *const F);
f(
Value::from_glib_borrow(this).unsafe_cast_ref(),
value,
&glib::GString::from_glib_borrow(text),
)
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"value-changed\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
value_changed_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("Value")
}
}
// ===== END =====
// ===== BEGIN rust =====
pub mod dispatch;
pub mod glue;
pub mod interface;
pub mod variant;
use anyhow::Result;
use dirs;
use log::LevelFilter;
use once_cell::sync::Lazy;
use simplelog;
use std::{
default::Default,
fs::{self, File},
path::PathBuf,
};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Auth {
Anonymous,
Kerberos,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Config {
pub log_level: LevelFilter,
pub auth_mechanism: Auth,
}
impl Default for Config {
fn default() -> Self {
Config { log_level: LevelFilter::Off, auth_mechanism: Auth::Kerberos }
}
}
fn load_config_and_init_log() -> Result<Config> {
let path = match dirs::config_dir() {
Some(d) => d,
None => match dirs::home_dir() {
Some(d) => d,
None => PathBuf::from("\\"),
},
};
let base = path.join("netidx-excel");
fs::create_dir_all(base.clone())?;
let config_file = base.join("config.json");
let log_file = base.join("log.txt");
if !config_file.exists() {
fs::write(&*config_file, &serde_json::to_string_pretty(&Config::default())?)?;
}
let config: Config = serde_json::from_str(&fs::read_to_string(config_file.clone())?)?;
let log = File::create(log_file)?;
simplelog::WriteLogger::init(config.log_level, simplelog::Config::default(), log)?;
Ok(config)
}
pub static CONFIG: Lazy<Config> = Lazy::new(|| match load_config_and_init_log() {
Ok(c) => c,
Err(_) => Config::default(),
});
// ===== END =====
// ===== BEGIN rust =====
// Shane Isbell licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
use map_list::MapData;
use prelude::DexReader;
use std::io::Cursor;
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct AnnotationSetRefList {
size: u32,
list: Vec<AnnotationSetRefItem>,
}
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct AnnotationSetRefItem {
annotations_off: u32,
}
pub fn diff_annotation_set_ref_list<'a, 'b>(
v1: &'a Vec<AnnotationSetRefList>,
v2: &'b Vec<AnnotationSetRefList>,
) -> Vec<(&'a AnnotationSetRefList, &'b AnnotationSetRefList)> {
v1.iter().zip(v2.iter()).filter(|&(a, b)| a != b).collect()
}
pub fn read_annotation_set_ref_list(data: &MapData) -> Vec<AnnotationSetRefList> {
let mut cursor = Cursor::new(&data.data);
let mut list = Vec::new();
for _i in 0..data.size {
list.push(AnnotationSetRefList::read(&mut cursor));
}
list
}
impl AnnotationSetRefList {
pub fn read(data: &mut Cursor<&Vec<u8>>) -> AnnotationSetRefList {
let size = data.u32();
AnnotationSetRefList {
size: size,
list: AnnotationSetRefItem::read_list(data, size),
}
}
}
impl AnnotationSetRefItem {
pub fn read_list(data: &mut Cursor<&Vec<u8>>, size: u32) -> Vec<AnnotationSetRefItem> {
let mut items = Vec::new();
for _i in 0..size {
items.push(AnnotationSetRefItem::read(data));
}
items
}
pub fn read(data: &mut Cursor<&Vec<u8>>) -> AnnotationSetRefItem {
AnnotationSetRefItem {
annotations_off: data.u32(),
}
}
}
// ===== END =====
// ===== BEGIN rust =====
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate protobuf;
use std::collections::HashMap;
use test::Bencher;
use rand::{thread_rng, Rng};
use protobuf::Message;
use kvproto::eraftpb::Entry;
use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request};
#[inline]
fn gen_rand_str(len: usize) -> Vec<u8> {
let mut rand_str = vec![0; len];
thread_rng().fill_bytes(&mut rand_str);
rand_str
}
#[inline]
fn generate_requests(map: &HashMap<&[u8], &[u8]>) -> Vec<Request> {
let mut reqs = vec![];
for (key, value) in map {
let mut r = Request::new();
r.set_cmd_type(CmdType::Put);
r.mut_put().set_cf("tikv".to_owned());
r.mut_put().set_key(key.to_vec());
r.mut_put().set_value(value.to_vec());
reqs.push(r);
}
reqs
}
fn encode(map: &HashMap<&[u8], &[u8]>) -> Vec<u8> {
let mut e = Entry::new();
let mut cmd = RaftCmdRequest::new();
let reqs = generate_requests(map);
cmd.set_requests(protobuf::RepeatedField::from_vec(reqs));
let cmd_msg = cmd.write_to_bytes().unwrap();
e.set_data(cmd_msg);
e.write_to_bytes().unwrap()
}
fn decode(data: &[u8]) {
let mut entry = Entry::new();
entry.merge_from_bytes(data).unwrap();
let mut cmd = RaftCmdRequest::new();
cmd.merge_from_bytes(entry.get_data()).unwrap();
}
#[bench]
fn bench_encode_one(b: &mut Bencher) {
let key = gen_rand_str(30);
let value = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::new();
map.insert(&key, &value);
b.iter(|| { encode(&map); });
}
#[bench]
fn bench_decode_one(b: &mut Bencher) {
let key = gen_rand_str(30);
let value = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::new();
map.insert(&key, &value);
let data = encode(&map);
b.iter(|| { decode(&data); });
}
#[bench]
fn bench_encode_two(b: &mut Bencher) {
let key_for_lock = gen_rand_str(30);
let value_for_lock = gen_rand_str(10);
let key_for_data = gen_rand_str(30);
let value_for_data = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::new();
map.insert(&key_for_lock, &value_for_lock);
map.insert(&key_for_data, &value_for_data);
b.iter(|| { encode(&map); });
}
#[bench]
fn bench_decode_two(b: &mut Bencher) {
let key_for_lock = gen_rand_str(30);
let value_for_lock = gen_rand_str(10);
let key_for_data = gen_rand_str(30);
let value_for_data = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::new();
map.insert(&key_for_lock, &value_for_lock);
map.insert(&key_for_data, &value_for_data);
let data = encode(&map);
b.iter(|| { decode(&data); });
}
// ===== END =====
// ===== BEGIN rust =====
use crate::{
canvas::{Drawable, Frame, Layer},
Primitive,
};
use iced_native::Size;
use std::{cell::RefCell, marker::PhantomData, sync::Arc};
/// A simple cache that stores generated geometry to avoid recomputation.
///
/// A [`Cache`] will not redraw its geometry unless the dimensions of its layer
/// change or it is explicitly cleared.
///
/// [`Layer`]: ../trait.Layer.html
/// [`Cached`]: struct.Cached.html
#[derive(Debug)]
pub struct Cache<T: Drawable> {
input: PhantomData<T>,
state: RefCell<State>,
}
enum State {
Empty,
Filled {
bounds: Size,
primitive: Arc<Primitive>,
},
}
impl<T> Cache<T>
where
T: Drawable + std::fmt::Debug,
{
/// Creates a new empty [`Cache`].
///
/// [`Cache`]: struct.Cache.html
pub fn new() -> Self {
Cache {
input: PhantomData,
state: RefCell::new(State::Empty),
}
}
/// Clears the cache, forcing a redraw the next time it is used.
///
/// [`Cached`]: struct.Cached.html
pub fn clear(&mut self) {
*self.state.borrow_mut() = State::Empty;
}
/// Binds the [`Cache`] with some data, producing a [`Layer`] that can be
/// added to a [`Canvas`].
///
/// [`Cache`]: struct.Cache.html
/// [`Layer`]: ../trait.Layer.html
/// [`Canvas`]: ../../struct.Canvas.html
pub fn with<'a>(&'a self, input: &'a T) -> impl Layer + 'a {
Bind {
cache: self,
input: input,
}
}
}
#[derive(Debug)]
struct Bind<'a, T: Drawable> {
cache: &'a Cache<T>,
input: &'a T,
}
impl<'a, T> Layer for Bind<'a, T>
where
T: Drawable + std::fmt::Debug,
{
fn draw(&self, current_bounds: Size) -> Arc<Primitive> {
use std::ops::Deref;
if let State::Filled { bounds, primitive } =
self.cache.state.borrow().deref()
{
if *bounds == current_bounds {
return primitive.clone();
}
}
let mut frame = Frame::new(current_bounds.width, current_bounds.height);
self.input.draw(&mut frame);
let primitive = Arc::new(frame.into_primitive());
*self.cache.state.borrow_mut() = State::Filled {
bounds: current_bounds,
primitive: primitive.clone(),
};
primitive
}
}
impl std::fmt::Debug for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
State::Empty => write!(f, "Empty"),
State::Filled { primitive, bounds } => f
.debug_struct("Filled")
.field("primitive", primitive)
.field("bounds", bounds)
.finish(),
}
}
}
// ===== END =====
// ===== BEGIN rust =====
pub mod models;
pub mod operations;
pub const API_VERSION: &str = "2017-04-01-preview";
// ===== END =====
// ===== BEGIN rust =====
//! Types for tracking pieces of source code within a crate.
//!
//! The [`SourceMap`] tracks all the source code used within a single crate, mapping
//! from integer byte positions to the original source code location. Each bit
//! of source parsed during crate parsing (typically files, in-memory strings,
//! or various bits of macro expansion) cover a continuous range of bytes in the
//! `SourceMap` and are represented by [`SourceFile`]s. Byte positions are stored in
//! [`Span`] and used pervasively in the compiler. They are absolute positions
//! within the `SourceMap`, which upon request can be converted to line and column
//! information, source code snippets, etc.
pub use crate::hygiene::{ExpnData, ExpnKind};
pub use crate::*;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::StableHasher;
use rustc_data_structures::sync::{AtomicU32, Lrc, MappedReadGuard, ReadGuard, RwLock};
use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::{clone::Clone, cmp};
use std::{convert::TryFrom, unreachable};
use std::fs;
use std::io;
use tracing::debug;
#[cfg(test)]
mod tests;
/// Returns the span itself if it doesn't come from a macro expansion,
/// otherwise return the call site span up to the `enclosing_sp` by
/// following the `expn_data` chain.
pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
let expn_data1 = sp.ctxt().outer_expn_data();
let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
if expn_data1.is_root() || !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site
{
sp
} else {
original_sp(expn_data1.call_site, enclosing_sp)
}
}
pub mod monotonic {
use std::ops::{Deref, DerefMut};
/// A `MonotonicVec` is a `Vec` which can only be grown.
/// Once inserted, an element can never be removed or swapped,
/// guaranteeing that any indices into a `MonotonicVec` are stable
// This is declared in its own module to ensure that the private
// field is inaccessible
pub struct MonotonicVec<T>(Vec<T>);
impl<T> MonotonicVec<T> {
pub fn new(val: Vec<T>) -> MonotonicVec<T> {
MonotonicVec(val)
}
pub fn push(&mut self, val: T) {
self.0.push(val);
}
}
impl<T> Default for MonotonicVec<T> {
fn default() -> Self {
MonotonicVec::new(vec![])
}
}
impl<T> Deref for MonotonicVec<T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> !DerefMut for MonotonicVec<T> {}
}
#[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
pub struct Spanned<T> {
pub node: T,
pub span: Span,
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned { node: t, span: sp }
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respan(DUMMY_SP, t)
}
// _____________________________________________________________________________
// SourceFile, MultiByteChar, FileName, FileLines
//
/// An abstraction over the fs operations used by the Parser.
pub trait FileLoader {
/// Query the existence of a file.
fn file_exists(&self, path: &Path) -> bool;
/// Read the contents of a UTF-8 file into memory.
fn read_file(&self, path: &Path) -> io::Result<String>;
}
/// A FileLoader that uses std::fs to load real files.
pub struct RealFileLoader;
impl FileLoader for RealFileLoader {
fn file_exists(&self, path: &Path) -> bool {
path.exists()
}
fn read_file(&self, path: &Path) -> io::Result<String> {
fs::read_to_string(path)
}
}
/// This is a [SourceFile] identifier that is used to correlate source files between
/// subsequent compilation sessions (which is something we need to do during
/// incremental compilation).
///
/// The [StableSourceFileId] also contains the CrateNum of the crate the source
/// file was originally parsed for. This way we get two separate entries in
/// the [SourceMap] if the same file is part of both the local and an upstream
/// crate. Trying to only have one entry for both cases is problematic because
/// at the point where we discover that there's a local use of the file in
/// addition to the upstream one, we might already have made decisions based on
/// the assumption that it's an upstream file. Treating the two files as
/// different has no real downsides.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
pub struct StableSourceFileId {
// A hash of the source file's FileName. This is hash so that it's size
// is more predictable than if we included the actual FileName value.
pub file_name_hash: u64,
// The CrateNum of the crate this source file was originally parsed for.
// We cannot include this information in the hash because at the time
// of hashing we don't have the context to map from the CrateNum's numeric
// value to a StableCrateId.
pub cnum: CrateNum,
}
// FIXME: we need a more globally consistent approach to the problem solved by
// StableSourceFileId, perhaps built atop source_file.name_hash.
impl StableSourceFileId {
pub fn new(source_file: &SourceFile) -> StableSourceFileId {
StableSourceFileId::new_from_name(&source_file.name, source_file.cnum)
}
fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId {
let mut hasher = StableHasher::new();
name.hash(&mut hasher);
StableSourceFileId { file_name_hash: hasher.finish(), cnum }
}
}
// _____________________________________________________________________________
// SourceMap
//
#[derive(Default)]
pub(super) struct SourceMapFiles {
source_files: monotonic::MonotonicVec<Lrc<SourceFile>>,
stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
}
pub struct SourceMap {
/// The address space below this value is currently used by the files in the source map.
used_address_space: AtomicU32,
files: RwLock<SourceMapFiles>,
file_loader: Box<dyn FileLoader + Sync + Send>,
// This is used to apply the file path remapping as specified via
// `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
path_mapping: FilePathMapping,
/// The algorithm used for hashing the contents of each source file.
hash_kind: SourceFileHashAlgorithm,
}
impl SourceMap {
pub fn new(path_mapping: FilePathMapping) -> SourceMap {
Self::with_file_loader_and_hash_kind(
Box::new(RealFileLoader),
path_mapping,
SourceFileHashAlgorithm::Md5,
)
}
pub fn with_file_loader_and_hash_kind(
file_loader: Box<dyn FileLoader + Sync + Send>,
path_mapping: FilePathMapping,
hash_kind: SourceFileHashAlgorithm,
) -> SourceMap {
SourceMap {
used_address_space: AtomicU32::new(0),
files: Default::default(),
file_loader,
path_mapping,
hash_kind,
}
}
pub fn path_mapping(&self) -> &FilePathMapping {
&self.path_mapping
}
pub fn file_exists(&self, path: &Path) -> bool {
self.file_loader.file_exists(path)
}
pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
let src = self.file_loader.read_file(path)?;
let filename = path.to_owned().into();
Ok(self.new_source_file(filename, src))
}
/// Loads source file as a binary blob.
///
/// Unlike `load_file`, guarantees that no normalization like BOM-removal
/// takes place.
pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
// Ideally, this should use `self.file_loader`, but it can't
// deal with binary files yet.
let bytes = fs::read(path)?;
// We need to add file to the `SourceMap`, so that it is present
// in dep-info. There's also an edge case that file might be both
//
// ===== END =====
// ===== BEGIN rust =====
use crate::redis_helpers::*;
use crate::test_helpers::*;
use ilp_node::InterledgerNode;
use serde::Deserialize;
use serde_json::{self, json};
use tungstenite::{client, handshake::client::Request};
use std::{
sync::{Arc, Mutex},
thread,
time::Duration,
};
#[tokio::test]
async fn payments_incoming() {
let context = TestContext::new();
let mut connection_info1 = context.get_client_connection_info();
connection_info1.db = 1;
let mut connection_info2 = context.get_client_connection_info();
connection_info2.db = 2;
// test ports
let node_a_http = get_open_port(None);
let node_a_settlement = get_open_port(None);
let node_b_http = get_open_port(None);
let node_b_settlement = get_open_port(None);
// accounts to be created on node a
let alice_on_a = json!({
"username": "alice_on_a",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_http_incoming_token" : "default account holder",
});
let b_on_a = json!({
"username": "b_on_a",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_btp_url": format!("ws://localhost:{}/accounts/{}/ilp/btp", node_b_http, "a_on_b"),
"ilp_over_btp_outgoing_token" : "token",
"routing_relation": "Parent",
});
// accounts to be created on node b
let a_on_b = json!({
"username": "a_on_b",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_btp_incoming_token" : "token",
"routing_relation": "Child",
});
let bob_on_b = json!({
"username": "bob_on_b",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_http_incoming_token" : "default account holder",
});
let caleb_on_b = json!({
"username": "caleb_on_b",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_http_incoming_token" : "default account holder",
});
let dave_on_b = json!({
"username": "dave_on_b",
"asset_code": "XYZ",
"asset_scale": 9,
"ilp_over_http_incoming_token" : "default account holder",
});
// node a config
let node_a: InterledgerNode = serde_json::from_value(json!({
"admin_auth_token": "admin",
"database_url": connection_info_to_string(connection_info1),
"http_bind_address": format!("127.0.0.1:{}", node_a_http),
"settlement_api_bind_address": format!("127.0.0.1:{}", node_a_settlement),
"secret_seed": random_secret(),
"route_broadcast_interval": 200,
"exchange_rate": {
"poll_interval": 60000
},
}))
.expect("Error creating node_a.");
// node b config
let node_b: InterledgerNode = serde_json::from_value(json!({
"ilp_address": "example.parent",
"default_spsp_account": "bob_on_b",
"admin_auth_token": "admin",
"database_url": connection_info_to_string(connection_info2),
"http_bind_address": format!("127.0.0.1:{}", node_b_http),
"settlement_api_bind_address": format!("127.0.0.1:{}", node_b_settlement),
"secret_seed": random_secret(),
"route_broadcast_interval": Some(200),
"exchange_rate": {
"poll_interval": 60000
},
}))
.expect("Error creating node_b.");
// start node b and open its accounts
node_b.serve(None).await.unwrap();
create_account_on_node(node_b_http, a_on_b, "admin")
.await
.unwrap();
create_account_on_node(node_b_http, bob_on_b, "admin")
.await
.unwrap();
create_account_on_node(node_b_http, caleb_on_b, "admin")
.await
.unwrap();
create_account_on_node(node_b_http, dave_on_b, "admin")
.await
.unwrap();
// start node a and open its accounts
node_a.serve(None).await.unwrap();
create_account_on_node(node_a_http, alice_on_a, "admin")
.await
.unwrap();
create_account_on_node(node_a_http, b_on_a, "admin")
.await
.unwrap();
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct PmtNotificationWrapper {
Ok: PmtNotification,
}
#[derive(Deserialize)]
struct PmtNotification {
to_username: String,
from_username: String,
amount: u64,
}
// create a cross-thread collection of payment notifications
let pmt_notifications = Arc::new(Mutex::new(Vec::<PmtNotification>::with_capacity(3)));
// spawn a thread that listens in on node-wide payment notifications for node b
let notifications = pmt_notifications.clone();
std::thread::spawn(move || {
let ws_request = Request::builder()
.uri(format!("ws://localhost:{}/payments/incoming", node_b_http))
.header("Authorization", "Bearer admin")
.body(())
.unwrap();
let mut payments_ws = client::connect(ws_request).unwrap().0;
// loop as many times as there are expected payment notifications
for _ in 0..3 {
let msg = payments_ws.read_message().unwrap();
let notification: PmtNotificationWrapper =
serde_json::from_str(&msg.into_text().unwrap()).unwrap();
notifications.lock().unwrap().push(notification.Ok);
}
payments_ws.close(None).unwrap();
});
// send money from alice (node a) to bob (node b)
send_money_to_username(
node_a_http,
node_b_http,
1000,
"bob_on_b",
"alice_on_a",
"default account holder",
)
.await
.unwrap();
// send money from alice (node a) to caleb (node b)
send_money_to_username(
node_a_http,
node_b_http,
2000,
"caleb_on_b",
"alice_on_a",
"default account holder",
)
.await
.unwrap();
// send money from alice (node a) to dave (node b)
send_money_to_username(
node_a_http,
node_b_http,
3000,
"dave_on_b",
"alice_on_a",
"default account holder",
)
.await
.unwrap();
// a small delay to make sure the notifications are intercepted in the other thread
thread::sleep(Duration::from_secs(1));
// check if all the payment notifications were received as expected
let messages = pmt_notifications.lock().unwrap();
assert_eq!(messages.len(), 3);
assert_eq!(messages[0].to_username, "bob_on_b");
assert_eq!(messages[1].to_username, "caleb_on_b");
assert_eq!(messages[2].to_username, "dave_on_b");
assert_eq!(messages[0].from_username, "a_on_b");
assert_eq!(messages[1].from_username, "a_on_b");
assert_eq!(messages[2].from_username, "a_on_b");
assert_eq!(messages[0].amount, 1000);
assert_eq!(messages[1].amount, 2000);
assert_eq!(messages[2].amount, 3000);
}
// ===== END =====
// ===== BEGIN rust =====
// option1.rs
// Make me compile! Execute `rustlings hint option1` for hints
// you can modify anything EXCEPT for this function's sig
fn print_number(maybe_number: Option<u16>) {
println!("printing: {}", maybe_number.unwrap());
}
fn main() {
print_number(Some (13));
print_number(Some (99));
let mut numbers: [Option<u16>; 5] = [None;5];
for iter in 0..5 {
let number_to_add: u16 = {
((iter * 1235) + 2) / (4 * 16)
};
numbers[iter as usize] = Some(number_to_add);
}
}
// ===== END =====
// ===== BEGIN rust =====
pub fn brackets_are_balanced(string: &str) -> bool {
unimplemented!("Check if the string \"{}\" contains balanced brackets", string);
}
// ===== END =====
// ===== BEGIN rust =====
use datatypes::*;
pub fn read_u16(data: &[u8]) -> u16 {
(data[0] as u16) | ((data[1] as u16) << 8)
}
pub fn read_i16(data: &[u8]) -> i16 {
read_u16(data) as i16
}
pub fn read_imm16(data: &[u8]) -> ImmediateValue {
ImmediateValue::Imm16(read_i16(data))
}
pub fn read_u32(data: &[u8]) -> u32 {
(data[0] as u32) | ((data[1] as u32) << 8) | ((data[2] as u32) << 16) | ((data[3] as u32) << 24)
}
pub fn read_i32(data: &[u8]) -> i32 {
read_u32(data) as i32
}
pub fn read_imm32(data: &[u8]) -> ImmediateValue {
ImmediateValue::Imm32(read_i32(data))
}
pub fn get_override_size(mode: BitMode, prefix: u16) -> (OperandSize, OperandSize) {
let is_op_overridden = (prefix & Prefix::OverrideOpSize as u16) != 0;
let is_addr_overridden = (prefix & Prefix::OverrideAddrSize as u16) != 0;
let op_size = if mode == BitMode::X86_32 {
if is_op_overridden {
OperandSize::Bit16
} else {
OperandSize::Bit32
}
} else {
unimplemented!("64 bit mode");
};
let addr_size = if mode == BitMode::X86_32 {
if is_addr_overridden {
OperandSize::Bit16
} else {
OperandSize::Bit32
}
} else {
unimplemented!("64 bit mode");
};
(op_size, addr_size)
}
// ===== END =====
// ===== BEGIN rust =====
use crate::layer::Layer;
use crate::control::{ControlState, MapEventDispatcher, MapControlSettings};
use crate::render_target::RenderTarget;
use crate::event::{HandlerStore, TypedHandlerStore, EventListener};
use crate::Point;
use std::rc::{Weak, Rc};
use std::cell::RefCell;
pub struct Map {
layers: Vec<Rc<RefCell<dyn Layer>>>,
position: MapPosition,
animation: Option<MapAnimation>,
control_state: ControlState,
handler_store: Rc<RefCell<HandlerStore>>,
}
impl Map {
pub fn new() -> Self {
Self {
layers: vec![],
position: MapPosition::default(),
animation: None,
control_state: ControlState::default(),
handler_store: Rc::new(RefCell::new(HandlerStore::default())),
}
}
pub fn draw(&mut self, target: &mut RenderTarget) {
let (x, y) = target.get_dimensions();
self.position.set_screen_size(x, y);
for layer in &mut self.layers {
layer.borrow_mut().draw(target, &self.position);
}
}
pub fn animate_to(&mut self, position: MapPosition, duration: u64) {
todo!()
}
pub fn add_layer(&mut self, layer: Rc<RefCell<dyn Layer>>) {
self.layers.push(layer);
}
fn animation_frame(&mut self) {
todo!()
}
pub fn position(&self) -> &MapPosition {
&self.position
}
pub fn position_mut(&mut self) -> &mut MapPosition {
&mut self.position
}
pub fn set_center(&mut self, x: f32, y: f32) {
self.position.set_center(x, y);
}
pub fn set_resolution(&mut self, resolution: f32) {
self.position.set_resolution(resolution);
}
pub fn control(&mut self) -> MapEventDispatcher {
MapEventDispatcher { map: self, settings: MapControlSettings::default() }
}
pub fn control_state(&self) -> &ControlState {
&self.control_state
}
pub fn control_state_mut(&mut self) -> &mut ControlState {
&mut self.control_state
}
}
impl<E> EventListener<E> for Map
where E: Copy,
HandlerStore: TypedHandlerStore<E>
{
fn handler_store(&self) -> Weak<RefCell<HandlerStore>> {
Rc::downgrade(&self.handler_store)
}
}
#[derive(Debug)]
pub struct MapPosition {
screen_scale: na::Matrix4<f32>,
scale: na::Matrix4<f32>,
translate: na::Matrix4<f32>,
rotation_x: f32,
rotation_z: f32,
}
impl MapPosition {
pub fn set_center(&mut self, x: f32, y: f32) {
self.translate = na::Matrix4::new_translation(&na::Vector3::new(-x, -y, 0.0));
}
pub fn set_resolution(&mut self, resolution: f32) {
self.scale = na::Matrix4::new_scaling(1.0 / resolution);
}
pub fn width_px(&self) -> f32 {
2.0 / self.screen_scale[(0, 0)]
}
pub fn height_px(&self) -> f32 {
2.0 / self.screen_scale[(1, 1)]
}
fn translate(&mut self, dx: f32, dy: f32) {
todo!()
}
pub fn translate_px(&mut self, dx: i32, dy: i32) {
let translate_px = na::Vector4::new(dx as f32, dy as f32, 0.0, 0.0);
let rotated = self.inverse_rotation() * translate_px;
let scaled = self.inverse_scale() * rotated;
let translation = na::Matrix4::new_translation(&scaled.remove_fixed_rows::<1>(3));
self.translate = self.translate * translation;
}
pub fn rotate(&mut self, x: f32, z: f32) {
const MIN_X_ANGLE: f32 = 0.0;
const MAX_X_ANGLE: f32 = 3.0 * std::f32::consts::FRAC_PI_8;
self.rotation_x = (self.rotation_x + x).max(MIN_X_ANGLE).min(MAX_X_ANGLE);
self.rotation_z += z;
}
pub fn rotation(&self) -> na::Matrix4<f32> {
let x = na::Matrix4::from_axis_angle(&na::Unit::new_normalize(na::Vector3::new(1.0, 0.0, 0.0)), self.rotation_x);
let z = na::Matrix4::from_axis_angle(&na::Unit::new_normalize(na::Vector3::new(0.0, 0.0, 1.0)), self.rotation_z);
x * z
}
pub fn inverse_rotation(&self) -> na::Matrix4<f32> {
let x = na::Matrix4::from_axis_angle(&na::Unit::new_normalize(na::Vector3::new(1.0, 0.0, 0.0)), -self.rotation_x);
let z = na::Matrix4::from_axis_angle(&na::Unit::new_normalize(na::Vector3::new(0.0, 0.0, 1.0)), -self.rotation_z);
z * x
}
pub fn zoom(&mut self, delta: f32, center_px: [i32; 2]) {
let zoom_c = self.get_map_position(¢er_px);
let map_c = self.center();
let dx = map_c[0] - zoom_c[0];
let dy = map_c[1] - zoom_c[1];
let dx_scaled = dx * (1.0 - delta);
let dy_scaled = dy * (1.0 - delta);
self.translate[(0, 3)] = -(map_c[0] + dx_scaled);
self.translate[(1, 3)] = -(map_c[1] + dy_scaled);
let transformation = na::Matrix4::new_nonuniform_scaling(&na::Vector3::new(delta, delta, delta));
self.scale = self.scale * transformation;
}
pub fn matrix(&self) -> na::Matrix4<f32> {
self.screen_scale * self.scale * self.rotation() * self.translate
}
fn set_screen_size(&mut self, width: u32, height: u32) {
self.screen_scale = na::Matrix4::new_nonuniform_scaling(&na::Vector3::new(2.0 / width as f32, 2.0 / height as f32, 2.0 / width as f32));
}
pub fn inverse_scale(&self) -> na::Matrix4<f32> {
na::Matrix4::new_nonuniform_scaling(&na::Vector3::new(1.0 / self.scale[(0, 0)], 1.0 / self.scale[(1, 1)], 1.0 / self.scale[(2, 2)]))
}
pub fn center(&self) -> Point {
[-self.translate[(0, 3)], -self.translate[(1, 3)]]
}
pub fn resolution(&self) -> f32 {
1.0 / self.scale[(0, 0)]
}
pub fn inverse_translation(&self) -> na::Matrix4<f32> {
na::Matrix4::new_translation(&na::Vector3::new(-self.translate[(0, 3)], -self.translate[(1, 3)], 0.0))
}
pub fn half_screen_translation(&self) -> na::Matrix4<f32> {
na::Matrix4::new_nonuniform_scaling(&na::Vector3::new(1.0, -1.0, 1.0)) *
na::Matrix4::new_translation(&na::Vector3::new(-self.width_px() / 2.0, - self.height_px() / 2.0, 0.0))
}
pub fn inverse_screen_transformation(&self) -> na::Matrix4<f32> {
self.inverse_translation() * self.inverse_scale() * self.inverse_rotation() * self.half_screen_translation()
}
pub fn get_map_position(&self, px_position: &[i32; 2]) -> Point {
let point = na::Vector4::new(px_position[0] as f32, px_position[1] as f32, 0.0, 1.0);
let transformed = self.inverse_screen_transformation() * point;
[transformed[0], transformed[1]]
}
}
impl Default for MapPosition {
fn default() -> Self {
use num_traits::identities::One;
Self {
screen_scale: na::Matrix4::one(),
scale: na::Matrix4::one(),
translate: na::Matrix4::one(),
rotation_x: 0.0,
rotation_z: 0.0,
}
}
}
struct MapAnimation {
from: MapPosition,
to: MapPosition,
duration: u64,
start: u64,
}
// ===== END =====
// ===== BEGIN rust =====
// This file is part of Substrate.
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Operation on unhashed runtime storage.
use codec::{Decode, Encode};
use sp_std::prelude::*;
/// Return the value of the item in storage under `key`, or `None` if there is no explicit entry.
pub fn get<T: Decode + Sized>(key: &[u8]) -> Option<T> {
sp_io::storage::get(key).and_then(|val| {
Decode::decode(&mut &val[..]).map(Some).unwrap_or_else(|_| {
// TODO #3700: error should be handleable.
crate::runtime_print!("ERROR: Corrupted state at {:?}", key);
None
})
})
}
/// Return the value of the item in storage under `key`, or the type's default if there is no
/// explicit entry.
pub fn get_or_default<T: Decode + Sized + Default>(key: &[u8]) -> T {
get(key).unwrap_or_else(Default::default)
}
/// Return the value of the item in storage under `key`, or `default_value` if there is no
/// explicit entry.
pub fn get_or<T: Decode + Sized>(key: &[u8], default_value: T) -> T {
get(key).unwrap_or(default_value)
}
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
/// explicit entry.
pub fn get_or_else<T: Decode + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
get(key).unwrap_or_else(default_value)
}
/// Put `value` in storage under `key`.
pub fn put<T: Encode + ?Sized>(key: &[u8], value: &T) {
value.using_encoded(|slice| sp_io::storage::set(key, slice));
}
/// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise.
pub fn take<T: Decode + Sized>(key: &[u8]) -> Option<T> {
let r = get(key);
if r.is_some() {
kill(key);
}
r
}
/// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage,
/// the default for its type.
pub fn take_or_default<T: Decode + Sized + Default>(key: &[u8]) -> T {
take(key).unwrap_or_else(Default::default)
}
/// Return the value of the item in storage under `key`, or `default_value` if there is no
/// explicit entry. Ensure there is no explicit entry on return.
pub fn take_or<T: Decode + Sized>(key: &[u8], default_value: T) -> T {
take(key).unwrap_or(default_value)
}
/// Return the value of the item in storage under `key`, or `default_value()` if there is no
/// explicit entry. Ensure there is no explicit entry on return.
pub fn take_or_else<T: Decode + Sized, F: FnOnce() -> T>(key: &[u8], default_value: F) -> T {
take(key).unwrap_or_else(default_value)
}
/// Check to see if `key` has an explicit entry in storage.
pub fn exists(key: &[u8]) -> bool {
sp_io::storage::exists(key)
}
/// Ensure `key` has no explicit entry in storage.
pub fn kill(key: &[u8]) {
sp_io::storage::clear(key);
}
/// Ensure keys with the given `prefix` have no entries in storage.
pub fn kill_prefix(prefix: &[u8], limit: Option<u32>) -> sp_io::KillStorageResult {
sp_io::storage::clear_prefix(prefix, limit)
}
/// Get a Vec of bytes from storage.
pub fn get_raw(key: &[u8]) -> Option<Vec<u8>> {
sp_io::storage::get(key)
}
/// Put a raw byte slice into storage.
///
/// **WARNING**: If you set the storage of the Substrate Wasm (`well_known_keys::CODE`),
/// you should also call `frame_system::RuntimeUpgraded::put(true)` to trigger the
/// `on_runtime_upgrade` logic.
pub fn put_raw(key: &[u8], value: &[u8]) {
sp_io::storage::set(key, value)
}
// ===== END =====
// ===== BEGIN rust =====
//! Time wheel based timer service.
//!
//! Inspired by linux kernel timers system
#![allow(arithmetic_overflow)]
use std::cell::RefCell;
use std::time::{Duration, Instant, SystemTime};
use std::{cmp::max, future::Future, mem, pin::Pin, rc::Rc, task, task::Poll};
use futures_timer::Delay;
use slab::Slab;
use crate::task::LocalWaker;
// Clock divisor for the next level
const LVL_CLK_SHIFT: u64 = 3;
const LVL_CLK_DIV: u64 = 1 << LVL_CLK_SHIFT;
const LVL_CLK_MASK: u64 = LVL_CLK_DIV - 1;
const fn lvl_shift(n: u64) -> u64 {
n * LVL_CLK_SHIFT
}
const fn lvl_gran(n: u64) -> u64 {
1 << lvl_shift(n)
}
// Resolution:
// 0: 1 millis
// 4: ~17 millis
const UNITS: u64 = 4;
// const UNITS: u64 = 0;
const fn to_units(n: u64) -> u64 {
n >> UNITS
}
const fn to_millis(n: u64) -> u64 {
n << UNITS
}
// The time start value for each level to select the bucket at enqueue time
const fn lvl_start(lvl: u64) -> u64 {
(LVL_SIZE - 1) << ((lvl - 1) * LVL_CLK_SHIFT)
}
// Size of each clock level
const LVL_BITS: u64 = 6;
const LVL_SIZE: u64 = 1 << LVL_BITS;
const LVL_MASK: u64 = LVL_SIZE - 1;
// Level depth
const LVL_DEPTH: u64 = 8;
const fn lvl_offs(n: u64) -> u64 {
n * LVL_SIZE
}
// The cutoff (max. capacity of the wheel)
const WHEEL_TIMEOUT_CUTOFF: u64 = lvl_start(LVL_DEPTH);
const WHEEL_TIMEOUT_MAX: u64 = WHEEL_TIMEOUT_CUTOFF - (lvl_gran(LVL_DEPTH - 1));
const WHEEL_SIZE: usize = (LVL_SIZE as usize) * (LVL_DEPTH as usize);
// Low res time resolution
const LOWRES_RESOLUTION: Duration = Duration::from_millis(5);
const fn as_millis(dur: Duration) -> u64 {
dur.as_secs() * 1_000 + (dur.subsec_millis() as u64)
}
/// Returns an instant corresponding to “now”.
///
/// Resolution is 5ms
#[inline]
pub fn now() -> Instant {
TIMER.with(|t| t.borrow_mut().now(t))
}
/// Returns the system time corresponding to “now”.
///
/// Resolution is 5ms
#[inline]
pub fn system_time() -> SystemTime {
TIMER.with(|t| t.borrow_mut().system_time(t))
}
/// Returns the system time corresponding to “now”.
///
/// If low resolution system time is not set, use system time.
/// This method does not start timer driver.
#[inline]
pub fn query_system_time() -> SystemTime {
TIMER.with(|t| t.borrow().query_system_time())
}
#[derive(Debug)]
pub struct TimerHandle(usize);
impl TimerHandle {
/// Createt new timer and return handle
pub fn new(millis: u64) -> Self {
TIMER.with(|t| Timer::add_timer(t, millis))
}
/// Resets the `TimerHandle` instance to a new deadline.
pub fn reset(&self, millis: u64) {
TIMER.with(|t| Timer::update_timer(t, self.0, millis))
}
pub fn is_elapsed(&self) -> bool {
TIMER.with(|t| t.borrow_mut().timers[self.0].bucket.is_none())
}
pub fn poll_elapsed(&self, cx: &mut task::Context<'_>) -> Poll<()> {
TIMER.with(|t| {
let entry = &t.borrow().timers[self.0];
if entry.bucket.is_none() {
Poll::Ready(())
} else {
entry.task.register(cx.waker());
Poll::Pending
}
})
}
}
impl Drop for TimerHandle {
fn drop(&mut self) {
TIMER.with(|t| t.borrow_mut().remove_timer(self.0));
}
}
bitflags::bitflags! {
pub struct Flags: u8 {
const DRIVER_STARTED = 0b0000_0001;
const DRIVER_RECALC = 0b0000_0010;
const LOWRES_TIMER = 0b0000_1000;
const LOWRES_DRIVER = 0b0001_0000;
}
}
thread_local! {
static TIMER: Rc<RefCell<Timer>>= Rc::new(RefCell::new(Timer::new()));
}
struct Timer {
timers: Slab<TimerEntry>,
elapsed: u64,
elapsed_time: Option<Instant>,
next_expiry: u64,
flags: Flags,
driver: LocalWaker,
driver_sleep: Delay,
buckets: Vec<Bucket>,
/// Bit field tracking which bucket currently contain entries.
occupied: [u64; WHEEL_SIZE],
lowres_time: Option<Instant>,
lowres_stime: Option<SystemTime>,
lowres_driver: LocalWaker,
lowres_driver_sleep: Delay,
}
impl Timer {
fn new() -> Self {
Timer {
buckets: Self::create_buckets(),
timers: Slab::default(),
elapsed: 0,
elapsed_time: None,
next_expiry: u64::MAX,
flags: Flags::empty(),
driver: LocalWaker::new(),
driver_sleep: Delay::new(Duration::ZERO),
occupied: [0; WHEEL_SIZE],
lowres_time: None,
lowres_stime: None,
lowres_driver: LocalWaker::new(),
lowres_driver_sleep: Delay::new(Duration::ZERO),
}
}
fn create_buckets() -> Vec<Bucket> {
let mut buckets = Vec::with_capacity(WHEEL_SIZE);
for idx in 0..WHEEL_SIZE {
let lvl = idx / (LVL_SIZE as usize);
let offs = idx % (LVL_SIZE as usize);
buckets.push(Bucket::new(lvl, offs))
}
buckets
}
fn now(&mut self, inner: &Rc<RefCell<Timer>>) -> Instant {
if let Some(cur) = self.lowres_time {
cur
} else {
let now = Instant::now();
self.lowres_time = Some(now);
if self.flags.contains(Flags::LOWRES_DRIVER) {
self.lowres_driver.wake();
} else {
LowresTimerDriver::start(self, inner);
}
now
}
}
fn system_time(&mut self, inner: &Rc<RefCell<Timer>>) -> SystemTime {
if let Some(cur) = self.lowres_stime {
cur
} else {
let now = SystemTime::now();
self.lowres_stime = Some(now);
if self.flags.contains(Flags::LOWRES_DRIVER) {
self.lowres_driver.wake();
} else {
LowresTimerDriver::start(self, inner);
}
now
}
}
fn query_system_time(&self) -> SystemTime {
if let Some(cur) = self.lowres_stime {
cur
} else {
SystemTime::now()
}
}
fn elapsed_time(&mut self) -> Instant {
if let Some(elapsed_time) = self.elapsed_time {
elapsed_time
} else {
let elapsed_time = Instant::now();
self.elapsed_time = Some(elapsed_time);
elapsed_time
}
}
/// Add the timer into the hash bucket
fn add_timer(inner: &Rc<RefCell<Self>>, millis: u64) -> TimerHandle {
let mut slf = inner.borrow_mut();
if millis == 0 {
let entry = slf.timers.vacant_entry();
let no = entry.key();
entry.insert(TimerEntry {
bucket_entry: 0,
bucket: None,
task: LocalWaker::new(),
});
return TimerHandle(no);
}
let now = slf.now(inner);
let elapsed_time = slf.elapsed_time();
let delta = if now >= elapsed_time {
to_units(as_millis(now - elapsed_time) + millis)
} else {
to_units(millis)
};
let (no, bucket_expiry) = {
let slf = &mut *slf;
// crate timer entry
let (idx, bucket_expiry) =
slf.calc_wheel_index(slf.elapsed.wrapping_add(delta), delta);
let entry = slf.timers.vacant_entry();
let no = entry.key();
let bucket = &mut slf.buckets[idx];
let bucket_entry = bucket.add_entry(no);
entry.insert(TimerEntry {
bucket_entry,
bucket: Some(idx as u16),
task: LocalWaker::new(),
});
slf.occupied[bucket.lvl as usize] |= bucket.bit;
(no, bucket_expiry)
};
// Check whether new bucket expire earlier
if bucket_expiry < slf.next_expiry {
slf.next_expiry = bucket_expiry;
if slf.flags.contains(Flags::DRIVER_STARTED) {
slf.flags.insert(Flags::DRIVER_RECALC);
slf.driver.wake();
} else {
T
// ===== END =====
// ===== BEGIN rust =====
/*
*
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LolStatstonesCatalogItemDetails {
#[serde(rename = "inventoryType", skip_serializing_if = "Option::is_none")]
pub inventory_type: Option<String>,
#[serde(rename = "itemId", skip_serializing_if = "Option::is_none")]
pub item_id: Option<i32>,
#[serde(rename = "itemInstanceId", skip_serializing_if = "Option::is_none")]
pub item_instance_id: Option<String>,
#[serde(rename = "prices", skip_serializing_if = "Option::is_none")]
pub prices: Option<Vec<crate::models::LolStatstonesCatalogBundlePrice>>,
#[serde(rename = "releaseDate", skip_serializing_if = "Option::is_none")]
pub release_date: Option<String>,
#[serde(rename = "subInventoryType", skip_serializing_if = "Option::is_none")]
pub sub_inventory_type: Option<String>,
}
impl LolStatstonesCatalogItemDetails {
pub fn new() -> LolStatstonesCatalogItemDetails {
LolStatstonesCatalogItemDetails {
inventory_type: None,
item_id: None,
item_instance_id: None,
prices: None,
release_date: None,
sub_inventory_type: None,
}
}
}
// ===== END =====
// ===== BEGIN rust =====
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
use std::fmt::Write;
/// See [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput)
pub mod associate_external_connection_input {
/// A builder for [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) domain: std::option::Option<std::string::String>,
pub(crate) domain_owner: std::option::Option<std::string::String>,
pub(crate) repository: std::option::Option<std::string::String>,
pub(crate) external_connection: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The name of the domain that contains the repository.</p>
pub fn domain(mut self, input: impl Into<std::string::String>) -> Self {
self.domain = Some(input.into());
self
}
/// <p>The name of the domain that contains the repository.</p>
pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self {
self.domain = input;
self
}
/// <p>
/// The 12-digit account number of the AWS account that owns the domain. It does not include
/// dashes or spaces.
/// </p>
pub fn domain_owner(mut self, input: impl Into<std::string::String>) -> Self {
self.domain_owner = Some(input.into());
self
}
/// <p>
/// The 12-digit account number of the AWS account that owns the domain. It does not include
/// dashes or spaces.
/// </p>
pub fn set_domain_owner(mut self, input: std::option::Option<std::string::String>) -> Self {
self.domain_owner = input;
self
}
/// <p>
/// The name of the repository to which the external connection is added.
/// </p>
pub fn repository(mut self, input: impl Into<std::string::String>) -> Self {
self.repository = Some(input.into());
self
}
/// <p>
/// The name of the repository to which the external connection is added.
/// </p>
pub fn set_repository(mut self, input: std::option::Option<std::string::String>) -> Self {
self.repository = input;
self
}
/// <p>
/// The name of the external connection to add to the repository. The following values are supported:
/// </p>
/// <ul>
/// <li>
/// <p>
/// <code>public:npmjs</code> - for the npm public repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:pypi</code> - for the Python Package Index.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-central</code> - for Maven Central.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-googleandroid</code> - for the Google Android repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-commonsware</code> - for the CommonsWare Android repository.
/// </p>
/// </li>
/// </ul>
pub fn external_connection(mut self, input: impl Into<std::string::String>) -> Self {
self.external_connection = Some(input.into());
self
}
/// <p>
/// The name of the external connection to add to the repository. The following values are supported:
/// </p>
/// <ul>
/// <li>
/// <p>
/// <code>public:npmjs</code> - for the npm public repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:pypi</code> - for the Python Package Index.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-central</code> - for Maven Central.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-googleandroid</code> - for the Google Android repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-gradleplugins</code> - for the Gradle plugins repository.
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>public:maven-commonsware</code> - for the CommonsWare Android repository.
/// </p>
/// </li>
/// </ul>
pub fn set_external_connection(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.external_connection = input;
self
}
/// Consumes the builder and constructs a [`AssociateExternalConnectionInput`](crate::input::AssociateExternalConnectionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::AssociateExternalConnectionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::AssociateExternalConnectionInput {
domain: self.domain,
domain_owner: self.domain_owner,
repository: self.repository,
external_connection: self.external_connection,
})
}
}
}
#[doc(hidden)]
pub type AssociateExternalConnectionInputOperationOutputAlias =
crate::operation::AssociateExternalConnection;
#[doc(hidden)]
pub type AssociateExternalConnectionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy;
impl AssociateExternalConnectionInput {
/// Consumes the builder and constructs an Operation<[`AssociateExternalConnection`](crate::operation::AssociateExternalConnection)>
#[allow(clippy::let_and_return)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::AssociateExternalConnection,
aws_http::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
fn uri_base(
_input: &crate::input::AssociateExternalConnectionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/v1/repository/external-connection")
.expect("formatting should succeed");
Ok(())
}
fn uri_query(
_input: &crate::input::AssociateExternalConnectionInput,
mut output: &mut String,
) {
let mut query = aws_smithy_http::query::Writer::new(&mut output);
if let Some(inner_1) = &_input.domain {
query.push_kv("domain", &aws_smithy_http::query::fmt_string(&inner_1));
}
if let Some(inner_2) = &_input.domain_owner {
query.push_kv(
"domain-owner",
&aws_smithy_http::query::fmt_string(&inner_2),
);
}
if let Some(inner_3) = &_input.repository {
query.push_kv("repository", &aws_smithy_http::query::fmt_string(&inner_3));
}
if let Some(inner_4) = &_input.external_connection {
query.push_kv(
"external-connection",
&aws_smithy_http::query::fmt_string(&inner_4),
);
}
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::AssociateExternalConnectionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Bu
// ===== END =====
// ===== BEGIN rust =====
#[doc = "Register `UARTFR` reader"]
pub struct R(crate::R<UARTFR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<UARTFR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<UARTFR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<UARTFR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `RI` reader - Ring indicator. This bit is the complement of the UART ring indicator, nUARTRI, modem status input. That is, the bit is 1 when nUARTRI is LOW."]
pub struct RI_R(crate::FieldReader<bool, bool>);
impl RI_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RI_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RI_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXFE` reader - Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the Line Control Register, UARTLCR_H. If the FIFO is disabled, this bit is set when the transmit holding register is empty. If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does not indicate if there is data in the transmit shift register."]
pub struct TXFE_R(crate::FieldReader<bool, bool>);
impl TXFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXFE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TXFE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXFF` reader - Receive FIFO full. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the receive holding register is full. If the FIFO is enabled, the RXFF bit is set when the receive FIFO is full."]
pub struct RXFF_R(crate::FieldReader<bool, bool>);
impl RXFF_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXFF_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RXFF_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TXFF` reader - Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the transmit holding register is full. If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full."]
pub struct TXFF_R(crate::FieldReader<bool, bool>);
impl TXFF_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
TXFF_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for TXFF_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `RXFE` reader - Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the receive holding register is empty. If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty."]
pub struct RXFE_R(crate::FieldReader<bool, bool>);
impl RXFE_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
RXFE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for RXFE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `BUSY` reader - UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains set until the complete byte, including all the stop bits, has been sent from the shift register. This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether the UART is enabled or not."]
pub struct BUSY_R(crate::FieldReader<bool, bool>);
impl BUSY_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
BUSY_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BUSY_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DCD` reader - Data carrier detect. This bit is the complement of the UART data carrier detect, nUARTDCD, modem status input. That is, the bit is 1 when nUARTDCD is LOW."]
pub struct DCD_R(crate::FieldReader<bool, bool>);
impl DCD_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
DCD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DCD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DSR` reader - Data set ready. This bit is the complement of the UART data set ready, nUARTDSR, modem status input. That is, the bit is 1 when nUARTDSR is LOW."]
pub struct DSR_R(crate::FieldReader<bool, bool>);
impl DSR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
DSR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DSR_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CTS` reader - Clear to send. This bit is the complement of the UART clear to send, nUARTCTS, modem status input. That is, the bit is 1 when nUARTCTS is LOW."]
pub struct CTS_R(crate::FieldReader<bool, bool>);
impl CTS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CTS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CTS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bit 8 - Ring indicator. This bit is the complement of the UART ring indicator, nUARTRI, modem status input. That is, the bit is 1 when nUARTRI is LOW."]
#[inline(always)]
pub fn ri(&self) -> RI_R {
RI_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the Line Control Register, UARTLCR_H. If the FIFO is disabled, this bit is set when the transmit holding register is empty. If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. This bit does not indicate if there is data in the transmit shift register."]
#[inline(always)]
pub fn txfe(&self) -> TXFE_R {
TXFE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - Receive FIFO full. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the receive holding register is full. If the FIFO is enabled, the RXFF bit is set when the receive FIFO is full."]
#[inline(always)]
pub fn rxff(&self) -> RXFF_R {
RXFF_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 5 - Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the transmit holding register is full. If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full."]
#[inline(always)]
pub fn txff(&self) -> TXFF_R {
TXFF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the UARTLCR_H Register. If the FIFO is disabled, this bit is set when the receive holding register is empty. If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty."]
#[inline(always)]
pub fn rxfe(&self) -> RXFE_R {
RXFE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains set un
// ===== END =====
// ===== BEGIN ruby =====
module Dictionary
def self.table_name_prefix
'dictionary_'
end
end
// ===== END =====
// ===== BEGIN ruby =====
# Represents a lock object for a {CloudUser} and {Application}s that it owns
# @!attribute [r] apps
# @return List of {Application}s that are locked
# @!attribute [r] user
# @return {CloudUser} owner of the lock
# @!attribute [r] locked
# @return [Boolean] representing if the user is locked
class Lock
include Mongoid::Document
belongs_to :user, class_name: CloudUser.name
field :locked, type: Boolean, default: false
field :timeout, type: Integer, default: 0
field :app_ids, type: Hash, default: {}
index({:user_id => 1})
create_indexes
# Attempts to lock the {CloudUser}. Once locked, no other threads can obtain a lock on the {CloudUser} or any owned {Application}s.
# This lock is denied if any of the {Application}s owned by the {CloudUser} are currently locked.
#
# == Parameters:
# user::
# The {CloudUser} to attempt to lock
#
# == Returns:
# True if the lock was successful.
def self.create_lock(user)
lock = Lock.find_or_create_by( :user_id => user._id )
end
def self.delete_lock(user)
lock = Lock.delete( :user_id => user._id )
end
# Attempts to lock the {CloudUser}.
# NOTE: User lock is available only for user apps with application lock.
def self.lock_user(user, app, timeout=1800)
begin
now = Time.now.to_i
lock = Lock.find_or_create_by( :user_id => user._id )
query = {:user_id => user._id, "$or" => [{:locked => false}, {:timeout.lt => now}], "app_ids.#{app._id}" => { "$exists" => true }}
updates = {"$set" => { locked: true, timeout: (now + timeout) }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure
return false
end
end
# Attempts to unlock the {CloudUser}.
#
# == Parameters:
# user::
# The {CloudUser} to attempt to unlock
#
# == Returns:
# True if the unlock was successful.
def self.unlock_user(user, app)
begin
query = {:user_id => user._id, :locked => true, "app_ids.#{app._id}" => { "$exists" => true }}
updates = {"$set" => { "locked" => false }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure
return false
end
end
# Attempts to lock an {Application}. Once locked, no other threads can obtain a lock on the {Application} or the {CloudUser} that owns it.
# This lock is denied if the owning {CloudUser} is locked or the {Application} has been locked by another thread.
#
# == Parameters:
# application::
# The {Application} to attempt to lock
#
# == Returns:
# True if the lock was successful.
def self.lock_application(application, timeout=1800)
begin
# application.domain can be nil if the application is being created immediately after domain creation
# If the domain is being read from the secondary, it may not be present
# If domain is nil, try to load the domain from the primary
# Note: If there is a way to load the domain relationship from the primary, we should do that
if application.domain.nil?
user_id = Domain.find_by(_id: application.domain_id).owner_id
else
user_id = application.domain.owner_id
end
app_id = application._id.to_s
now = Time.now.to_i
query = { :user_id => user_id, "$or" => [{"app_ids.#{app_id}" => {"$exists" => false}}, {"app_ids.#{app_id}" => {"$lt" => now}}] }
updates = {"$set"=> { "app_ids.#{app_id}" => (now + timeout) }}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure => ex
Rails.logger.error "Failed to obtain lock for application #{application.name}: #{ex.message}"
return false
end
end
# Attempts to unlock an {Application}.
#
# == Parameters:
# application::
# The {Application} to attempt to unlock
#
# == Returns:
# True if the unlock was successful.
def self.unlock_application(application)
begin
# application.domain can be nil if the application is being created immediately after domain creation
# If the domain is being read from the secondary, it may not be present
# If domain is nil, try to load the domain from the primary
# Note: If there is a way to load the domain relationship from the primary, we should do that
if application.domain.nil?
user_id = Domain.find_by(_id: application.domain_id).owner_id
else
user_id = application.domain.owner_id
end
app_id = application._id.to_s
query = {:user_id => user_id, "app_ids.#{app_id}" => { "$exists" => true }}
updates = {"$unset"=> {"app_ids.#{app_id}" => ""}}
lock = Lock.where(query).find_and_modify(updates, new: true)
return (not lock.nil?)
rescue Moped::Errors::OperationFailure => ex
Rails.logger.error "Failed to unlock application #{application.name}: #{ex.message}"
return false
end
end
end
// ===== END =====
// ===== BEGIN ruby =====
class Lean < Formula
desc "Theorem prover"
homepage "https://leanprover-community.github.io/"
url "https://github.com/leanprover-community/lean/archive/v3.42.1.tar.gz"
sha256 "5b8cbfdea6cf4de5488467297958876aa0b3a79ed5806f7d0f01a0c396beb4e2"
license "Apache-2.0"
head "https://github.com/leanprover-community/lean.git", branch: "master"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
strategy :git do |tags, regex|
tags.map do |tag|
version = tag[regex, 1]
next if version == "9.9.9" # Omit a problematic version tag
version
end
end
end
bottle do
sha256 cellar: :any, arm64_monterey: "58337f99ae7f334d298267e4f0153334d408a72d7640aeb7834d6fc8499ed0ca"
sha256 cellar: :any, arm64_big_sur: "d8dfeaf7e902829013d0109938b910061349a2d16394e48c714a3a1f4b312717"
sha256 cellar: :any, monterey: "1e14e749b7b08576bc0dd91f6f6fec6ab97c1c32d79f22a69c5a6b4b41330f95"
sha256 cellar: :any, big_sur: "d623ba837328fe54810386ce2385aef9d147784bdf71c43fb749e09bf68546a0"
sha256 cellar: :any, catalina: "e16cb80f3a05541ac1d981ff75a6ade15a601931ed8dfa606076ff2b06ac67a9"
sha256 cellar: :any_skip_relocation, x86_64_linux: "4d8d848d08308e6301a5eb4ae8bf6f7155a0936df27270c6a82ba699737c3cca"
end
depends_on "cmake" => :build
depends_on "coreutils"
depends_on "gmp"
depends_on "jemalloc"
depends_on macos: :mojave
on_linux do
depends_on "gcc"
end
conflicts_with "elan-init", because: "`lean` and `elan-init` install the same binaries"
fails_with gcc: "5"
def install
args = std_cmake_args + %w[
-DCMAKE_CXX_FLAGS='-std=c++14'
]
system "cmake", "-S", "src", "-B", "src/build", *args
system "cmake", "--build", "src/build"
system "cmake", "--install", "src/build"
end
test do
(testpath/"hello.lean").write <<~EOS
def id' {α : Type} (x : α) : α := x
inductive tree (α : Type) : Type
| node : α → list tree → tree
example (a b : Prop) : a ∧ b -> b ∧ a :=
begin
intro h, cases h,
split, repeat { assumption }
end
EOS
system bin/"lean", testpath/"hello.lean"
system bin/"leanpkg", "help"
end
end
// ===== END =====
// ===== BEGIN ruby =====
# frozen_string_literal: true
class ProjectFeature < ActiveRecord::Base
# == Project features permissions
#
# Grants access level to project tools
#
# Tools can be enabled only for users, everyone or disabled
# Access control is made only for non private projects
#
# levels:
#
# Disabled: not enabled for anyone
# Private: enabled only for team members
# Enabled: enabled for everyone able to access the project
# Public: enabled for everyone (only allowed for pages)
#
# Permission levels
DISABLED = 0
PRIVATE = 10
ENABLED = 20
PUBLIC = 30
FEATURES = %i(issues merge_requests wiki snippets builds repository pages).freeze
PRIVATE_FEATURES_MIN_ACCESS_LEVEL = { merge_requests: Gitlab::Access::REPORTER }.freeze
class << self
def access_level_attribute(feature)
feature = ensure_feature!(feature)
"#{feature}_access_level".to_sym
end
def quoted_access_level_column(feature)
attribute = connection.quote_column_name(access_level_attribute(feature))
table = connection.quote_table_name(table_name)
"#{table}.#{attribute}"
end
def required_minimum_access_level(feature)
feature = ensure_feature!(feature)
PRIVATE_FEATURES_MIN_ACCESS_LEVEL.fetch(feature, Gitlab::Access::GUEST)
end
private
def ensure_feature!(feature)
feature = feature.model_name.plural.to_sym if feature.respond_to?(:model_name)
raise ArgumentError, "invalid project feature: #{feature}" unless FEATURES.include?(feature)
feature
end
end
# Default scopes force us to unscope here since a service may need to check
# permissions for a project in pending_delete
# http://stackoverflow.com/questions/1540645/how-to-disable-default-scope-for-a-belongs-to
belongs_to :project, -> { unscope(where: :pending_delete) }
validates :project, presence: true
validate :repository_children_level
validate :allowed_access_levels
default_value_for :builds_access_level, value: ENABLED, allows_nil: false
default_value_for :issues_access_level, value: ENABLED, allows_nil: false
default_value_for :merge_requests_access_level, value: ENABLED, allows_nil: false
default_value_for :snippets_access_level, value: ENABLED, allows_nil: false
default_value_for :wiki_access_level, value: ENABLED, allows_nil: false
default_value_for :repository_access_level, value: ENABLED, allows_nil: false
def feature_available?(feature, user)
# This feature might not be behind a feature flag at all, so default to true
return false unless ::Feature.enabled?(feature, user, default_enabled: true)
get_permission(user, access_level(feature))
end
def access_level(feature)
public_send(ProjectFeature.access_level_attribute(feature)) # rubocop:disable GitlabSecurity/PublicSend
end
def builds_enabled?
builds_access_level > DISABLED
end
def wiki_enabled?
wiki_access_level > DISABLED
end
def merge_requests_enabled?
merge_requests_access_level > DISABLED
end
def issues_enabled?
issues_access_level > DISABLED
end
def pages_enabled?
pages_access_level > DISABLED
end
def public_pages?
return true unless Gitlab.config.pages.access_control
pages_access_level == PUBLIC || pages_access_level == ENABLED && project.public?
end
private
# Validates builds and merge requests access level
# which cannot be higher than repository access level
def repository_children_level
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > repository_access_level
self.errors.add(field, "cannot have higher visibility level than repository access level") if not_allowed
end
%i(merge_requests_access_level builds_access_level).each(&validator)
end
# Validates access level for other than pages cannot be PUBLIC
def allowed_access_levels
validator = lambda do |field|
level = public_send(field) || ProjectFeature::ENABLED # rubocop:disable GitlabSecurity/PublicSend
not_allowed = level > ProjectFeature::ENABLED
self.errors.add(field, "cannot have public visibility level") if not_allowed
end
(FEATURES - %i(pages)).each {|f| validator.call("#{f}_access_level")}
end
def get_permission(user, level)
case level
when DISABLED
false
when PRIVATE
user && (project.team.member?(user) || user.full_private_access?)
when ENABLED
true
when PUBLIC
true
else
true
end
end
end
// ===== END =====
// ===== BEGIN ruby =====
# frozen_string_literal: true
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: 'Example User', email: '[email protected]',
password: 'foobar', password_confirmation: 'foobar')
end
test 'should be valid' do
assert @user.valid?
end
test 'name should be present' do
@user.name = ' '
assert_not @user.valid?
end
test 'email should be present' do
@user.email = ' '
assert_not @user.valid?
end
test 'email validation should accept valid addresses' do
valid_addresses = %w[[email protected] [email protected] [email protected]
[email protected] [email protected]]
valid_addresses.each do |valid_address|
@user.email = valid_address
assert @user.valid?, "#{valid_address.inspect} should be valid"
end
end
test 'email validation should reject invalid addresses' do
invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
foo@bar_baz.com foo@bar+baz.com]
invalid_addresses.each do |invalid_address|
@user.email = invalid_address
assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
end
end
test 'email addresses should be unique' do
duplicate_user = @user.dup
@user.save
assert_not duplicate_user.valid?
end
test 'email addresses should be unique (case sensitive)' do
duplicate_user = @user.dup
duplicate_user.email = @user.email.upcase
@user.save
assert_not duplicate_user.valid?
end
test 'email addresses should be saved as lower-case' do
mixed_case_email = '[email protected]'
@user.email = mixed_case_email
@user.save
assert_equal mixed_case_email.downcase, @user.reload.email
end
test 'password should be present (nonblank)' do
@user.password = @user.password_confirmation = ' ' * 6
assert_not @user.valid?
end
test 'password should have a minimum length' do
@user.password = @user.password_confirmation = 'a' * 5
assert_not @user.valid?
end
test 'authenticated? should return false for a user with nil digest' do
assert_not @user.authenticated?('')
end
end
// ===== END =====
// ===== BEGIN ruby =====
class Address < ApplicationRecord
belongs_to :user
belongs_to :order, optional: true
accepts_nested_attributes_for :order
validates :zip_code, presence: { message: "Please Enter Zip Code" }, length: {is: 5, wrong_length: "Zip Code Must Be 5 Digits"}
validates :first_name, presence: { message: "Please Enter First Name" }
validates :last_name, presence: { message: "Please Enter Last Name" }
validates :address, presence: { message: "Please Enter Address" }
validates :city, presence: { message: "Please Enter City" }
validates :state, presence: { message: "Please Enter State" }
validates :country, presence: { message: "Please Enter Country" }
end
// ===== END =====
// ===== BEGIN ruby =====
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'
module Google
module Apis
module PubsubV1beta2
# Cloud Pub/Sub API
#
# Provides reliable, many-to-many, asynchronous messaging between applications.
#
# @example
# require 'google/apis/pubsub_v1beta2'
#
# Pubsub = Google::Apis::PubsubV1beta2 # Alias the module
# service = Pubsub::PubsubService.new
#
# @see https://cloud.google.com/pubsub/docs
class PubsubService < Google::Apis::Core::BaseService
# @return [String]
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token.
attr_accessor :key
# @return [String]
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
attr_accessor :quota_user
def initialize
super('https://pubsub.googleapis.com/', '')
@batch_path = 'batch'
end
# Acknowledges the messages associated with the `ack_ids` in the
# `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages
# from the subscription.
# Acknowledging a message whose ack deadline has expired may succeed,
# but such a message may be redelivered later. Acknowledging a message more
# than once will not result in an error.
# @param [String] subscription
# The subscription whose message is being acknowledged.
# @param [Google::Apis::PubsubV1beta2::AcknowledgeRequest] acknowledge_request_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::PubsubV1beta2::Empty] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::PubsubV1beta2::Empty]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def acknowledge_subscription(subscription, acknowledge_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:post, 'v1beta2/{+subscription}:acknowledge', options)
command.request_representation = Google::Apis::PubsubV1beta2::AcknowledgeRequest::Representation
command.request_object = acknowledge_request_object
command.response_representation = Google::Apis::PubsubV1beta2::Empty::Representation
command.response_class = Google::Apis::PubsubV1beta2::Empty
command.params['subscription'] = subscription unless subscription.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Creates a subscription to a given topic.
# If the subscription already exists, returns `ALREADY_EXISTS`.
# If the corresponding topic doesn't exist, returns `NOT_FOUND`.
# If the name is not provided in the request, the server will assign a random
# name for this subscription on the same project as the topic. Note that
# for REST API requests, you must specify a name.
# @param [String] name
# The name of the subscription. It must have the format
# `"projects/`project`/subscriptions/`subscription`"`. ``subscription`` must
# start with a letter, and contain only letters (`[A-Za-z]`), numbers
# (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`),
# plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters
# in length, and it must not start with `"goog"`.
# @param [Google::Apis::PubsubV1beta2::Subscription] subscription_object
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-specific options
#
# @yield [result, err] Result & error if block supplied
# @yieldparam result [Google::Apis::PubsubV1beta2::Subscription] parsed result object
# @yieldparam err [StandardError] error object if request failed
#
# @return [Google::Apis::PubsubV1beta2::Subscription]
#
# @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried
# @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification
# @raise [Google::Apis::AuthorizationError] Authorization is required
def create_project_subscription(name, subscription_object = nil, fields: nil, quota_user: nil, options: nil, &block)
command = make_simple_command(:put, 'v1beta2/{+name}', options)
command.request_representation = Google::Apis::PubsubV1beta2::Subscription::Representation
command.request_object = subscription_object
command.response_representation = Google::Apis::PubsubV1beta2::Subscription::Representation
command.response_class = Google::Apis::PubsubV1beta2::Subscription
command.params['name'] = name unless name.nil?
command.query['fields'] = fields unless fields.nil?
command.query['quotaUser'] = quota_user unless quota_user.nil?
execute_or_queue_command(command, &block)
end
# Deletes an existing subscription. All pending messages in the subscription
# are immediately dropped. Calls to `Pull` after deletion will return
# `NOT_FOUND`. After a subscription is deleted, a new one may be created with
# the same name, but the new one has no association with the old
# subscription, or its topic unless the same topic is specified.
# @param [String] subscription
# The subscription to delete.
# @param [String] fields
# Selector specifying which fields to include in a partial response.
# @param [String] quota_user
# Available to use for quota purposes for server-side applications. Can be any
# arbitrary string assigned to a user, but should not exceed 40 characters.
# @param [Google::Apis::RequestOptions] options
# Request-
// ===== END =====
// ===== BEGIN ruby =====
# frozen_string_literal: true
class TournamentPolicy < DirectorPolicy
class Scope < ScopeBase
def resolve
user.superuser? ? scope.all : scope.where(id: user.tournament_ids)
end
end
def index?
sufficient_role?
end
def show?
sufficient_access?
end
def update?
sufficient_access?
end
def state_change?
sufficient_access?
end
def clear_test_data?
sufficient_access?
end
def igbots_download?
sufficient_access?
end
def csv_download?
sufficient_access?
end
def update_testing_environment?
sufficient_access?
end
def destroy?
user.superuser?
end
def email_payment_reminders?
sufficient_access?
end
def demo_or_reset?
user.superuser?
end
private
def sufficient_role?
user.superuser? || user.director?
end
def sufficient_access?
user.superuser? || user.director? && user.tournaments.include?(record)
end
end
// ===== END =====
// ===== BEGIN ruby =====
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
# products must have a name, cost and country_of_origin
t.string :name
t.decimal :cost, precision: 6, scale: 2
t.string :country_of_origin
t.timestamps
end
end
end
// ===== END =====
// ===== BEGIN ruby =====
module RSpec
module Expectations
RSpec.describe Configuration do
let(:config) { Configuration.new }
describe "#backtrace_formatter" do
let(:original_backtrace) { %w[ clean-me/a.rb other/file.rb clean-me/b.rb ] }
let(:cleaned_backtrace) { %w[ other/file.rb ] }
let(:formatted_backtrace) do
config.backtrace_formatter.format_backtrace(original_backtrace)
end
before do
@old_patterns = RSpec.configuration.backtrace_exclusion_patterns
@orig_full_backtrace = RSpec.configuration.full_backtrace?
RSpec.configuration.full_backtrace = false
RSpec.configuration.backtrace_exclusion_patterns = [/clean-me/]
end
after do
RSpec.configuration.backtrace_exclusion_patterns = @old_patterns
RSpec.configuration.full_backtrace = @orig_full_backtrace
end
it "defaults to rspec-core's backtrace formatter when rspec-core is loaded" do
expect(config.backtrace_formatter).to be(RSpec.configuration.backtrace_formatter)
expect(formatted_backtrace).to eq(cleaned_backtrace)
end
it "defaults to a null formatter when rspec-core is not loaded" do
RSpec::Mocks.with_temporary_scope do
rspec_dup = ::RSpec.dup
class << rspec_dup; undef configuration; end
stub_const("RSpec", rspec_dup)
expect(formatted_backtrace).to eq(original_backtrace)
end
end
it "can be set to another backtrace formatter" do
config.backtrace_formatter = double(:format_backtrace => ['a'])
expect(formatted_backtrace).to eq(['a'])
end
end
context 'on an interpreter that does not provide BasicObject', :uses_should, :unless => defined?(::BasicObject) do
def with_delegate
in_sub_process_if_possible do
require 'delegate'
RSpec::Expectations::Syntax.disable_should(Delegator)
yield
end
end
let(:klass) do
Class.new(SimpleDelegator) do
def delegated?; true; end
end
end
let(:instance) { klass.new(Object.new) }
it 'provides a means to manually add it Delegator' do
with_delegate do
instance.should_not respond_to(:delegated?) # because #should is being delegated...
config.add_should_and_should_not_to Delegator
instance.should respond_to(:delegated?) # now it should work!
end
end
end
describe "#include_chain_clauses_in_custom_matcher_descriptions?" do
it "is false by default" do
expect(config.include_chain_clauses_in_custom_matcher_descriptions?).to be false
end
it "can be set to true" do
config.include_chain_clauses_in_custom_matcher_descriptions = true
expect(config.include_chain_clauses_in_custom_matcher_descriptions?).to be true
end
it "can be set back to false" do
config.include_chain_clauses_in_custom_matcher_descriptions = true
config.include_chain_clauses_in_custom_matcher_descriptions = false
expect(config.include_chain_clauses_in_custom_matcher_descriptions?).to be false
end
end
describe "#max_formatted_output_length=" do
before do
@orig_max_formatted_output_length = RSpec::Support::ObjectFormatter.default_instance.max_formatted_output_length
end
after do
config.max_formatted_output_length = @orig_max_formatted_output_length
end
let(:object_with_large_inspect_string) { Struct.new(:value).new("a"*300) }
it "sets the maximum object formatter length" do
config.max_formatted_output_length = 10
expect(RSpec::Support::ObjectFormatter.format(object_with_large_inspect_string)).to eq("#<stru...aaa\">")
end
it "formats the entire object when set to nil" do
config.max_formatted_output_length = nil
expect(RSpec::Support::ObjectFormatter.format(object_with_large_inspect_string)).to eq(object_with_large_inspect_string.inspect)
end
end
describe "#warn_about_potential_false_positives?" do
it "is true by default" do
expect(config.warn_about_potential_false_positives?).to be true
end
it "can be set to false" do
config.warn_about_potential_false_positives = false
expect(config.warn_about_potential_false_positives?).to be false
end
it "can be set back to true" do
config.warn_about_potential_false_positives = false
config.warn_about_potential_false_positives = true
expect(config.warn_about_potential_false_positives?).to be true
end
end
describe '#on_potential_false_positives' do
it 'is set to :warn by default' do
expect(config.on_potential_false_positives).to eq :warn
end
it 'can be set to :nothing' do
config.on_potential_false_positives = :nothing
expect(config.on_potential_false_positives).to eq :nothing
end
it 'can be set back to :warn' do
config.on_potential_false_positives = :nothing
config.on_potential_false_positives = :warn
expect(config.on_potential_false_positives).to eq :warn
end
it 'can be set to :raise' do
config.on_potential_false_positives = :raise
expect(config.on_potential_false_positives).to eq :raise
end
end
shared_examples "configuring the expectation syntax" do
before do
@orig_syntax = RSpec::Matchers.configuration.syntax
end
after do
configure_syntax(@orig_syntax)
end
it 'can limit the syntax to :should' do
configure_syntax :should
configured_syntax.should eq([:should])
3.should eq(3)
3.should_not eq(4)
lambda { expect(6).to eq(6) }.should raise_error(NameError)
end
it 'is a no-op when configured to :should twice' do
configure_syntax :should
method_added_count = 0
allow(Expectations::Syntax.default_should_host).to receive(:method_added) { method_added_count += 1 }
configure_syntax :should
method_added_count.should eq(0)
end
it 'can limit the syntax to :expect' do
configure_syntax :expect
expect(configured_syntax).to eq([:expect])
expect(3).to eq(3)
expect { 3.should eq(3) }.to raise_error(NameError)
expect { 3.should_not eq(3) }.to raise_error(NameError)
end
it 'is a no-op when configured to :expect twice' do
allow(RSpec::Matchers).to receive(:method_added).and_raise("no methods should be added here")
configure_syntax :expect
configure_syntax :expect
end
describe "`:should` being enabled by default deprecation" do
before { configure_default_syntax }
it "warns when the should syntax is called by default" do
expected_arguments = [
/Using.*without explicitly enabling/,
{ :replacement => "the new `:expect` syntax or explicitly enable `:should` with `config.expect_with(:rspec) { |c| c.syntax = :should }`" }
]
expect(RSpec).to receive(:depreFile truncated at 1 MB.