text
stringlengths 27
775k
|
---|
# -*- coding: utf-8 -*-
__author__ = 'bizhen'
from page.pages import *
from base.action import ElementActions
import pytest
class TestPersonInfo:
@pytest.fixture
def open_person_info(self, action: ElementActions):
action.click(MyPage.我的)
action.click(MyPage.已登录头像)
action.click(UpOwnerPage.编辑)
@pytest.allure.feature("用户资料")
@pytest.allure.step("用户资料页面")
@pytest.allure.testcase("用例名:资料页面没有修改,点击返回,不显示提示")
def test_not_change_person_info(self,open_person_info):
'''
预置条件:用户已登录
操作步骤:.......
'''
open_person_info
assert action.is_toast_show("昵称不能为空")
#def test_1(self,open_person_info):
# open_person_info |
package com.badoo.automation.deviceserver.data
import com.fasterxml.jackson.annotation.JsonProperty
import java.nio.file.Path
class DataPath(
@JsonProperty("bundle_id")
val bundleId: String,
@JsonProperty("path")
val path: Path) |
<?php
namespace App\Http\Controllers;
use App\Ajax;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function ajaxget()
{
$data = json_decode(Ajax::get());
return $data;
}
public function ajaxPost(Request $request)
{
$name = $request->input('name');
$roll = $request->input('roll');
Ajax::insert([
'name'=>$name,
'roll'=>$roll,
]);
return 'Insert Success';
}
}
|
from django.contrib import admin
from .models import Signing
class SigningAdmin(admin.ModelAdmin):
list_display = ('employee', 'start_date', 'end_date')
search_fields = ('employee', 'start_date', 'end_date')
admin.site.register(Signing, SigningAdmin)
|
# MATLAB Crash Course
Author: methylDragon
Contains a syntax reference for MATLAB!
I'll be adapting it from the ever amazing Derek Banas: https://www.youtube.com/watch?v=NSSTkkKRabI
------
## Pre-Requisites
### Good to know
- Systems
## 1. Introduction
MATLAB stands for Matrix Laboratory. It's a very famous program used for working with matrices.
There are two main windows you'll really type into in MATLAB:
- **The Command Window**
- It's like a terminal! You can define variables here, call functions, and use it like a calculator
- **The Editor**
- You can write scripts here that you can use in the command window!
There's a third section known as the **Workspace**, where you can inspect your variables!
If you ever need to ask for help, either Google for it, or use the `help` function in the command window!
```matlab
help <function>
```
## 2. Command Line Interface
### 2.1 Path
Be sure to ensure that all scripts you want to write are in MATLAB **Path**, in other words, that they are accessible and visible to MATLAB.
In the file explorer on the left, you may add folders and subfolders to your path by right clicking and selecting `Add To Path`. Alternatively, you may double click on a folder to focus it and add it to Path, since your Path also includes your current focused folder!
### 2.2 Clearing Data
```matlab
clc % Clear command window (does not clear variables)
clf % Clear figures
clear % Clear everything
clear all % Clear everything
clear <variable> % Clear single variable
```
### 2.3 Configure Output
```matlab
format compact % Keeps output compact!
```
### 2.4 Stop Execution
Use `CTRL-c` to stop executing a particular command!
### 2.5 Precision
Precision is set to 15 digits by default. But you can configure that!
## 3. Basic MATLAB Syntax Reference <a name="2"></a>
Click on New Script to start creating a new script!
### 3.1 Comments <a name="2.1"></a>
[go to top](#top)
```matlab
% Single Comment
%{
multi
line
comment!
%}
```
You can also use `CTRL-r` to comment and `CTRL-t` to uncomment!
### 3.2 Variables
Everything is a `double` by default in MATLAB.
```matlab
a = 5 % a is now 5! Yay!
```
Data Types:
- int8, int16, int32, int64
- char
- logical (Booleans)
- double
- single (Value without a decimal place)
- uint8
#### **More On Variables**
```matlab
c1 = 'A'
class(c1) % Prints the class/type of the variable!
s1 = 'A string'
class(s1) % With single quotes, the class is 'char'
s2 = "A string"
class(s2) % With double quotes, the class is 'string'
5 > 2 % Logical 1
b1 = true % Logical 1
```
To get the maximum number you can store, you can use these! The maximum and minimums differ depending on the number type. The example list I'm writing below is non-exhaustive.
```matlab
% For ints
intmax('int8')
intmin('int8')
% For doubles
realmax
% For singles
realmax('single')
```
### 3.3 Basic Operations
I really shouldn't need to explain this... You can use MATLAB like a calculator, and the results can go into variables!
```matlab
a = 1 + 2 + 3 + 4 + 5
5 + 5 % Add
5 - 5 % Subtract
5 * 5 % Multiply
5 / 5 % Divide
5 ^ 4 % Exponent
mod(5, 4) % Mod (get remainder)
% NOTE! MATLAB doesn't have increment and decrement operators. So you can't do stuff like a++, b--, etc.
```
### 3.4 Casting
```matlab
v2 = 8
v3 = int8(v2) % Like so!
```
Just write the appropriate class identifier and use it like a function!
### 3.5 Printing and Displaying
```matlab
% Use this to display vectors and numbers!
disp(some_vector_variable)
% Use this to print strings!
fprintf("Hello world!")
% sprintf prints as a string
sprintf('5 + 4 = %d\n', 5 + 4)
% With the %d here, it transplants the next variable argument into the string!
```
### 3.6 User Input
Using the `;` suppresses the input printout after the user has entered the input!
> Note: `"` might not work in some versions of MATLAB as a string delineator. Use `'` in that case.
**String Input**
```matlab
% String Input
% Notice the '' escapes the second quote
name = input('What''s your name : ', 's');
% Let's use this if statement to print the input out! (~ means not)
if ~isempty(name)
fprinf('Hello %s\n', name)
end
```
**Vector Input**
```matlab
vInput = input('Enter a vector : ');
disp(vInput)
```
### 3.7 Useful Math Functions
`help elfun` for a whole list of math functions
```matlab
randi([10, 20]) % Random int
abs(-1) % Returns 1
floor(2.45) % Returns 2
ceil(2.45) % Returns 3
round(2.45) % Returns 2
exp(1) % e^x
log(100) % Log base e (ln)
log10(100) % Log base 10
log2(100) % Log base 2
sqrt(100) % Square root
deg2rad(90)
rad2deg(3.14)
```
### 3.8 Conditionals
```matlab
> % More than
< % Less than
>= % More than or equal to
<= % Less than or equal to
== % Equal to
~= % Not equal to
|| % Or
&& % And
~ % Not
```
**If block**
```matlab
if <condition>
<do something>
elseif <condition>
<do something else>
else
<do something entirely different>
end % REMEMBER TO END!!!
```
**Switch Statement**
```matlab
switch score
case 1
disp("Aw")
case 2
disp("Better")
case 3
disp("You get the point")
otherwise
disp("WHO NAMED IT OTHERWISE OMG")
end % REMEMBER TO END
```
### 3.9 Vectors
They're one dimensional rows or columns!
**THE INDEXING FOR MATLAB STARTS AT 1, NOT 0!!!!**
```matlab
% Row Vectors
vector_1 = [5 3 2 1] % Yep!
vector_2 [5, 3, 2, 1] % Both are valid ways!
% Column Vectors
vector_3 = [5; 3; 2; 1]
% Index into the vectors
vector_1(1) % 5
vector_1(end) % 1 (Last value)
vector([1 2 3]) % Get first, second, and third value in vector
% Get range
vector_1(1:3) % First to third
% Change at index
vector_1(1) = 6
% Transpose Vector
a = [1 2 3]
a' % This is now 1, 2, 3 as a column!
```
**Vector Operations**
```matlab
a = [2; 3; 4]
b = [1 2 3]
a * b
% 2 4 6
% 3 6 9
% 4 8 2
```
### 3.10 Vector Methods
```matlab
vector_1 = [1 2 3 4 5]
length(vector_1)
sort(vector_1, 'descend')
% Create ranges
5 : 10 % Gives you [5 6 7 8 9 10]
2 : 2 : 10 % Gives you [2 4 6 8 10]
% Concatenate
a = [1 2 3]
b = [4 5 6]
[a b] % [1 2 3 4 5 6]
% Dot Product (Either...)
a * b' % Transpose as needed
dot(a, b) % Self explanatory
% Cross Product
cross(a, b) % Nice
% Linspace
linspace(1, 20, 4) % Generates 4 numbers equally spaced between 1 and 20
% Logspace
logspace(1, 3, 3) % Like linspace, but the spacing is logarithmic
```
### 3.11 Matrices
It's MATLAB, not Vector lab.
```matlab
matrix_a = [2 3 4; 4 6 8] % 2 rows, 3 columns (2x3)
length(matrix_a) % Gets you 3 (columns)
numel(matrix_a) % Number of values in matrix (6)
size(matrix_a) % Rows, then Columns (2 3)
% Generate random matrices!
randi([10, 20], 2)
% Index into matrices
a = [1 2 3; 4 5 6; 7 8 9]
a(1, 2) = 22 % Index into single value
a(1, :) = 25 % Change all row values
a(:, 2) % Change all column values
a(end, 1) % Last row
a(1, end) % Last column
% To delete a value, just literally put a semicolon at the end.
a(1, 2) = ;
% Multiply matrices
a * b
% Element-wise multiplication
a .* b % Take note of the period!
% Other matrix stuffffff
a - b
a + b
```
### 3.12 Matrix Methods
The list is not exhaustive!
#### **Construction**
Use the `help` command to find out how these work! They're overloaded functions.
```matlab
eye()
ones()
zeros()
diag()
```
#### **Mathematical Operations**
```matlab
sqrt(a) % Square root all values in matrix
sum(a) % Sum all columns
sum(a, 'all') % Sum all entries
prod(a) % Multiply all column values
cumsum(a, 'reverse') % Cumulative sum. First row stays the same, each row after is the sum of the preceding and current row (reverse makes it go in reverse)
cumsum(a) % Or if you don't want it reversed..
cumprod(a) % Cumulative product.
det() % Determinant
inv() % Inverse
```
#### **Conditionals and Indexing**
```matlab
isequal(a, b) % Check for equality
a > 3 % Apply conditional to all entries
find(a > 24) % Gives you index of entries that fulfill the condition
```
#### **Transformations**
```matlab
fliplr(a) % Flip left to right
flipud(a) % Flip up down
rot90(a) % Rotate 90 degrees
rot90(a, 2) % Rotate 180 degrees
reshape(a, 2, 6) % Reshape into 2x6, it's like numpy!
repmat(a, 2, 1) % Duplicate matrix into new matrix. Eg. If original matrix was 3x3, doing repmat(a, 2, 1) makes it 6x3
repelem(m3, 2, 1) % Duplicates ELEMENTS, so in this case, each element is duplicated twice in terms of the row
```
### 3.13 For Loops
For loops! It's pretty Pythonic. It iterates through a range.
```matlab
% Loop from 1 to 10 and print it
for i = 1:10
disp(i)
end % REMEMBER TO END
% MORE EXAMPLES
% Print every value in matrix
a = [1 2 3; 4 5 6]
for i = 1:2
for j = 1:3
disp(a(i, j))
end
end
% Print for undetermined length
b = [6 7 8]
for i = 1:length(b)
disp(b(i))
end
```
### 3.14 While Loops
```matlab
i = 1 % You must create the variable first!
while i < 20
if(mod(i, 2)) == 0
disp(i)
i = i + 1; % Semicolon suppresses the print
continue
end % This end is for i
i = i + 1;
if i >= 10
break
end
end
```
### 3.15 Cell Arrays
You can store data of multiple types
```matlab
cell_A = {'Hi', 35, [25 8 19]}
cell_B = cell(5) % Create the cell spaces first
cell_A{1} % Get first element
cell_A{3}(2) % Index further
cell_A{4} = 'Something else'
cell_A(4) = ; % Delete
for i = 1:length(cell_A)
disp(cell_A{i})
end
% You can cast character arrays into cell arrays too!
a = ['A', 'BB', 'CCC']
char_array = cellstr(a)
```
### 3.16 Strings
Strings are vectors of characters!
```matlab
str_1 = 'I am a string'
length(str_1)
% Index into a string
str_1(1)
str_1(3:4) % Slices
% Concatenation
str = strcat(str1, ' and now I''m longer!')
% Look for substring
strfind(str, 'a') % Returns indexes of all found substrings
% Replace string
strrep(str, 'longer', 'bigger')
% Split string
str_array = strsplit(str, ' ') % Splits at all spaces. Makes a string array
% Convert numbers to string
int2str(99)
num2str(3.14)
% Check for equality
strcmp(str1, str2)
% Check if is char
ischar('Rawr!11!!1')
% Check if a string is just made of letters
isletter('num 2') % Logical 0
isstrprop('word2', 'alpha')
% Check if string is made of alphanumeric characters
isstrprop('word2', 'alphanum') % Logical 1
% Sort
sort(str, 'descend')
% Delete whitespace (it's like .strip() in python)
strtrim(str)
% Lower and Uppercase conversion
lower(str)
upper(str)
```
### 3.17 Structures
Custom data types! Think C++ structs! Or Python dictionaries/maps.
```matlab
methyl_struct = struct('name', 'methylDragon', ... % the ... lets you skip down to the next line (:
'species', ' Dragon')
disp(methyl_struct.name) % methylDragon
% Add a new field!
methyl_struct.sound = 'Rawr'
% Delete a field
methyl_struct = rmfield(methyl_struct, 'sound')
% Check if field exists
isfield(methyl_struct, 'species')
% Get all field names
fieldnames(methyl_struct)
% Store structures in vectors!
a(1) = methyl_struct
```
### 3.18 Tables
Tables are labelled rows of data in a table format
Get `help table` if you need help.
```matlab
a = {'A'; 'B'; 'C'; 'D'};
b = [29; 42; 1; 2]
c = {'AA', 'BB', 'CC', 'DD'}
% Create a table!!! We'll specify a as the index now
test_table = table(a, b, c, 'RowName', a)
% You can do cool stuff with tables!
mean(test_table.b) % For example.. find the means
% Add new fields
test_table.d = [1; 2; 3]
% Pull specific entries
test_table({'A', 'B'}, :) % This defaults to using the RowName as indexer
% Pull specific entries, using another row
a(ismember(test_table.b, {29, 42},:)
```
### 3.19 File IO
```matlab
% Let's just make a random matrix first
rand_matrix = randi([10, 50], 8)
% Let's save and load some files!
save sampdata.dat rand_matrix -ascii
load sampdata.dat
disp sampdata
type sampdata.dat
% We can save variables in a file as well!
save params % Leaving no arguments saves all variables you have on hand
load params
who % Display it on the screen
a = 123
save -append params a % This appends to the normal variable
```
### 3.20 Eval
If you know Python you should know what this does already.
Eval executes strings as code!
```matlab
toExecute = spritnf('total = %d + %d', 5, 4)
eval(toExecute) % Executes it as:
% total = 5 + 4
```
### 3.21 Pausing
You can pause in MATLAB too! Think of it like Arduino `delay()` or Python `time.sleep()`
```matlab
pause(5) % Pause for 5 seconds
pause off % Disable pause
pause on % Enable pause
```
## 4. Functional and OOP MATLAB
### 4.1 Functions
Functions have to come at the **end** of your file!
Local and global variable rules still apply! Local variables defined in functions don't change outside of the function! Just take note!
```matlab
% Function to calculate volume
% The return is defined by the name preceding the =
% The name of the function is the name following the =
% In this case, the return is 'vol' and the function name is 'cylinderVol'
function vol = cylinderVol(radius, height)
vol = pi radius^2 * height
end
% Let's try another one! This time a function with no arguments
function randNum = getRandomNum
randNum = randi([1, 100])
end
% Return more than one value
[coneV, cylVol] = getVols(10, 20) % I'll call the function here, and define it below
function [coneVol, cylinVol] = getVols(radius, height)
cylinVol = pi * radius^2 * height
coneVol = 1/3 * cylinVol
end
% Variable Number of Arguments
function sum = getSum(varargin)
sum = 0;
for k = 1:length(varargin)
sum = sum + varargin{k}(1);
end
end
% Return variable number of outputs
function [varargout] = getNumbers(howMany)
for k = 1:howMany
varargout{1}(k) = k;
end
end
```
### 4.2 Anonymous Functions
No named functions! Think lambda in python
```matlab
cubeVol = @ (l, w, h) l * w * h; % (input) output
a = cubeVol(2, 2, 2) % Gives you 8! Correct!
```
**Pass Function to another Function**
Think decorators!
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
```matlab
mult3 = @ (x) x * 3;
sol = doMath(mult3, 4)
function sol = doMath(func, num)
sol = func(num);
end
```
**Returning Functions**
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
```matlab
mult4 = doMath2(4);
sol2 = mult4(5)
function func = doMath2(num)
func = @(x) x * num;
end
```
### 4.3 Recursive Functions
They call themselves!
```matlab
function val = factorial(num)
if num == 1
val = 1;
else
val = num * factorial(num - 1);
end
end
```
### 4.4 Classes
Static members are shared amongst all members of a class
```matlab
classdef Shape
properties % Variables!!!
height
width
end
methods(Static)
function out = setGetNumShapes(data)
% Persistent values are shared by all objects also
persistent Var;
if isempty(Var)
Var = 0;
end
if nargin % Number of input arguments
Var = Var + data
end
out = Var;
end
end
methods
% Define a constructor
function obj = Shape(height, width)
obj.height = height
obj.width = width
obj.setGetNumShapes(1)
end
% Overloaded disp function
% If you don't know what overloading is, check my C++ tutorial. It basically overwrites the functionality of a pre-existing function if the argument number matches
function disp(obj)
fprintf('Height : %.2f / Width : %.2f\n', obj.height, obj.width)
end
function area = getArea(obj)
area = obj.height * obj.width;
end
% Overload Greater Than function
function tf = gt(obja, objb)
tf = obja.getArea > objb.getArea
end
end
end
```
**Let's try using it!**
```matlab
a1 = Shape(10, 20)
disp(a1)
Shape.setGetNumShapes
a1.getArea
a2 = Shape(5, 10)
disp(a2)
Shape.setGetNumShapes
a1 > a2
```
### 4.5 Class Inheritance
```matlab
classdef Trapezoid < Shape % Trapezoid inherits from Shape
properties
width2
end
methods
function obj = Trapezoid(height, width, width2)
obj@Shape(height,width) % The @ sign means you're taking it from the parent
% In this case we're using Shape's constructor!
obj.width2 = width2
end
function disp(obj)
fprint('Height : %.2f / Width : %.2f / Width2 : %.2f', obj.height, obj.width, obj.width2);
end
function area = getArea(obj)
area = (obj.height/2) * (obj.width + obj.width2);
end
end
end
```
**Let's try it out!**
```matlab
a3 = Trapezoid(10, 4, 6)
disp(a3)
a3.getArea
```
## 5. Plotting
### 5.1 Plotting in MATLAB
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
`help plot` for help!
```matlab
xVals = 1:5
yVals = [2 4 8 5 9]
yVals2 = [1 5 7 6 8]
figure(1)
plot(xVals, yVals, 'g+', 'LineWidth', 2)
hold on % Draw over what was plotted, keep plot settings
plot(xVals, yVals2, 'k*')
legend('yVals', 'yVals2')
grid on % Turn grid on
xlabel('Days')
ylabel('Money')
title('Money Made Today')
figure(2)
bar(xVals, yVals, 'r')
% Colors : blue(b), black(k), cyan(c), green(g),
% magenta(m), red(r), yellow(y), white(y)
% Plot Symbols : . o x + * s d v ^ < > p h
% Line Types : -, :, -., - -
% Set font weights and the like
% gca is the axis object, gcf is the figure object
set(gca, 'FontWeight', 'bold', 'FontSize', 20, 'color', 'white');
set(gcf, 'color', 'white')
clf % Delete all figures
```
#### **Example Sinusoid with Time**
```matlab
y = A.*cos(2*pi .* t/T - 2*pi .* x/lambda + phi0);
```
### 5.2 3D Plotting in MATLAB
#### **3D Plots and Meshgrids**

```matlab
plot3() % Use this instead of plot2!
% Example
t = 0: pi/50 : 10*pi;
plot3(sin(t), cos(t), t)
% Meshgrids
meshgrid()
```
#### **Surfaces**
```matlab
% Plot surfaces
cylinder()
sphere()
surf() % Plot a surface
isosurface() % For when plotting normal surfaces are too hard
contour() % Plot a contour map instead
```
#### **Vector Fields**
```matlab
quiver() % 2D
quiver3() % 3D
colorbar % Add a colorbar!
```
## 6. Intermediate and Advanced Math
### 6.1 Vector Calculus
```matlab
gradient()
divergence()
curl()
del2() % Discrete laplacian
```
```
. .
. |\-^-/| .
/| } O.=.O { |\
```
------
[.png)](https://www.buymeacoffee.com/methylDragon)
|
package org.silkframework.runtime.validation
/**
* Request exception.
* This will lead to a JSON error response if thrown inside a REST endpoint.
*
* @param msg The detailed error description.
* @param cause The optional cause of this exception.
*
*/
abstract class RequestException(msg: String, cause: Option[Throwable]) extends RuntimeException(msg, cause.orNull) {
/**
* A short description of the error type, e.g, "Task not found".
* Should be the same for all instances of the error type.
*/
def errorTitle: String
/**
* The HTTP error code that fits best to the given error type.
*/
def httpErrorCode: Option[Int]
}
|
// SPDX-FileCopyrightText: 2020-present Open Networking Foundation <[email protected]>
//
// SPDX-License-Identifier: Apache-2.0
package mho
import (
"context"
subutils "github.com/onosproject/ran-simulator/pkg/utils/e2ap/subscription"
)
func (m *Mho) processRrcUpdate(ctx context.Context, subscription *subutils.Subscription) {
log.Info("Start processing RRC updates")
for update := range m.rrcUpdateChan {
log.Debugf("Received RRC Update, IMSI:%v, GnbID:%v, NCGI:%v", update.IMSI, update.Cell.ID, update.Cell.NCGI)
ue, err := m.ServiceModel.UEs.Get(ctx, update.IMSI)
if err != nil {
log.Warn(err)
continue
}
err = m.sendRicIndicationFormat2(ctx, update.Cell.NCGI, ue, subscription)
if err != nil {
log.Warn(err)
continue
}
}
}
|
using System.Runtime.Serialization;
namespace Checkout.Risk.PreAuthentication
{
public enum PreAuthenticationDecision
{
[EnumMember(Value = "try_exemptions")] TryExemptions,
[EnumMember(Value = "try_frictionless")]
TryFrictionless,
[EnumMember(Value = "no_preference")] NoPreference,
[EnumMember(Value = "force_challenge")]
ForceChallenge,
[EnumMember(Value = "decline")] Decline
}
} |
// WITH_RUNTIME
inline fun <reified T : CharSequence, reified U, X> foo() {
<selection>listOf(T::class, U::class)</selection>
} |
<?php
foreach($fields as $f => $field) { ?>
<label>
<span><?php print ($view->escape($field)); ?></span>
</label>
<?php } |
/* --------------------------------------------------------------------------
* File: BendersATSP.java
* Version 12.8.0
* --------------------------------------------------------------------------
* Licensed Materials - Property of IBM
* 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
* Copyright IBM Corporation 2001, 2017. All Rights Reserved.
*
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with
* IBM Corp.
* --------------------------------------------------------------------------
*
* Example BendersATSP.java solves a flow MILP model for an
* Asymmetric Traveling Salesman Problem (ATSP) instance
* through Benders decomposition.
*
* The arc costs of an ATSP instance are read from an input file.
* The flow MILP model is decomposed into a master ILP and a worker LP.
*
* The master ILP is then solved by adding Benders' cuts during
* the branch-and-cut process via the cut callback classes
* IloCplex.LazyConstraintCallback and IloCplex.UserCutCallback.
* The cut callbacks add to the master ILP violated Benders' cuts
* that are found by solving the worker LP.
*
* The example allows the user to decide if Benders' cuts have to be separated:
*
* a) Only to separate integer infeasible solutions.
* In this case, Benders' cuts are treated as lazy constraints through the
* class IloCplex.LazyConstraintCallback.
*
* b) Also to separate fractional infeasible solutions.
* In this case, Benders' cuts are treated as lazy constraints through the
* class IloCplex.LazyConstraintCallback.
* In addition, Benders' cuts are also treated as user cuts through the
* class IloCplex.UserCutCallback.
*
*
* To run this example, command line arguments are required:
* java BendersATSP {0|1} [filename]
* where
* 0 Indicates that Benders' cuts are only used as lazy constraints,
* to separate integer infeasible solutions.
* 1 Indicates that Benders' cuts are also used as user cuts,
* to separate fractional infeasible solutions.
*
* filename Is the name of the file containing the ATSP instance (arc costs).
* If filename is not specified, the instance
* ../../../examples/data/atsp.dat is read
*
*
* ATSP instance defined on a directed graph G = (V, A)
* - V = {0, ..., n-1}, V0 = V \ {0}
* - A = {(i,j) : i in V, j in V, i != j }
* - forall i in V: delta+(i) = {(i,j) in A : j in V}
* - forall i in V: delta-(i) = {(j,i) in A : j in V}
* - c(i,j) = traveling cost associated with (i,j) in A
*
* Flow MILP model
*
* Modeling variables:
* forall (i,j) in A:
* x(i,j) = 1, if arc (i,j) is selected
* = 0, otherwise
* forall k in V0, forall (i,j) in A:
* y(k,i,j) = flow of the commodity k through arc (i,j)
*
* Objective:
* minimize sum((i,j) in A) c(i,j) * x(i,j)
*
* Degree constraints:
* forall i in V: sum((i,j) in delta+(i)) x(i,j) = 1
* forall i in V: sum((j,i) in delta-(i)) x(j,i) = 1
*
* Binary constraints on arc variables:
* forall (i,j) in A: x(i,j) in {0, 1}
*
* Flow constraints:
* forall k in V0, forall i in V:
* sum((i,j) in delta+(i)) y(k,i,j) - sum((j,i) in delta-(i)) y(k,j,i) = q(k,i)
* where q(k,i) = 1, if i = 0
* = -1, if k == i
* = 0, otherwise
*
* Capacity constraints:
* forall k in V0, for all (i,j) in A: y(k,i,j) <= x(i,j)
*
* Nonnegativity of flow variables:
* forall k in V0, for all (i,j) in A: y(k,i,j) >= 0
*/
import ilog.concert.*;
import ilog.cplex.*;
public class BendersATSP {
// The class BendersLazyConsCallback
// allows to add Benders' cuts as lazy constraints.
//
public static class BendersLazyConsCallback
extends IloCplex.LazyConstraintCallback {
final IloIntVar[][] x;
final WorkerLP workerLP;
final int numNodes;
BendersLazyConsCallback(IloIntVar[][] x, WorkerLP workerLP) {
this.x = x;
this.workerLP = workerLP;
numNodes = x.length;
}
public void main() throws IloException {
// Get the current x solution
double[][] sol = new double[numNodes][];
for (int i = 0; i < numNodes; ++i)
sol[i] = getValues(x[i]);
// Benders' cut separation
IloRange cut = workerLP.separate(sol, x);
if ( cut != null) add(cut, IloCplex.CutManagement.UseCutForce);
}
} // END BendersLazyConsCallback
// The class BendersUserCutCallback
// allows to add Benders' cuts as user cuts.
//
public static class BendersUserCutCallback
extends IloCplex.UserCutCallback {
final IloIntVar[][] x;
final WorkerLP workerLP;
final int numNodes;
BendersUserCutCallback(IloIntVar[][] x, WorkerLP workerLP) {
this.x = x;
this.workerLP = workerLP;
numNodes = x.length;
}
public void main() throws IloException {
// Skip the separation if not at the end of the cut loop
if ( !isAfterCutLoop() )
return;
// Get the current x solution
double[][] sol = new double[numNodes][];
for (int i = 0; i < numNodes; ++i)
sol[i] = getValues(x[i]);
// Benders' cut separation
IloRange cut = workerLP.separate(sol, x);
if ( cut != null) add(cut, IloCplex.CutManagement.UseCutForce);
}
} // END BendersUserCutCallback
// Data class to read an ATSP instance from an input file
//
static class Data {
int numNodes;
double[][] arcCost;
Data(String fileName) throws IloException, java.io.IOException,
InputDataReader.InputDataReaderException {
InputDataReader reader = new InputDataReader(fileName);
arcCost = reader.readDoubleArrayArray();
numNodes = arcCost.length;
for (int i = 0; i < numNodes; ++i) {
if ( arcCost[i].length != numNodes )
throw new IloException("Inconsistent data in file " + fileName);
arcCost[i][i] = 0.;
}
}
} // END Data
// This class builds the worker LP (i.e., the dual of flow constraints and
// capacity constraints of the flow MILP) and allows to separate violated
// Benders' cuts.
//
static class WorkerLP {
IloCplex cplex;
int numNodes;
IloNumVar[][][] v;
IloNumVar[][] u;
IloObjective obj;
// The constructor sets up the IloCplex instance to solve the worker LP,
// and creates the worker LP (i.e., the dual of flow constraints and
// capacity constraints of the flow MILP)
//
// Modeling variables:
// forall k in V0, i in V:
// u(k,i) = dual variable associated with flow constraint (k,i)
//
// forall k in V0, forall (i,j) in A:
// v(k,i,j) = dual variable associated with capacity constraint (k,i,j)
//
// Objective:
// minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
// - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
//
// Constraints:
// forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
//
// Nonnegativity on variables v(k,i,j)
// forall k in V0, forall (i,j) in A: v(k,i,j) >= 0
//
WorkerLP(int numNodes) throws IloException {
this.numNodes = numNodes;
int i, j, k;
// Set up IloCplex instance to solve the worker LP
cplex = new IloCplex();
cplex.setOut(null);
// Turn off the presolve reductions and set the CPLEX optimizer
// to solve the worker LP with primal simplex method.
cplex.setParam(IloCplex.Param.Preprocessing.Reduce, 0);
cplex.setParam(IloCplex.Param.RootAlgorithm, IloCplex.Algorithm.Primal);
// Create variables v(k,i,j) forall k in V0, (i,j) in A
// For simplicity, also dummy variables v(k,i,i) are created.
// Those variables are fixed to 0 and do not partecipate to
// the constraints.
v = new IloNumVar[numNodes-1][numNodes][numNodes];
for (k = 1; k < numNodes; ++k) {
for (i = 0; i < numNodes; ++i) {
for (j = 0; j < numNodes; ++j) {
v[k-1][i][j] = cplex.numVar(0., Double.MAX_VALUE, "v." + k + "." + i + "." + j);
cplex.add(v[k-1][i][j]);
}
v[k-1][i][i].setUB(0.);
}
}
// Create variables u(k,i) forall k in V0, i in V
u = new IloNumVar[numNodes-1][numNodes];
for (k = 1; k < numNodes; ++k) {
for(i = 0; i < numNodes; ++i) {
u[k-1][i] = cplex.numVar(-Double.MAX_VALUE, Double.MAX_VALUE, "u." + k + "." + i);
cplex.add(u[k-1][i]);
}
}
// Initial objective function is empty
obj = cplex.addMinimize();
// Add constraints:
// forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
for (k = 1; k < numNodes; ++k) {
for(i = 0; i < numNodes; ++i) {
for(j = 0; j < numNodes; ++j) {
if ( i != j ) {
IloLinearNumExpr expr = cplex.linearNumExpr();
expr.addTerm(v[k-1][i][j], -1.);
expr.addTerm(u[k-1][i], 1.);
expr.addTerm(u[k-1][j], -1.);
cplex.addLe(expr, 0.);
}
}
}
}
} // END WorkerLP
void end() { cplex.end(); }
// This method separates Benders' cuts violated by the current x solution.
// Violated cuts are found by solving the worker LP
//
IloRange separate(double[][] xSol, IloIntVar[][] x) throws IloException {
int i, j, k;
IloRange cut = null;
// Update the objective function in the worker LP:
// minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
// - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
IloLinearNumExpr objExpr = cplex.linearNumExpr();
for (k = 1; k < numNodes; ++k) {
for(i = 0; i < numNodes; ++i) {
for(j = 0; j < numNodes; ++j) {
objExpr.addTerm(v[k-1][i][j], xSol[i][j]);
}
}
}
for (k = 1; k < numNodes; ++k) {
objExpr.addTerm(u[k-1][k], 1.);
objExpr.addTerm(u[k-1][0], -1.);
}
obj.setExpr(objExpr);
// Solve the worker LP
cplex.solve();
// A violated cut is available iff the solution status is Unbounded
if ( cplex.getStatus().equals(IloCplex.Status.Unbounded) ) {
// Get the violated cut as an unbounded ray of the worker LP
IloLinearNumExpr rayExpr = cplex.getRay();
// Compute the cut from the unbounded ray. The cut is:
// sum((i,j) in A) (sum(k in V0) v(k,i,j)) * x(i,j) >=
// sum(k in V0) u(k,0) - u(k,k)
IloLinearNumExpr cutLhs = cplex.linearNumExpr();
double cutRhs = 0.;
IloLinearNumExprIterator iter = rayExpr.linearIterator();
while ( iter.hasNext() ) {
IloNumVar var = iter.nextNumVar();
boolean varFound = false;
for (k = 1; k < numNodes && !varFound; ++k) {
for (i = 0; i < numNodes && !varFound; ++i) {
for (j = 0; j < numNodes && !varFound; ++j) {
if ( var.equals(v[k-1][i][j]) ) {
cutLhs.addTerm(x[i][j], iter.getValue());
varFound = true;
}
}
}
}
for (k = 1; k < numNodes && !varFound; ++k) {
for (i = 0; i < numNodes && !varFound; ++i) {
if ( var.equals(u[k-1][i]) ) {
if ( i == 0 )
cutRhs += iter.getValue();
else if ( i == k )
cutRhs -= iter.getValue();
varFound = true;
}
}
}
}
cut = cplex.ge(cutLhs, cutRhs);
}
return cut;
} // END separate
} // END WorkerLP
// This method creates the master ILP (arc variables x and degree constraints).
//
// Modeling variables:
// forall (i,j) in A:
// x(i,j) = 1, if arc (i,j) is selected
// = 0, otherwise
//
// Objective:
// minimize sum((i,j) in A) c(i,j) * x(i,j)
//
// Degree constraints:
// forall i in V: sum((i,j) in delta+(i)) x(i,j) = 1
// forall i in V: sum((j,i) in delta-(i)) x(j,i) = 1
//
// Binary constraints on arc variables:
// forall (i,j) in A: x(i,j) in {0, 1}
//
static void createMasterILP(IloModeler model,
Data data,
IloIntVar[][] x) throws IloException {
int i, j;
int numNodes = data.numNodes;
// Create variables x(i,j) for (i,j) in A
// For simplicity, also dummy variables x(i,i) are created.
// Those variables are fixed to 0 and do not partecipate to
// the constraints.
for (i = 0; i < numNodes; ++i) {
for (j = 0; j < numNodes; ++j) {
x[i][j] = model.boolVar("x." + i + "." + j);
model.add(x[i][j]);
}
x[i][i].setUB(0);
}
// Create objective function: minimize sum((i,j) in A ) c(i,j) * x(i,j)
IloLinearNumExpr objExpr = model.linearNumExpr();
for (i = 0; i < numNodes; ++i)
objExpr.add(model.scalProd(x[i], data.arcCost[i]));
model.addMinimize(objExpr);
// Add the out degree constraints.
// forall i in V: sum((i,j) in delta+(i)) x(i,j) = 1
for (i = 0; i < numNodes; ++i) {
IloLinearNumExpr expr = model.linearNumExpr();
for (j = 0; j < i; ++j) expr.addTerm(x[i][j], 1.);
for (j = i+1; j < numNodes; ++j) expr.addTerm(x[i][j], 1.);
model.addEq(expr, 1.);
}
// Add the in degree constraints.
// forall i in V: sum((j,i) in delta-(i)) x(j,i) = 1
for (i = 0; i < numNodes; ++i) {
IloLinearNumExpr expr = model.linearNumExpr();
for (j = 0; j < i; ++j) expr.addTerm(x[j][i], 1.);
for (j = i+1; j < numNodes; ++j) expr.addTerm(x[j][i], 1.);
model.addEq(expr, 1.);
}
} // END createMasterILP
public static void main(String[] args) {
try {
String fileName = "../../../examples/data/atsp.dat";
// Check the command line arguments
if ( args.length != 1 && args.length != 2) {
usage();
return;
}
if ( ! (args[0].equals("0") || args[0].equals("1")) ) {
usage();
return;
}
boolean separateFracSols = ( args[0].charAt(0) == '0' ? false : true );
if ( separateFracSols ) {
System.out.println("Benders' cuts separated to cut off: " +
"Integer and fractional infeasible solutions.");
}
else {
System.out.println("Benders' cuts separated to cut off: " +
"Only integer infeasible solutions.");
}
if ( args.length == 2 ) fileName = args[1];
// Read arc_costs from data file (9 city problem)
Data data = new Data(fileName);
// create master ILP
int numNodes = data.numNodes;
IloCplex cplex = new IloCplex();
IloIntVar[][] x = new IloIntVar[numNodes][numNodes];
createMasterILP(cplex, data, x);
// Create workerLP for Benders' cuts separation
WorkerLP workerLP = new WorkerLP(numNodes);
// Set up the cut callback to be used for separating Benders' cuts
cplex.setParam(IloCplex.Param.Preprocessing.Presolve, false);
// Set the maximum number of threads to 1.
// This instruction is redundant: If MIP control callbacks are registered,
// then by default CPLEX uses 1 (one) thread only.
// Note that the current example may not work properly if more than 1 threads
// are used, because the callback functions modify shared global data.
// We refer the user to the documentation to see how to deal with multi-thread
// runs in presence of MIP control callbacks.
cplex.setParam(IloCplex.Param.Threads, 1);
// Turn on traditional search for use with control callbacks
cplex.setParam(IloCplex.Param.MIP.Strategy.Search, IloCplex.MIPSearch.Traditional);
cplex.use(new BendersLazyConsCallback(x, workerLP));
if ( separateFracSols )
cplex.use(new BendersUserCutCallback(x, workerLP));
// Solve the model and write out the solution
if ( cplex.solve() ) {
System.out.println();
System.out.println("Solution status: " + cplex.getStatus());
System.out.println("Objective value: " + cplex.getObjValue());
if ( cplex.getStatus().equals(IloCplex.Status.Optimal) ) {
// Write out the optimal tour
int i, j;
double[][] sol = new double[numNodes][];
int[] succ = new int[numNodes];
for (j = 0; j < numNodes; ++j)
succ[j] = -1;
for (i = 0; i < numNodes; ++i) {
sol[i] = cplex.getValues(x[i]);
for(j = 0; j < numNodes; ++j) {
if ( sol[i][j] > 1e-03 ) succ[i] = j;
}
}
System.out.println("Optimal tour:");
i = 0;
while ( succ[i] != 0 ) {
System.out.print(i + ", ");
i = succ[i];
}
System.out.println(i);
}
else {
System.out.println("Solution status is not Optimal");
}
}
else {
System.out.println("No solution available");
}
workerLP.end();
cplex.end();
}
catch (IloException ex) {
System.out.println("Concert Error: " + ex);
}
catch (InputDataReader.InputDataReaderException ex) {
System.out.println("Data Error: " + ex);
}
catch (java.io.IOException ex) {
System.out.println("IO Error: " + ex);
}
} // END main
static void usage() {
System.out.println("Usage: java BendersATSP {0|1} [filename]");
System.out.println(" 0: Benders' cuts only used as lazy constraints,");
System.out.println(" to separate integer infeasible solutions.");
System.out.println(" 1: Benders' cuts also used as user cuts,");
System.out.println(" to separate fractional infeasible solutions.");
System.out.println(" filename: ATSP instance file name.");
System.out.println(" File ../../../examples/data/atsp.dat used " +
"if no name is provided.");
} // END BendersATSP.usage
} // END BendersATSP
|
CREATE DATABASE `dbvideo_club` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;
CREATE TABLE `film` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`genre` varchar(45) CHARACTER SET utf8mb4 DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`time_filmrent` bigint(20) DEFAULT NULL,
`n_rentperfilm` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) CHARACTER SET utf8mb4 DEFAULT NULL,
`password` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
`first_name` varchar(45) CHARACTER SET utf8mb4 DEFAULT NULL,
`last_name` varchar(45) CHARACTER SET utf8mb4 DEFAULT NULL,
`jmbg` bigint(13) DEFAULT NULL,
`telephone` varchar(45) CHARACTER SET utf8 DEFAULT NULL,
`n_rentperuser` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username_UNIQUE` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) CHARACTER SET utf8mb4 DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `user_film` (
`film_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`film_id`,`user_id`),
KEY `uid_idx` (`user_id`),
KEY `fid_idx` (`film_id`),
CONSTRAINT `fid` FOREIGN KEY (`film_id`) REFERENCES `film` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `uid` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_role` (
`usr_id` int(11) NOT NULL,
`rol_id` int(11) NOT NULL,
PRIMARY KEY (`usr_id`,`rol_id`),
KEY `rid_idx` (`rol_id`),
KEY `uid_idx` (`usr_id`),
CONSTRAINT `rolid` FOREIGN KEY (`rol_id`) REFERENCES `role` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `usrid` FOREIGN KEY (`usr_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
<?php
namespace webignition\WebResource\Sitemap\UrlExtractor;
abstract class AbstractSitemapsOrgXmlExtractor implements UrlExtractorInterface
{
const SITEMAP_XML_NAMESPACE_REFERENCE = 's';
abstract protected function getXpath(): string;
public function extract(string $content): array
{
$urls = [];
$xml = new \SimpleXMLElement($content);
$xml->registerXPathNamespace('s', $this->deriveNamespace($xml));
$result = $xml->xpath($this->getXpath());
foreach ($result as $url) {
$urls[] = (string)$url;
}
return $urls;
}
private function deriveNamespace(\SimpleXMLElement $xml)
{
$namespaces = $xml->getNamespaces();
foreach ($namespaces as $namespace) {
if (preg_match('/\/schemas\/sitemap\/[0-9\.]+$/', $namespace) > 0) {
return $namespace;
}
}
return null;
}
}
|
# frozen_string_literal: true
class Mutations::CreateToc < Mutations::BaseMutation
argument :repository_id, ID, required: true, description: "Repository primary id"
argument :title, String, required: true, description: "Title"
argument :url, String, required: false, description: "URL"
argument :external, Boolean, required: false, default_value: false, description: "External only create Toc, otherwice will create a blank doc"
argument :target_id, ID, required: false, description: "Order toc with the target (default: append to bottom)"
argument :position, String, required: false, default_value: "right", description: "If you give target_id, this option for speical the positon of toc: [left, right, child]"
argument :body, String, required: false, default_value: "", description: "Document content for markdown"
argument :body_sml, String, required: false, default_value: "", description: "Document content for sml"
argument :format, String, required: false, default_value: "sml", description: "Document content type"
type ::Types::TocType
def resolve(repository_id:, title: nil, url: nil, target_id: nil, position: "right", external: false, body: nil, body_sml: nil, format: "sml")
@repository = Repository.find(repository_id)
authorize! :create_doc, @repository
if !external
@doc = Doc.create_new(@repository, current_user.id, slug: url, title: title)
@doc.format = format
@doc.body = body
@doc.body_sml = body_sml
@doc.save
@toc = @doc.toc
else
@toc = @repository.tocs.create(title: title, url: url)
end
if target_id
target = @repository.tocs.find(target_id)
@toc.move_to(target, position.to_sym) if target
end
@toc
end
end
|
# frozen_string_literal: true
require 'spec_helper'
describe 'Anonymous function syntax' do
it 'anonymous function' do
expect(<<~'EOF').to include_elixir_syntax('elixirAnonymousFunction', 'fn')
fn(_, state) -> state end
EOF
end
it 'as a default argument' do
expect(<<~'EOF').to include_elixir_syntax('elixirAnonymousFunction', 'fn')
def exec(func \\ fn(_, state) -> state end) do
end
EOF
end
it 'as a default argument in a module' do
str = <<~'EOF'
defmodule HelloWorld do
def exec(func \\ fn(_, state) -> state end) do
end
end
EOF
expect(str).to include_elixir_syntax('elixirAnonymousFunction', 'fn')
# Test that the syntax properly closed
expect(str).to include_elixir_syntax('elixirBlockDefinition', '^end')
end
end
|
<?php
session_start();
include_once '../model/mysql.class.php';
$helper = new helper();
$reback =1;
$name = $_GET['name'];
$password =md5($_GET['pass']);
$email = $_GET['email'];
$sql= "insert into user(name,pass,email) ";
$sql.="values ('$name','$password','$email')";
$sql1="select * from user where name='".$name."'";
$res=$helper->dql($sql1);
if($res==null){
$rst= $helper->exectue_dml($sql);
if($rst!=1)
{
$reback =3;
echo $reback;
}
else
{
$_SESSION['member']=$name;
$_SESSION['id'] =$helper->insert_id();
$reback =2;
echo $reback;
}
}
else echo $reback;
?> |
# frozen_string_literal: true
module Sicily
Sicily.register_generator do |generator|
generator.filename = 'google_photo.rb'
generator.load_on_start = true
generator.content = <<~CONTENT
Sicily.configure_google do |config|
config.id = 'your id'
config.pw = 'your pw'
end
CONTENT
generator.post_generate_message = <<~MESSAGE
To upload to Google Photos,
turn on "Allowing less secure apps to access your account"
: https://support.google.com/accounts/answer/6010255
*USE AT YOUR OWN RISK*
MESSAGE
end
end
|
package minietcd
import (
"encoding/json"
"errors"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
)
type versionResponse struct {
EtcdCluster string `json:"etcdcluster"`
EtcdServer string `json:"etcdserver"`
}
type readResponse struct {
Action string `json:"action"`
Node struct {
Node
Nodes []Node `json:"nodes"`
} `json:"node"`
}
type Node struct {
Dir bool `json:"dir,omitempty"`
Key string `json:"key"`
Value string `json:"value,omitempty"`
CreatedIndex int `json:"createdIndex"`
ModifiedIndex int `json:"modifiedIndex"`
}
var ErrSupportedVersion = errors.New("minietcd only works with version 2")
type Conn struct {
_url string
client *http.Client
log *log.Logger
}
func New() (conn *Conn) {
conn = new(Conn)
conn.client = &http.Client{Timeout: 5 * time.Second}
conn.log = log.New(os.Stdout, "[minietcd] ", log.LstdFlags)
return conn
}
func (c *Conn) SetLoggingOutput(w io.Writer) {
c.log.SetOutput(w)
}
func (c *Conn) Dial(_url string) error {
c._url = _url
resp, err := c.do("/version")
if err != nil {
return err
}
defer resp.Body.Close()
var etcdResponse versionResponse
err = json.NewDecoder(resp.Body).Decode(&etcdResponse)
if err != nil {
return err
}
serverVersionOk := strings.HasPrefix(etcdResponse.EtcdServer, "2.")
clusterVersionOk := strings.HasPrefix(etcdResponse.EtcdCluster, "2.")
if !serverVersionOk || !clusterVersionOk {
return ErrSupportedVersion
}
return nil
}
func (c *Conn) Keys(name string) (kv map[string]string, err error) {
resp, err := c.do(path.Join("/v2", "keys", name))
if err != nil {
return nil, err
}
defer resp.Body.Close()
// var buf bytes.Buffer
var etcdResponse readResponse
// err = json.NewDecoder(io.TeeReader(resp.Body, &buf)).Decode(&etcdResponse)
err = json.NewDecoder(resp.Body).Decode(&etcdResponse)
if err != nil {
// c.log.Println("buffer contents", buf.String())
// defer buf.Reset()
return nil, err
}
kv = make(map[string]string)
for _, node := range etcdResponse.Node.Nodes {
key := strings.TrimPrefix(node.Key, "/"+name+"/")
kv[key] = node.Value
}
return kv, nil
}
func (c *Conn) do(path string) (*http.Response, error) {
req, err := newRequest(c._url, path)
if err != nil {
return nil, err
}
c.log.Println("Conn.do GET", req.URL)
return c.client.Do(req)
}
func newRequest(rawurl, path string) (*http.Request, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
u.Path = path
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
return req, nil
}
|
CREATE SEQUENCE flow_sample_id_seq
START WITH 9523
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE flow_sample_id_seq OWNER TO postgres;
--
-- TOC entry 350 (class 1259 OID 968286)
-- Name: census_flow_sample; Type: TABLE; Schema: import; Owner: postgres
--
CREATE TABLE census_flow_sample (
id integer DEFAULT nextval('flow_sample_id_seq'::regclass) NOT NULL,
source_oa character varying NOT NULL,
target_oa character varying NOT NULL,
source public.geometry(Point,27700),
target public.geometry(Point,27700),
flow public.geometry(LineString,27700),
source_node public.geometry(Point,27700),
target_node public.geometry(Point,27700),
source_description character varying,
target_description character varying,
walk_source_node public.geometry(Point,27700),
walk_target_node public.geometry(Point,27700),
cycle_source_node public.geometry(Point,27700),
cycle_target_node public.geometry(Point,27700),
car_source_node public.geometry(Point,27700),
car_target_node public.geometry(Point,27700)
);
ALTER TABLE census_flow_sample OWNER TO postgres; |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module GenericDerivedDefinition where
import Text.JSON
import Control.Lens
import AbstractStructure
import HardCoded
import Task
import SDKMonad
import SDKBase
import PropClasses
import ModelEngine
instance QixClass GenericDerivedDefinition where
getHandle (GenericDerivedDefinition (QixObject h _)) = h
|
import React from 'react'
import styled from 'styled-components'
import { navigate } from 'gatsby'
import { auth } from '../../firebase'
import { Button } from 'rebass'
const LogoutButton = () => (
<StyledLogoutButton
type="button"
onClick={() => {
auth.doSignOut().then(() => navigate(`/`))
}}
>
Sign Out
</StyledLogoutButton>
)
export default LogoutButton
const StyledLogoutButton = styled(Button)`
margin: 7.5px;
`
|
/*
File: MBCBoard.h
Contains: Fundamental move and board classes.
Copyright: � 2002-2012 by Apple Inc., all rights reserved.
IMPORTANT: This Apple software is supplied to you by Apple Computer,
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms,
and subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the
Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its
entirety and without modifications, you must retain this notice and
the following text and disclaimers in all such redistributions of the
Apple Software. Neither the name, trademarks, service marks or logos
of Apple Inc. may be used to endorse or promote products
derived from the Apple Software without specific prior written
permission from Apple. Except as expressly stated in this notice, no
other rights or licenses, express or implied, are granted by Apple
herein, including but not limited to any patent rights that may be
infringed by your derivative works or by other works in which the
Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT,
INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE,
HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING
NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <OpenGL/gl.h>
#import <Cocoa/Cocoa.h>
#import <stdio.h>
enum MBCVariant {
kVarNormal,
kVarCrazyhouse,
kVarSuicide,
kVarLosers
};
extern NSString * gVariantName[];
extern const char gVariantChar[];
enum MBCPlayers {
kHumanVsHuman,
kHumanVsComputer,
kComputerVsHuman,
kComputerVsComputer,
kHumanVsGameCenter,
};
enum MBCSideCode {
kPlayWhite,
kPlayBlack,
kPlayEither
};
enum MBCUniqueCode {
kMatchingPieceExists = 1,
kMatchingPieceOnSameRow = 2,
kMatchingPieceOnSameCol = 4,
};
typedef int MBCUnique;
enum MBCPieceCode {
EMPTY = 0,
KING, QUEEN, BISHOP, KNIGHT, ROOK, PAWN,
kWhitePiece = 0,
kBlackPiece = 8,
kPromoted = 16,
kPieceMoved = 32
};
typedef unsigned char MBCPiece;
inline MBCPiece White(MBCPieceCode code) { return kWhitePiece | code; }
inline MBCPiece Black(MBCPieceCode code) { return kBlackPiece | code; }
inline MBCPieceCode Piece(MBCPiece piece){ return (MBCPieceCode)(piece&7); }
inline MBCPieceCode Color(MBCPiece piece){ return (MBCPieceCode)(piece&8); }
inline MBCPieceCode What(MBCPiece piece) { return (MBCPieceCode)(piece&15);}
inline MBCPiece Matching(MBCPiece piece, MBCPieceCode code)
{ return (piece & 8) | code; }
inline MBCPiece Opposite(MBCPiece piece) { return piece ^ 8; }
inline MBCPieceCode Promoted(MBCPiece piece)
{ return (MBCPieceCode)(piece & 16); }
inline MBCPieceCode PieceMoved(MBCPiece piece)
{ return (MBCPieceCode)(piece & 32); }
enum MBCMoveCode {
kCmdNull,
kCmdMove, kCmdDrop, kCmdUndo,
kCmdWhiteWins, kCmdBlackWins, kCmdDraw,
kCmdPong, kCmdStartGame,
kCmdPMove, kCmdPDrop,
kCmdMoveOK
};
typedef unsigned char MBCSquare;
enum {
kSyntheticSquare = 0x70,
kWhitePromoSquare = 0x71,
kBlackPromoSquare = 0x72,
kBorderRegion = 0x73,
kInHandSquare = 0x80,
kInvalidSquare = 0xFF,
kSquareA8 = 56,
kBoardSquares = 64
};
inline unsigned Row(MBCSquare square)
{ return 1+(square>>3); }
inline char Col(MBCSquare square)
{ return 'a'+(square&7); }
inline MBCSquare Square(char col, unsigned row)
{ return ((row-1)<<3)|(col-'a'); }
inline MBCSquare Square(const char * colrow)
{ return ((colrow[1]-'1')<<3)|(colrow[0]-'a'); }
enum MBCCastling {
kUnknownCastle, kCastleQueenside, kCastleKingside, kNoCastle
};
enum MBCSide {
kWhiteSide, kBlackSide, kBothSides, kNeitherSide
};
inline bool SideIncludesWhite(MBCSide side) { return side==kWhiteSide || side==kBothSides; }
inline bool SideIncludesBlack(MBCSide side) { return side==kBlackSide || side==kBothSides; }
extern const MBCSide gHumanSide[];
extern const MBCSide gEngineSide[];
//
// A compact move has a very short existence and is only used in places
// where the information absolutely has to be kept to 32 bits.
//
typedef unsigned MBCCompactMove;
//
// MBCMove - A move
//
@interface MBCMove : NSObject
{
@public
MBCMoveCode fCommand; // Command
MBCSquare fFromSquare; // Starting square of piece if move
MBCSquare fToSquare; // Finishing square if move or drop
MBCPiece fPiece; // Moved or dropped piece
MBCPiece fPromotion; // Pawn promotion piece
MBCPiece fVictim; // Captured piece, set by [board makeMove]
MBCCastling fCastling; // Castling move, set by [board makeMove]
BOOL fEnPassant; // En passant, set by [board makeMove]
BOOL fCheck; // Check, set by [board makeMove]
BOOL fCheckMate; // Checkmate, set asynchronously
BOOL fAnimate; // Animate on board
}
- (id) initWithCommand:(MBCMoveCode)command;
+ (id) newWithCommand:(MBCMoveCode)command;
+ (id) moveWithCommand:(MBCMoveCode)command;
- (id) initFromCompactMove:(MBCCompactMove)move;
+ (id) newFromCompactMove:(MBCCompactMove)move;
+ (id) moveFromCompactMove:(MBCCompactMove)move;
- (id) initFromEngineMove:(NSString *)engineMove;
+ (id) newFromEngineMove:(NSString *)engineMove;
+ (id) moveFromEngineMove:(NSString *)engineMove;
+ (BOOL) compactMoveIsWin:(MBCCompactMove)move;
- (NSString *) localizedText;
- (NSString *) engineMove;
- (NSString *) origin;
- (NSString *) operation;
- (NSString *) destination;
- (NSString *) check;
@end
//
// MBCPieces - The full position representation
//
struct MBCPieces {
MBCPiece fBoard[64];
char fInHand[16];
MBCSquare fEnPassant; // Current en passant square, if any
bool NoPieces(MBCPieceCode color);
};
//
// MBCBoard - The game board
//
@interface MBCBoard : NSObject
{
MBCPieces fCurPos;
MBCPieces fPrvPos;
int fMoveClock;
MBCVariant fVariant;
NSMutableArray * fMoves;
MBCPiece fPromotion[2];
NSMutableArray * fObservers;
id fDocument;
}
- (void) removeChessObservers;
- (void) setDocument:(id)doc;
- (void) startGame:(MBCVariant)variant;
- (MBCPiece) curContents:(MBCSquare)square; // Read contents of a square
- (MBCPiece) oldContents:(MBCSquare)square; // Read contents of a square
- (int) curInHand:(MBCPiece)piece; // # of pieces to drop
- (int) oldInHand:(MBCPiece)piece; // # of pieces to drop
- (void) makeMove:(MBCMove *)move; // Move pieces and record
- (MBCCastling) tryCastling:(MBCMove *)move;
- (void) tryPromotion:(MBCMove *)move;
- (MBCSide) sideOfMove:(MBCMove *)move;
- (MBCUnique) disambiguateMove:(MBCMove *)move;
- (bool) undoMoves:(int)numMoves;
- (void) commitMove; // Save position
- (NSString *) fen; // Position in FEN notation
- (NSString *) holding; // Pieces held
- (NSString *) moves; // Moves in engine format
- (void) setFen:(NSString *)fen holding:(NSString *)holding
moves:(NSString *)moves;
- (BOOL) saveMovesTo:(FILE *)f;
- (BOOL) canPromote:(MBCSide)side;
- (BOOL) canUndo;
- (MBCMove *) lastMove;
- (int) numMoves;
- (MBCMove *) move:(int)index;
- (MBCPieces *) curPos;
- (MBCPiece) defaultPromotion:(BOOL)white;
- (void) setDefaultPromotion:(MBCPiece)piece for:(BOOL)white;
- (MBCMoveCode)outcome;
- (NSString *) stringFromMove:(MBCMove *)move withLocalization:(NSDictionary *)localization;
- (NSString *) extStringFromMove:(MBCMove *)move withLocalization:(NSDictionary *)localization;
@end
NSString * LocalizedString(NSDictionary * localization, NSString * key, NSString * fallback);
#define LOC(key, fallback) LocalizedString(localization, key, fallback)
// Local Variables:
// mode:ObjC
// End:
|
package org.bukkit;
import org.bukkit.permissions.ServerOperator;
public interface OfflinePlayer extends ServerOperator {
/**
* Checks if this player is currently online
*
* @return true if they are online
*/
public boolean isOnline();
/**
* Returns the name of this player
*
* @return Player name
*/
public String getName();
/**
* Checks if this player is banned or not
*
* @return true if banned, otherwise false
*/
public boolean isBanned();
/**
* Bans or unbans this player
*
* @param banned true if banned
*/
public void setBanned(boolean banned);
/**
* Checks if this player is whitelisted or not
*
* @return true if whitelisted
*/
public boolean isWhitelisted();
/**
* Sets if this player is whitelisted or not
*
* @param value true if whitelisted
*/
public void setWhitelisted(boolean value);
}
|
// Copyright (c) Microsoft. All rights reserved.
use std::collections::BTreeMap;
use std::str;
use docker::models::AuthConfig;
use failure::ResultExt;
use k8s_openapi::ByteString;
use crate::error::{ErrorKind, PullImageErrorReason, Result};
#[derive(Debug, PartialEq, Default)]
pub struct ImagePullSecret {
registry: Option<String>,
username: Option<String>,
password: Option<String>,
}
impl ImagePullSecret {
pub fn from_auth(auth: &AuthConfig) -> Option<Self> {
if let (None, None, None) = (auth.serveraddress(), auth.username(), auth.password()) {
None
} else {
Some(Self {
registry: auth.serveraddress().map(Into::into),
username: auth.username().map(Into::into),
password: auth.password().map(Into::into),
})
}
}
#[cfg(test)]
pub fn with_registry(mut self, registry: impl Into<String>) -> Self {
self.registry = Some(registry.into());
self
}
#[cfg(test)]
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = Some(username.into());
self
}
#[cfg(test)]
pub fn with_password(mut self, password: impl Into<String>) -> Self {
self.password = Some(password.into());
self
}
pub fn name(&self) -> Option<String> {
match (&self.username, &self.registry) {
(Some(user), Some(registry)) => Some(format!(
"{}-{}",
user.to_lowercase(),
registry.to_lowercase()
)),
_ => None,
}
}
pub fn data(&self) -> Result<ByteString> {
let registry = self
.registry
.as_ref()
.ok_or_else(|| ErrorKind::PullImage(PullImageErrorReason::AuthServerAddress))?;
let user = self
.username
.as_ref()
.ok_or_else(|| ErrorKind::PullImage(PullImageErrorReason::AuthUser))?;
let password = self
.password
.as_ref()
.ok_or_else(|| ErrorKind::PullImage(PullImageErrorReason::AuthPassword))?;
let mut auths = BTreeMap::new();
auths.insert(
registry.to_string(),
AuthEntry::new(user.to_string(), password.to_string()),
);
Auth::new(auths).secret_data()
}
}
// AuthEntry models the JSON string needed for entryies in the image pull secrets.
#[derive(Debug, serde_derive::Serialize, serde_derive::Deserialize, Clone)]
struct AuthEntry {
pub username: String,
pub password: String,
pub auth: String,
}
impl AuthEntry {
pub fn new(username: String, password: String) -> AuthEntry {
let auth = base64::encode(&format!("{}:{}", username, password));
AuthEntry {
username,
password,
auth,
}
}
}
// Auth represents the JSON string needed for image pull secrets.
// JSON struct is
// { "auths":
// {"<registry>" :
// { "username":"<user>",
// "password":"<password>",
// "email":"<email>" (not needed)
// "auth":"<base64 of '<user>:<password>'>"
// }
// }
// }
#[derive(Debug, serde_derive::Serialize, serde_derive::Deserialize, Clone)]
struct Auth {
pub auths: BTreeMap<String, AuthEntry>,
}
impl Auth {
pub fn new(auths: BTreeMap<String, AuthEntry>) -> Auth {
Auth { auths }
}
pub fn secret_data(&self) -> Result<ByteString> {
let data =
serde_json::to_vec(self).context(ErrorKind::PullImage(PullImageErrorReason::Json))?;
Ok(ByteString(data))
}
}
#[cfg(test)]
mod tests {
use docker::models::AuthConfig;
use serde_json::{json, Value};
use crate::error::PullImageErrorReason;
use crate::registry::ImagePullSecret;
use crate::ErrorKind;
#[test]
fn it_converts_to_image_pull_secret_none_when_all_data_missing() {
let auth = AuthConfig::new();
let image_pull_secret = ImagePullSecret::from_auth(&auth);
assert!(image_pull_secret.is_none());
}
#[test]
fn it_converts_to_image_pull_secret_some_if_any_data_exist() {
let auths = vec![
AuthConfig::new()
.with_username(String::from("USER"))
.with_serveraddress(String::from("REGISTRY")),
AuthConfig::new()
.with_password(String::from("a password"))
.with_serveraddress(String::from("REGISTRY")),
AuthConfig::new()
.with_password(String::from("a password"))
.with_username(String::from("USER")),
];
for auth in auths {
let image_pull_secret = ImagePullSecret::from_auth(&auth);
assert!(image_pull_secret.is_some());
}
}
#[test]
fn it_returns_some_secret_name() {
let image_pull_secret = ImagePullSecret::default()
.with_registry("REGISTRY")
.with_username("USER");
let name = image_pull_secret.name();
assert_eq!(name, Some("user-registry".to_string()));
}
#[test]
fn it_returns_none_secret_name_when_username_or_registry_missing() {
let image_pull_secrets = vec![
ImagePullSecret::default().with_registry("REGISTRY"),
ImagePullSecret::default().with_username("USER"),
ImagePullSecret::default(),
];
for image_pull_secret in image_pull_secrets {
let name = image_pull_secret.name();
assert_eq!(name, None);
}
}
#[test]
fn it_generates_secret_data() {
let image_pull_secret = ImagePullSecret::default()
.with_registry("REGISTRY")
.with_username("USER")
.with_password("PASSWORD");
let data = image_pull_secret.data();
let expected = json!({
"auths": {
"REGISTRY": {
"username":"USER",
"password":"PASSWORD",
"auth":"VVNFUjpQQVNTV09SRA=="
}
}
});
let actual: Value = serde_json::from_slice(data.unwrap().0.as_slice()).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn it_fails_to_generate_secret_data() {
let image_pull_secrets = vec![
(
ImagePullSecret::default(),
ErrorKind::PullImage(PullImageErrorReason::AuthServerAddress),
),
(
ImagePullSecret::default().with_registry("REGISTRY"),
ErrorKind::PullImage(PullImageErrorReason::AuthUser),
),
(
ImagePullSecret::default()
.with_registry("REGISTRY")
.with_username("USER"),
ErrorKind::PullImage(PullImageErrorReason::AuthPassword),
),
];
for (image_pull_secret, cause) in image_pull_secrets {
let data = image_pull_secret.data();
assert_eq!(data.unwrap_err().kind(), &cause);
}
}
}
|
import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?watchstadium\.com/live"
))
class Stadium(Plugin):
_policy_key_re = re.compile(r"""options:\s*\{.+policyKey:\s*"([^"]+)""", re.DOTALL)
_API_URL = (
"https://edge.api.brightcove.com/playback/v1/accounts/{data_account}/videos/{data_video_id}"
"?ad_config_id={data_ad_config_id}"
)
_PLAYER_URL = "https://players.brightcove.net/{data_account}/{data_player}_default/index.min.js"
_streams_schema = validate.Schema(
{
"tags": ["live"],
"sources": [
{
"src": validate.url(scheme="http"),
validate.optional("ext_x_version"): str,
"type": str,
}
],
},
validate.get("sources"),
)
def _get_streams(self):
res = self.session.http.get(self.url)
for tag in itertags(res.text, "video"):
if tag.attributes.get("id") == "brightcove_video_player":
data_video_id = tag.attributes.get("data-video-id")
data_account = tag.attributes.get("data-account")
data_ad_config_id = tag.attributes.get("data-ad-config-id")
data_player = tag.attributes.get("data-player")
url = self._PLAYER_URL.format(data_account=data_account, data_player=data_player)
res = self.session.http.get(url)
policy_key = self._policy_key_re.search(res.text).group(1)
headers = {
"Accept": "application/json;pk={0}".format(policy_key),
}
url = self._API_URL.format(
data_account=data_account, data_video_id=data_video_id, data_ad_config_id=data_ad_config_id
)
res = self.session.http.get(url, headers=headers)
streams = self.session.http.json(res, schema=self._streams_schema)
for stream in streams:
if stream["type"] == "application/x-mpegURL":
for s in HLSStream.parse_variant_playlist(self.session, stream["src"]).items():
yield s
else:
log.warning("Unexpected stream type: '{0}'".format(stream["type"]))
__plugin__ = Stadium
|
// Copyright (c) 2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.ledger.javaapi.data
import java.time.Instant
import java.util.{Optional => JOptional}
import java.util.concurrent.TimeUnit
import com.daml.ledger.javaapi.data.Generators._
import com.daml.ledger.api.v1.ValueOuterClass.Value.SumCase
import org.scalacheck.Gen
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec
class ValueSpec
extends AnyFlatSpec
with Matchers
with ScalaCheckDrivenPropertyChecks
with TableDrivenPropertyChecks {
implicit override val generatorDrivenConfig: PropertyCheckConfiguration =
PropertyCheckConfiguration(minSize = 1, sizeRange = 3)
"Value.fromProto" should "convert Protoc-generated instances to data instances" in forAll(
valueGen
) { value =>
Value.fromProto(value).toProto shouldEqual value
}
val conversions = Map[SumCase, (Value => JOptional[_], String)](
SumCase.BOOL -> (((_: Value).asBool(), "asBool")),
SumCase.CONTRACT_ID -> (((_: Value).asContractId(), "asContractId")),
SumCase.DATE -> (((_: Value).asDate(), "asDate")),
SumCase.NUMERIC -> (((_: Value).asNumeric(), "asNumeric")),
SumCase.INT64 -> (((_: Value).asInt64(), "asInt64")),
SumCase.LIST -> (((_: Value).asList(), "asList")),
SumCase.PARTY -> (((_: Value).asParty(), "asParty")),
SumCase.RECORD -> (((_: Value).asRecord(), "asRecord")),
SumCase.TEXT -> (((_: Value).asText(), "asText")),
SumCase.TIMESTAMP -> (((_: Value).asTimestamp(), "asTimestamp")),
SumCase.UNIT -> (((_: Value).asUnit(), "asUnit")),
SumCase.VARIANT -> (((_: Value).asVariant(), "asVariant")),
SumCase.OPTIONAL -> (((_: Value).asOptional(), "asOptional")),
SumCase.MAP -> (((_: Value).asTextMap(), "asTextMap")),
SumCase.GEN_MAP -> (((_: Value).asGenMap(), "asGenMap")),
)
def assertConversions[T <: Value](sumCase: SumCase, expected: T): scala.Unit = {
assertSuccessfulConversion(sumCase, expected)
assertUnsuccessfulConversions(expected, sumCase)
}
def assertSuccessfulConversion[T <: Value](sumCase: SumCase, expected: T): scala.Unit = {
val (conversion, name) = conversions(sumCase)
s"Value.$name()" should s" work on ${value.getClass.getSimpleName}} instances" in {
val converted = conversion(expected.asInstanceOf[Value])
withClue(s"expected: ${expected.toString} converted: ${converted.toString}") {
converted shouldEqual JOptional.of(expected)
}
}
}
def assertUnsuccessfulConversions(value: Value, excludedSumCase: SumCase): scala.Unit = {
for ((conversion, name) <- conversions.filterKeys(_ != excludedSumCase).values) {
s"Value.$name()" should s" should return Optional.empty() for ${value.getClass.getSimpleName} instances" in {
conversion(value) shouldEqual JOptional.empty()
}
}
}
assertConversions(SumCase.BOOL, Value.fromProto(boolValueGen.sample.get))
assertConversions(SumCase.CONTRACT_ID, Value.fromProto(contractIdValueGen.sample.get))
assertConversions(SumCase.DATE, Value.fromProto(dateValueGen.sample.get))
assertConversions(SumCase.NUMERIC, Value.fromProto(decimalValueGen.sample.get))
assertConversions(SumCase.INT64, Value.fromProto(int64ValueGen.sample.get))
assertConversions(SumCase.LIST, Value.fromProto(listValueGen.sample.get))
assertConversions(SumCase.PARTY, Value.fromProto(partyValueGen.sample.get))
assertConversions(SumCase.RECORD, Value.fromProto(recordValueGen.sample.get))
assertConversions(SumCase.TEXT, Value.fromProto(textValueGen.sample.get))
assertConversions(SumCase.TIMESTAMP, Value.fromProto(timestampValueGen.sample.get))
assertConversions(SumCase.UNIT, Value.fromProto(unitValueGen.sample.get))
assertConversions(SumCase.VARIANT, Value.fromProto(variantValueGen.sample.get))
assertConversions(SumCase.OPTIONAL, Value.fromProto(optionalValueGen.sample.get))
assertConversions(SumCase.MAP, Value.fromProto(textMapValueGen.sample.get))
assertConversions(SumCase.GEN_MAP, Value.fromProto(genMapValueGen.sample.get))
"Timestamp" should
"be constructed from Instant" in forAll(Gen.posNum[Long]) { micros =>
val expected = new Timestamp(micros)
val instant =
Instant.ofEpochSecond(TimeUnit.MICROSECONDS.toSeconds(micros), micros % 1000 * 1000)
val timestampFromInstant = Timestamp.fromInstant(instant)
expected shouldEqual timestampFromInstant
}
"Timestamp" should
"be constructed from millis" in forAll(Gen.posNum[Long]) { millis =>
val expected = new Timestamp(millis * 1000)
val timestampFromMillis = Timestamp.fromMillis(millis)
expected shouldEqual timestampFromMillis
}
}
|
C++***************************************************************
C Program PROFILE_MODSQ
C
C Simpler version of PROFILE_MODSQ, specially designed for
C computing profiles of angular sectors of a centered "modsq" (=power spectrum)
C
C This programme computes a profile along circular annuli.
C Discards stars and defects over n-sigma (n is chosen by the user)
C Possibility of computation within angular sectors or on complete annuli.
C Input parameters in a file (See PROFILE1.DOC for documentation
C Output profile stored with the input parameter file.
C Output checking file in "profile_plain.log"
C
C Unit 2 : Profile (Output)
C Unit 3 : profile_plain.log (Logfile)
C Unit 10 : Parameter input file
C
C JLP2000:
C Differences with PROFILE_PLAIN:
C Does not compute a mask
C
C Syntax:
C runs profile_modsq input_image 0.,0. output_profile
C or
C runs profile_modsq input_image phi_center,delta_phi output_profile
C
C JLP
C Version of 24-02-00
C--***************************************************************
PROGRAM PROFILE_MODSQ
LOGICAL MASK_OUT,SECTOR,MEDIAN,MULT_SECT
INTEGER NX,NY,NBINS,ITERMAX,IXMIN,IXMAX,IYMIN,IYMAX
REAL AXRATIO,PHI,X0,Y0,RADMIN1,RADMAX1,AMIN,AMAX
REAL XINCREM,FACT,SCALE,SKY,SIGREJEC,BADVALUE,RVMAG
REAL AXISMIN,AXISMAX,BB1,DD1,UU,VV,WW,DELTA_PHI
CHARACTER NAME1*40,NAMEPRO*40,NAMEPAR*40,COMMENTS1*160
CHARACTER MASK_NAME*40,MASK_COM*160
CHARACTER ANS*1
INTEGER*4 MADRID(1),PNTR_ARRAY,PNTR_MASK
COMMON /VMR/MADRID
10 FORMAT(A)
COMMON /PRF1_DATA/NX,NY,NAME1,COMMENTS1
COMMON /PRF1_OPTIONS/MASK_OUT,SECTOR,MEDIAN,MULT_SECT
COMMON /PRF1_PARAM/AXRATIO,PHI,X0,Y0,RADMIN1,RADMAX1,AMIN,AMAX,
1 XINCREM,FACT,SCALE,SKY,NBINS,SIGREJEC,BADVALUE,ITERMAX,RVMAG
COMMON /PRF1_UTILITIES/AXISMIN,AXISMAX,BB1,DD1,UU,VV,WW,
1 IXMIN,IXMAX,IYMIN,IYMAX
CALL JLP_BEGIN
C Writing the title :
WRITE(6,867)
867 FORMAT(' PROGRAM PROFILE_MODSQ TO COMPUTE PROFILES OF GALAXIES',
1 ' - VERSION OF 23/06/88 -',/)
C Output file with all the important details
OPEN(3,FILE='profile_plain.log',STATUS='unknown',
1 ACCESS='SEQUENTIAL',ERR=999)
WRITE(3,867)
C Prompting the format for the files :
CALL JLP_INQUIFMT
MASK_OUT=.FALSE.
C Input image
PRINT *,' Input image ?'
READ(5,10) NAME1
C**** Input of the image to process *****************
CALL JLP_VM_READIMAG(PNTR_ARRAY,NX,NY,NAME1,COMMENTS1)
WRITE(3,868)NAME1,NX,NY
868 FORMAT(' INPUT FILE : ',A,/,' NX, NY :',I4,2X,I4)
PRINT *,' Theta_center, Delta_Theta (0,0 if complete annuli) ?'
READ(5,*)PHI,DELTA_PHI
IF(PHI.EQ.0..AND.DELTA_PHI.EQ.0)THEN
PRINT *,'OK complete annuli'
SECTOR=.FALSE.
PHI=0.
AMIN=0.
AMAX=0.
ELSE
SECTOR=.TRUE.
AMIN=PHI-DELTA_PHI/2.
AMAX=PHI+DELTA_PHI/2.
PRINT *,'OK profile on sectors'
ENDIF
C Temprorary file with the input parameters
NAMEPAR='profile_modsq.par'
C Input of the simplest set of parameters:
C WARNING: SECTOR, PHI, AMIN, AMAX should be set
C in the common blocks before calling this routine!
CALL READ_PARAM_SIMPLEST(NAMEPAR)
C Ouput profile:
PRINT *,' Output profile name ?'
READ(5,10) NAMEPRO
C*********** General procedure ********
C Computes different coefficients which are used during all the following ;
CALL UTILITIES
C Computes the profile
CALL PROF1(MADRID(PNTR_ARRAY),NX)
C Output the results :
CALL OUTPUT_RESULTS(NAMEPAR,NAMEPRO)
CALL JLP_END
PRINT *,' Files created: "profile_plain.log" and "profile_modsq.par"'
STOP
999 PRINT *,' ERROR OPENING "profile_plain.log"'
STOP
END
C ******************************************************************
C Subroutine PROF1
C Computes the profile discarding the
C bad points (BADVALUE) and the stars and defects over n-sigma.
C Now, no longer used. But could be useful later. So I keep it.
C
C Meaning of the different arrays for the main loop on ITER (iterations):
C
C RADFIRST : Mean equivalent radius in arcseconds for the first iteration
C NBFIRST : pixel number in the first step (ITER=1)
C
C SIGMA : sigma computed in the previous iteration (ITER_1)
C MEAN : mean computed in the previous iteration (ITER-1)
C
C NBER : pixel number beeing computed in this iteration
C MAJAXIS : Semi-major axis in arcseconds beeing computed in this iteration
C SUM : sum being computed in the current iteration
C SUMSQ : sum of squares being computed in the current iteration
C
C Output:
C MEAN, SIGMA : for the last iteration
C
C*******************************************************************
SUBROUTINE PROF1(ARRAY,IDIM)
PARAMETER (IDIM1=2000)
REAL*4 ARRAY(IDIM,*)
REAL*8 SIG(IDIM1),MEAN(IDIM1),RADFIRST(IDIM1)
REAL*8 SUM(IDIM1),SUMSQ(IDIM1),MAJAXIS(IDIM1),SIGMA(IDIM1)
INTEGER*4 NBER(IDIM1),NBFIRST(IDIM1)
LOGICAL MASK_OUT,SECTOR,MEDIAN,MULT_SECT,NORMAL
CHARACTER NAME1*40,COMMENTS1*160
COMMON /PRF1_DATA/NX,NY,NAME1,COMMENTS1
COMMON /PRF1_OPTIONS/MASK_OUT,SECTOR,MEDIAN,
1 MULT_SECT
COMMON /PRF1_PARAM/AXRATIO,PHI,X0,Y0,RADMIN1,RADMAX1,AMIN,AMAX,
1 XINCREM,FACT,SCALE,SKY,NBINS,SIGREJEC,BADVALUE,ITERMAX,RVMAG
COMMON /PRF1_RESULTS/MEAN,SIGMA,NBER,RADFIRST,NBFIRST
COMMON /PRF1_UTILITIES/AXISMIN,AXISMAX,BB1,DD1,UU,VV,WW,
1 IXMIN,IXMAX,IYMIN,IYMAX
C Problem when boundaries around zero, so:
NORMAL=AMIN.LE.AMAX
C Initialization of the arrays (SIGMA and MEAN : of the previous iteration)
DO K=1,NBINS
SIGMA(K)=10000000.
MEAN(K)=0.D0
END DO
C **********************************************************************
C Main loop : (index=ITER) , to discard deviant points (over n-sigma)
C The image is scanned and when a value is discarded, it is set
C to BADVALUE, to avoid examining it on the next iterations.
C **********************************************************************
DO 200 ITER=1,ITERMAX
C Initialise the following arrays for the next step :
C SUMSQ : sum of squares of the current step
C NBER : pixel number of the current step
C SUM : sum of the current step
DO 201 K=1,NBINS
NBER(K)=0
SUMSQ(K)=0D0
SUM(K)=0D0
201 CONTINUE
DO 1 IY=IYMIN,IYMAX
Y1=FLOAT(IY)-Y0
DO 2 IX=IXMIN,IXMAX
C Discard the points equal to BADVALUE
IF(ARRAY(IX,IY).EQ.BADVALUE.AND.ITER.GT.1)GO TO 2
C Check if the pixel lies within the angular limits of the sector :
X1=FLOAT(IX)-X0
IF (SECTOR) THEN
CALL ANGLED(X1,Y1,APOINT)
IF(NORMAL)THEN
IF(APOINT.LT.AMIN.OR.APOINT.GT.AMAX)THEN
ARRAY(IX,IY)=BADVALUE
GO TO 2
ENDIF
ELSE
IF(APOINT.GT.AMAX.AND.APOINT.GT.AMIN)THEN
ARRAY(IX,IY)=BADVALUE
GO TO 2
ENDIF
ENDIF
ENDIF
C F2: Semi major axis of the ellipse containing the current pixel (in arcsec)
F2=SCALE*SQRT(UU*X1*X1+VV*Y1*Y1+WW*X1*Y1)
C KBIN : Index of the profile bin corresponding to the current pixel
C The law is such that the increment is increased of EPSILON
C at each step (Then the ratio of two successive increments
C is roughly FACT=1. + EPSILON since EPSILON is assumed to be small.
KBIN=1+INT(SQRT(BB1*BB1+DD1*(F2-AXISMIN))-BB1)
IF(KBIN.GE.1.AND.KBIN.LE.NBINS) THEN
SIG3=SIGREJEC*SIGMA(KBIN)
WORK=ABS(ARRAY(IX,IY)-MEAN(KBIN))
C Discard the points over (SIGREJEC*SIGMA)
IF(WORK.LE.SIG3)THEN
SUM(KBIN)=SUM(KBIN)+ARRAY(IX,IY)
SUMSQ(KBIN)=SUMSQ(KBIN)+ARRAY(IX,IY)*ARRAY(IX,IY)
NBER(KBIN)=NBER(KBIN)+1
MAJAXIS(KBIN)=MAJAXIS(KBIN)+F2
GO TO 2
ENDIF
ENDIF
ARRAY(IX,IY)=BADVALUE
2 CONTINUE
1 CONTINUE
C Reduce the value of NBINS if the arrays are too large.
C This accelerates the next iterations.
94 IF(NBER(NBINS).GT.2.OR.NBINS.LT.10) GOTO 95
NBINS=NBINS-1
GOTO 94
C Preparation for the next step :
95 DO 300 KL=1,NBINS
XNUMB=FLOAT(NBER(KL))
IF(XNUMB.EQ.0)THEN
MEAN(KL)=0.
SIGMA(KL)=10000000.
ELSEIF(XNUMB.LE.2)THEN
MEAN(KL)=SUM(KL)/XNUMB
SIGMA(KL)=10000000.
ELSE
MEAN(KL)=SUM(KL)/XNUMB
SIGMA(KL)=DSQRT((SUMSQ(KL)/XNUMB)-MEAN(KL)*MEAN(KL))
ENDIF
300 CONTINUE
C If First iteration, store the values of NBER and MAJAXIS :
IF(ITER.EQ.1)THEN
DO KL=1,NBINS
NBFIRST(KL)=NBER(KL)
IF(NBFIRST(KL).GT.0.)
1 RADFIRST(KL)=SQRT(AXRATIO)*MAJAXIS(KL)/FLOAT(NBER(KL))
END DO
ENDIF
200 CONTINUE
RETURN
END
C-----------------------------------------------------------------------
include 'jlpsub:profile_set.for'
|
'''
FastAPI Demo
Create the initial user
'''
from database.setup import session_local, engine
from database import models
from data_schemas import schemas
from utils.config_utils import get_config
from utils.user_utils import (
create_user,
set_user_admin
)
###############################################################################
CONFIG = get_config('initial_user.cfg')
INITIAL_USER_CONFIG = CONFIG['initial_user']
INITIAL_USER = schemas.UserCreate(
username=INITIAL_USER_CONFIG['username'],
first_name=INITIAL_USER_CONFIG['first_name'],
last_name=INITIAL_USER_CONFIG['last_name'],
email=INITIAL_USER_CONFIG['email'],
password=INITIAL_USER_CONFIG['password']
)
###############################################################################
def create_initial_user():
'''Create the initial user'''
session = session_local()
models.Base.metadata.create_all(bind=engine)
user = create_user(database=session, user=INITIAL_USER)
set_user_admin(database=session, user_id=user.user_id, admin=True)
###############################################################################
create_initial_user()
|
package me.jiho.fruitreactive.habits
import org.springframework.data.r2dbc.repository.Query
import org.springframework.data.r2dbc.repository.R2dbcRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.time.LocalDate
interface HabitExecutionDateRepository: R2dbcRepository<HabitExecutionDate, Long> {
fun findByHabitIdAndAccountIdAndDate(habitId: Long, accountId: Long, date: LocalDate): Mono<HabitExecutionDate>
fun findAllByHabitIdInAndDate(habitIds: List<Long?>, date: LocalDate): Flux<HabitExecutionDate>
} |
package actions
import (
"net/http"
)
func proxyHomeHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`"Welcome to The Athens Proxy"`))
}
|
import type { Observable } from 'rxjs';
// *****************************
// Misc Types
// *****************************
export type ControlId = string | symbol;
// Passing a whole `AbstractControl` to validator functions could create
// unexpected bugs in ControlDirectives if the control type changes in
// a way the developer didn't expect (e.g. from FormControl to FormGroup).
// Because validator services are now an option, I don't think it's necessary
// for ValidatorFn to receive the control. Instead they can just receive the
// rawValue and value.
export type ValidatorFn = (obj: {
rawValue: unknown;
value: unknown;
}) => ValidationErrors | null;
export interface ValidationErrors {
[key: string]: any;
}
// *****************************
// ControlEvent interfaces
// *****************************
export interface IControlEvent {
/** For debugging. Internal path this event took before being emitted. */
readonly debugPath: string;
/** The ControlId of the thing which originally created this event */
readonly source: ControlId;
/** The ControlId of the control which emitted this specific event */
readonly controlId: ControlId;
/** The type of event */
readonly type: string;
/** Custom metadata associated with this event */
readonly meta: { [key: string]: unknown };
/**
* If `true`, this event will not cause `AbstractControl#observe()` and
* `AbstractControl#observeChanges()` to emit. `AbstractControl#events`
* will still emit regardless.
*/
readonly noObserve?: boolean;
}
export interface IControlEventOptions {
/** For debugging. Internal path this event took before being emitted. */
debugPath?: string;
/** The ControlId of the thing which created this event */
source?: ControlId;
/** Allows attaching arbitrary metadata to a ControlEvent */
meta?: { [key: string]: unknown };
/** Prevents `observe` and `observeChanges` subscriptions from triggering */
noObserve?: boolean;
/**
* **ADVANCED USE ONLY**
*
* Prevents any ControlEvents from being emitted. The primary use case
* for this is if you are performing many small changes to a control
* that you want to manually bundle together into a single ControlEvent.
*/
[AbstractControl.NO_EVENT]?: boolean;
}
export interface IControlValidationEvent<RawValue, Value = RawValue>
extends IControlEvent {
readonly type: 'ValidationStart' | 'AsyncValidationStart';
readonly rawValue: RawValue;
readonly value: Value;
}
export interface IControlStateChangeEvent extends IControlEvent {
readonly type: 'StateChange';
readonly changes: { readonly [key: string]: unknown };
readonly childEvents?: { readonly [key: string]: IControlStateChangeEvent };
}
export interface IControlFocusEvent extends IControlEvent {
readonly type: 'Focus';
readonly focus: boolean;
}
export interface IControlNonStateChangeChildEvent extends IControlEvent {
readonly type: 'ChildEvent';
readonly childEvents: { readonly [key: string]: IControlEvent };
}
export interface IProcessedEvent<T extends IControlEvent = IControlEvent> {
readonly status: 'PROCESSED' | 'UNKNOWN';
readonly result?: T;
}
// *****************************
// AbstractControl interface
// *****************************
export namespace AbstractControl {
export const INTERFACE = Symbol('@@AbstractControlInterface');
// let _eventId = 0;
// export function eventId(
// /**
// * A passed value will reset the "current" eventId number.
// * Only intended for use in tests.
// */
// reset?: number
// ) {
// return (_eventId = reset ?? _eventId + 1);
// }
export function isControl(object?: unknown): object is AbstractControl {
return (
typeof object === 'object' &&
typeof (object as any)?.[AbstractControl.INTERFACE] === 'function' &&
(object as any)[AbstractControl.INTERFACE]() === object
);
}
/**
* If not undefined, this callback will be called whenever an AbstractControl
* `source` emits. It can be used for printing all control events to
* the console.
*/
export let debugCallback:
| undefined
| ((this: AbstractControl, event: IControlEvent) => void);
export const NO_EVENT = Symbol('NO_EVENT');
export const PUBLIC_PROPERTIES = [
// The order is important since it defines the order of the `replayState`
// changes. Here we establish the convension of placing derived properties
// before "real" properties.
'enabled',
'selfEnabled',
'disabled',
'selfDisabled',
'touched',
'selfTouched',
'dirty',
'selfDirty',
'readonly',
'selfReadonly',
'submitted',
'selfSubmitted',
'data',
'value',
'rawValue',
'validator',
'validatorStore',
'pending',
'selfPending',
'pendingStore',
'valid',
'selfValid',
'invalid',
'selfInvalid',
'status',
'errors',
'selfErrors',
'errorsStore',
'parent',
] as const;
/** **INTERNAL USE ONLY** */
export const _PUBLIC_PROPERTIES_INDEX = Object.fromEntries(
PUBLIC_PROPERTIES.map((p, i) => [p, i])
);
/**
* **INTERNAL USE ONLY**
*
* Contains the names of AbstractControl props which are
* ignored by the `_isEqual` function when comparing two
* AbstractControls.
*/
// tslint:disable-next-line: variable-name
export let _isEqual_AbstractControlPropExclusions = [
'events',
'_source',
'id',
'_parent',
'_validator',
];
/**
* **INTERNAL USE ONLY**
*
* This `isEqual` implementation returns `true` if two objects are deeply equal.
* You should not rely upon this implementation in your own applications or
* libraries. In the future, this function may be removed or it's implementation
* changed.
*/
// this `isEqual` implementation is adapted from the `fast-deep-equal` library
export function _isEqual<T>(a: T, b: T): boolean;
export function _isEqual(a: unknown, b: unknown): boolean;
export function _isEqual(a: any, b: any) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
let length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0; ) if (!_isEqual(a[i], b[i])) return false;
return true;
}
if (a instanceof Map && b instanceof Map) {
if (a.size !== b.size) return false;
for (i of a.entries()) if (!b.has(i[0])) return false;
for (i of a.entries()) if (!_isEqual(i[1], b.get(i[0]))) return false;
return true;
}
if (a instanceof Set && b instanceof Set) {
if (a.size !== b.size) return false;
for (i of a.entries()) if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = (a as any).length;
if (length != (b as any).length) return false;
for (i = length; i-- !== 0; )
if ((a as any)[i] !== (b as any)[i]) return false;
return true;
}
if (a.constructor === RegExp)
return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf)
return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString)
return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0; )
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
const isControl = AbstractControl.isControl(a);
for (i = length; i-- !== 0; ) {
var key = keys[i];
if (
!(
isControl && _isEqual_AbstractControlPropExclusions.includes(key)
) &&
!_isEqual(a[key], b[key])
) {
return false;
}
}
return true;
}
// true if both NaN, false otherwise
return a !== a && b !== b;
}
}
export interface AbstractControl<RawValue = any, Data = any, Value = RawValue> {
/**
* The ID is used to determine where StateChanges originated,
* and to ensure that a given AbstractControl only processes
* values one time.
*/
readonly id: ControlId;
data: Data;
/** An observable of all events for this AbstractControl */
events: Observable<
IControlEvent | (IControlEvent & { [key: string]: unknown })
>;
/**
* The value of the AbstractControl. This is an alias for `rawValue`.
*/
readonly value: Value;
/** The value of the AbstractControl. */
readonly rawValue: RawValue;
/**
* `true` if this control is not disabled, false otherwise.
* This is an alias for `selfEnabled`.
*/
readonly enabled: boolean;
/** `true` if this control is not disabled, false otherwise. */
readonly selfEnabled: boolean;
/**
* `true` if this control is disabled, false otherwise.
* This is an alias for `selfDisabled`.
*/
readonly disabled: boolean;
/** `true` if this control is disabled, false otherwise. */
readonly selfDisabled: boolean;
/**
* `true` if this control is touched, false otherwise.
* This is an alias for `selfTouched`.
*/
readonly touched: boolean;
/** `true` if this control is touched, false otherwise. */
readonly selfTouched: boolean;
/**
* `true` if this control is dirty, false otherwise.
* This is an alias for `selfDirty`.
*/
readonly dirty: boolean;
/** `true` if this control is dirty, false otherwise. */
readonly selfDirty: boolean;
/**
* `true` if this control is readonly, false otherwise.
* This is an alias for `selfReadonly`.
*/
readonly readonly: boolean;
/** `true` if this control is readonly, false otherwise. */
readonly selfReadonly: boolean;
/**
* `true` if this control is submitted, false otherwise.
* This is an alias for `selfSubmitted`.
*/
readonly submitted: boolean;
/** `true` if this control is submitted, false otherwise. */
readonly selfSubmitted: boolean;
/**
* Contains a `ValidationErrors` object if this control
* has any errors. Otherwise contains `null`.
*
* An alias for `selfErrors`.
*/
readonly errors: ValidationErrors | null;
/**
* Contains a `ValidationErrors` object if this control
* has any errors. Otherwise contains `null`.
*/
readonly selfErrors: ValidationErrors | null;
readonly errorsStore: ReadonlyMap<ControlId, ValidationErrors>;
readonly validator: ValidatorFn | null;
readonly validatorStore: ReadonlyMap<ControlId, ValidatorFn>;
/**
* `true` if this control is pending, false otherwise.
* This is an alias for `selfPending`.
*/
readonly pending: boolean;
/** `true` if this control is pending, false otherwise. */
readonly selfPending: boolean;
readonly pendingStore: ReadonlySet<ControlId>;
/**
* `true` if `selfErrors` is `null`, `false` otherwise.
* This is an alias for `selfValid`.
*/
readonly valid: boolean;
/** `true` if `selfErrors` is `null`, `false` otherwise. */
readonly selfValid: boolean;
/**
* `true` if `selfErrors` contains errors, `false` otherwise.
* This is an alias for `selfInvalid`.
*/
readonly invalid: boolean;
/** `true` if `selfErrors` contains errors, `false` otherwise. */
readonly selfInvalid: boolean;
readonly status: 'DISABLED' | 'PENDING' | 'VALID' | 'INVALID';
readonly parent: AbstractControl | null;
[AbstractControl.INTERFACE](): this;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H],
J extends keyof this[A][B][C][D][E][F][G][H][I],
K extends keyof this[A][B][C][D][E][F][G][H][I][J]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I][J][K] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H],
J extends keyof this[A][B][C][D][E][F][G][H][I]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I][J] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
options?: { ignoreNoEmit?: boolean }
): Observable<this[A][B][C][D][E] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C]
>(
a: A,
b: B,
c: C,
d: D,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D] | undefined>;
observe<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B]
>(
a: A,
b: B,
c: C,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C] | undefined>;
observe<A extends keyof this, B extends keyof this[A]>(
a: A,
b: B,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B] | undefined>;
observe<A extends keyof this>(
a: A,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A]>;
observe<T = any>(
props: string[],
options?: { ignoreNoObserve?: boolean }
): Observable<T>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H],
J extends keyof this[A][B][C][D][E][F][G][H][I],
K extends keyof this[A][B][C][D][E][F][G][H][I][J]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
k: K,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I][J][K] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H],
J extends keyof this[A][B][C][D][E][F][G][H][I]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
j: J,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I][J] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G],
I extends keyof this[A][B][C][D][E][F][G][H]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
i: I,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H][I] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F],
H extends keyof this[A][B][C][D][E][F][G]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
h: H,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G][H] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E],
G extends keyof this[A][B][C][D][E][F]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
g: G,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F][G] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D],
F extends keyof this[A][B][C][D][E]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
f: F,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E][F] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C],
E extends keyof this[A][B][C][D]
>(
a: A,
b: B,
c: C,
d: D,
e: E,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D][E] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B],
D extends keyof this[A][B][C]
>(
a: A,
b: B,
c: C,
d: D,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C][D] | undefined>;
observeChanges<
A extends keyof this,
B extends keyof this[A],
C extends keyof this[A][B]
>(
a: A,
b: B,
c: C,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B][C] | undefined>;
observeChanges<A extends keyof this, B extends keyof this[A]>(
a: A,
b: B,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A][B] | undefined>;
observeChanges<A extends keyof this>(
a: A,
options?: { ignoreNoObserve?: boolean }
): Observable<this[A]>;
observeChanges<T = any>(
props: string[],
options?: { ignoreNoObserve?: boolean }
): Observable<T>;
setValue(value: RawValue, options?: IControlEventOptions): string[];
/**
* If provided a `ValidationErrors` object or `null`, replaces the errors
* associated with the source ID.
*
* If provided a `Map` object containing `ValidationErrors` keyed to source IDs,
* uses it to replace the `errorsStore` associated with this control.
*/
setErrors(
value: ValidationErrors | null | ReadonlyMap<ControlId, ValidationErrors>,
options?: IControlEventOptions
): string[];
/**
* If provided a `ValidationErrors` object, that object is merged with the
* existing errors associated with the source ID. If the error object has
* properties = `null`, errors associated with those keys are deleted
* from the `errorsStore`.
*
* If provided a `Map` object containing `ValidationErrors` keyed to source IDs,
* that object is merged with the existing `errorsStore`.
*/
patchErrors(
value: ValidationErrors | ReadonlyMap<ControlId, ValidationErrors>,
options?: IControlEventOptions
): string[];
markTouched(value: boolean, options?: IControlEventOptions): string[];
markDirty(value: boolean, options?: IControlEventOptions): string[];
markReadonly(value: boolean, options?: IControlEventOptions): string[];
markDisabled(value: boolean, options?: IControlEventOptions): string[];
markSubmitted(value: boolean, options?: IControlEventOptions): string[];
markPending(
value: boolean | ReadonlySet<ControlId>,
options?: IControlEventOptions
): string[];
setValidators(
value:
| ValidatorFn
| ValidatorFn[]
| ReadonlyMap<ControlId, ValidatorFn>
| null,
options?: IControlEventOptions
): string[];
/**
* Unlike other AbstractControl properties, the `data` property can be set directly.
* i.e. `control.data = newValue`.
*
* As an alternative to setting data this way,
* you can use `setData()` which uses the standard ControlEvent API and emits a `data`
* StateChange that can be observed. Data values are compared with strict equality
* (`===`). If it doesn't look like the data has changed, the event will be ignored.
*/
setData(data: Data, options?: IControlEventOptions): string[];
focus(value?: boolean, options?: Omit<IControlEventOptions, 'noEmit'>): void;
/**
* Returns an observable of this control's state in the form of
* StateChange objects which can be used to make another control
* identical to this one. This observable will complete upon
* replaying the necessary state changes.
*/
replayState(options?: IControlEventOptions): Observable<IControlEvent>;
/**
* Returns a new AbstractControl which is identical to this one except
* for the `id` and `parent` properties.
*/
clone(options?: IControlEventOptions): AbstractControl<RawValue, Data, Value>;
processEvent<T extends IControlEvent>(
event: T,
options?: IControlEventOptions
): IProcessedEvent<T>;
/**
* *INTERNAL USE*
*
* Sets the `parent` property of an AbstractControl. Generally,
* you shouldn't use this directly. The parent will be automatically
* set when you add or remove a control from an AbstractControlContainer.
*/
_setParent(
parent: AbstractControl | null,
options?: IControlEventOptions
): string[];
// /**
// * A convenience method for emitting an arbitrary control event.
// *
// * @returns the `eventId` of the emitted event
// */
// emitEvent<T extends IControlEvent = IControlEvent & { [key: string]: any }>(
// event: Partial<Pick<T, 'source' | 'noEmit' | 'meta'>> &
// Omit<T, 'source' | 'noEmit' | 'meta'> & {
// type: string;
// },
// options?: IControlEventOptions
// ): void;
}
|
use core::future::Future;
/// Random-number Generator
pub trait Rng {
type Error;
type RngFuture<'a>: Future<Output = Result<(), Self::Error>> + 'a
where
Self: 'a;
/// Completely fill the provided buffer with random bytes.
///
/// May result in delays if entropy is exhausted prior to completely
/// filling the buffer. Upon completion, the buffer will be completely
/// filled or an error will have been reported.
fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a>;
}
|
#[derive(Debug, PartialEq, Clone)]
pub enum Loc {
File {
filename: String,
line: i32,
pos: i32,
},
Unknown,
}
|
package models;
import play.data.validation.Constraints;
public class Post {
@Constraints.Required
public String subject;
public String tags;
@Constraints.Required
public String body;
}
|
package com.twtims.mapboxdemo.label
import android.animation.ArgbEvaluator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.twtims.mapboxdemo.R
import android.animation.ValueAnimator
import android.graphics.Color
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.CircleLayer
import com.mapbox.mapboxsdk.style.layers.FillLayer
import com.mapbox.mapboxsdk.style.layers.Property
import com.mapbox.mapboxsdk.style.layers.PropertyFactory
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import kotlinx.android.synthetic.main.activity_pulsing_layer_opacity_color.*
import java.io.IOException
import java.nio.charset.Charset
class PulsingLayerOpacityColorActivity : AppCompatActivity() {
private var parkColorAnimator: ValueAnimator? = null
private var hotelColorAnimator: ValueAnimator? = null
private var attractionsColorAnimator: ValueAnimator? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pulsing_layer_opacity_color)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.LIGHT) { style->
val hotelSource = GeoJsonSource("hotels", loadJsonFromAsset("la_hotels.geojson"))
style.addSource(hotelSource)
val hotelLayer = FillLayer("hotels", "hotels").withProperties(
PropertyFactory.fillColor(Color.parseColor("#5a9fcf")),
PropertyFactory.visibility(Property.NONE)
)
style.addLayer(hotelLayer)
val hotels = style.getLayer("hotels") as FillLayer?
hotelColorAnimator = ValueAnimator.ofObject(
ArgbEvaluator(),
Color.parseColor("#5a9fcf"),
Color.parseColor("#2c6b97")
)
hotelColorAnimator?.apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
addUpdateListener { animator ->
hotels?.setProperties(PropertyFactory.fillColor(animator.animatedValue as Int))
}
}
val attractionsSource =
GeoJsonSource("attractions", loadJsonFromAsset("la_attractions.geojson"))
style.addSource(attractionsSource)
val attractionsLayer = CircleLayer("attractions", "attractions").withProperties(
PropertyFactory.circleColor(Color.parseColor("#5a9fcf")),
PropertyFactory.visibility(Property.NONE)
)
style.addLayer(attractionsLayer)
val attractions = style.getLayer("attractions") as CircleLayer?
attractionsColorAnimator = ValueAnimator.ofObject(
ArgbEvaluator(),
Color.parseColor("#ec8a8a"),
Color.parseColor("#de3232")
)
attractionsColorAnimator?.apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
addUpdateListener { animator ->
attractions?.setProperties(
PropertyFactory.circleColor(animator.animatedValue as Int)
)
}
}
val parks = style.getLayer("landuse") as FillLayer?
parks?.setProperties(PropertyFactory.visibility(Property.NONE))
parkColorAnimator = ValueAnimator.ofObject(
ArgbEvaluator(),
Color.parseColor("#7ac79c"),
Color.parseColor("#419a68")
)
parkColorAnimator?.apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
addUpdateListener { animator ->
parks?.setProperties(
PropertyFactory.fillColor(animator.animatedValue as Int)
)
}
}
fab_toggle_hotels.setOnClickListener {
setLayerVisible("hotels", style)
}
fab_toggle_parks.setOnClickListener{
setLayerVisible("landuse", style)
}
fab_toggle_attractions.setOnClickListener {
setLayerVisible("attractions", style)
}
parkColorAnimator?.start()
hotelColorAnimator?.start()
attractionsColorAnimator?.start()
}
}
}
private fun setLayerVisible(layerId: String, style: Style) {
val layer = style.getLayer(layerId);
layer?.let {
if (Property.VISIBLE == layer.visibility.value){
layer.setProperties(PropertyFactory.visibility(Property.NONE))
}else{
layer.setProperties(PropertyFactory.visibility(Property.VISIBLE))
}
}
}
private fun loadJsonFromAsset(fileName: String): String? {
return try {
val inputStream = assets.open(fileName)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
String(buffer, Charset.forName("utf-8"))
} catch (e: IOException) {
e.printStackTrace()
null
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
public override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
}
|
namespace alg_13_Enums
{
//public enum Spol {
//Muski,
//Zenski
//}
internal class Osoba
{
private string ime;
private Spol spol;
public Osoba(string ime)
{
this.ime = ime;
this.spol = Spol.Zenski;
}
public Osoba(string ime, Spol s)
{
this.ime = ime;
this.spol = s;
}
public override string ToString()
{
return "Ime: " + this.ime + " A spol je:" + this.spol;
}
}
} |
# 条件运算
a = 10
if (a is 10):
print('a等于10')
elif(a is 20):
print('a 等于10')
else:
print('a不等于10')
b = 66
if(b <= 60):
print('b<=60,真实值为:',b)
elif(b<=70):
print('b<=70,真实值为:',b)
elif(b<=80):
print('b<=80,真实值为:',b)
elif(b<=90):
print('b<=90,真实值为:',b)
else:
print('91-100,真实值为:',b)
|
# Ticker-Token ICO
## Deploying
### Local deployment
Truffle console:
(Truffle v5.3.5)
`$ truffle console`
`truffle(development)> TickerTokenSale.deployed().then((i)=>{tokenSale = i})`
`truffle(development)> TickerToken.deployed().then((i)=>{token = i})`
`truffle(development)> tokensAvailable = 7500`
`truffle(development)> admin = accounts[0]`
`truffle(development)> token.transfer(tokenSale.address, tokensAvailable, {from:admin})`
`truffle(development)> token.balanceOf(tokenSale.address)`
### Rinkeby Test Network deployment
`geth --rinkeby --rpc --rpcapi="personal,eth,network,web3,net" --ipcpath="~/library/Ethereum/geth.ipc"`
To create a new account:
`geth --rinkeby account new`
|
{-|
Module : FRP.AST.Reflect
Description : Reflecting FRP-Types into the Haskell type-system
-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE QuasiQuotes #-}
module FRP.AST.Reflect (
Ty(..)
, Sing(..)
, FRP(..)
, reifySing
, typeToSingExp
) where
import Language.Haskell.TH ( Exp (..), ExpQ, Lit (..), Pat (..), Q
, DecQ, mkName, runQ)
import FRP.AST
import FRP.AST.Construct
import qualified Language.Haskell.TH as T
import Data.Data
-- -----------------------------------------------------------------------------
-- Ty
-- -----------------------------------------------------------------------------
-- | The type of FRP-types that can be reflected
data Ty
= TUnit
| TNat
| TBool
| TAlloc
| Ty :*: Ty
| Ty :+: Ty
| Ty :->: Ty
| TStream Ty
deriving (Show, Eq, Typeable, Data)
infixr 0 :->:
infixr 6 :*:
infixr 5 :+:
-- -----------------------------------------------------------------------------
-- Sing
-- -----------------------------------------------------------------------------
-- |Singleton representation to lift Ty into types
-- using kind-promotion
data Sing :: Ty -> * where
SNat :: Sing TNat
SUnit :: Sing TUnit
SBool :: Sing TBool
SAlloc :: Sing TAlloc
SProd :: Sing t1 -> Sing t2 -> Sing (t1 :*: t2)
SSum :: Sing t1 -> Sing t2 -> Sing (t1 :+: t2)
SArr :: Sing t1 -> Sing t2 -> Sing (t1 :->: t2)
SStream :: Sing t -> Sing (TStream t)
deriving instance Eq (Sing a)
deriving instance Show (Sing a)
deriving instance Typeable (Sing a)
-- |Reify a singleton back into an FRP type
reifySing :: Sing t -> Type ()
reifySing = \case
SNat -> tynat
SUnit -> tyunit
SBool -> tybool
SAlloc -> tyalloc
SProd t1 t2 -> reifySing t1 .*. reifySing t2
SSum t1 t2 -> reifySing t1 .+. reifySing t2
SArr t1 t2 -> reifySing t1 |-> reifySing t2
SStream t -> reifySing t
infixr 9 `SArr`
-- -----------------------------------------------------------------------------
-- FRP
-- -----------------------------------------------------------------------------
-- |An FRP program of a type, executed in an environment
data FRP :: Ty -> * where
FRP :: Env -> Term () -> Sing t -> FRP t
deriving instance Typeable (FRP t)
deriving instance Show (FRP t)
-- |Use template haskell to generate a singleton value that represents
-- an FRP type
typeToSingExp :: Type a -> ExpQ
typeToSingExp typ = case typ of
TyPrim _ TyNat -> T.conE 'SNat
TyPrim _ TyBool -> T.conE 'SBool
TyPrim _ TyUnit -> T.conE 'SUnit
TyAlloc _ -> T.conE 'SAlloc
TySum _ t1 t2 ->
let e1 = typeToSingExp t1
e2 = typeToSingExp t2
in T.conE 'SSum `T.appE` e1 `T.appE` e2
TyProd _ t1 t2 ->
let e1 = typeToSingExp t1
e2 = typeToSingExp t2
in runQ [| SProd $(e1) $(e2) |]
TyArr _ t1 t2 ->
let e1 = typeToSingExp t1
e2 = typeToSingExp t2
in runQ [| SArr $(e1) $(e2) |]
TyStream _ t ->
let e = typeToSingExp t
in runQ [| SStream $(e) |]
TyStable _ t -> typeToSingExp t
TyLater _ t -> typeToSingExp t
TyVar _ _ -> fail "FRP types must be fully instantiated when marshalled"
TyRec _ _ _ -> fail "Recursive types are not supported"
|
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Selection } from "prosemirror-state";
import Chromeless from "@atlaskit/editor-core/dist/es5/ui/Appearance/Chromeless";
import EditorContext from "@atlaskit/editor-core/dist/es5/ui/EditorContext";
import { PortalProvider, PortalRenderer } from "@atlaskit/editor-core/dist/es5/ui/PortalProvider";
import { moveCursorToTheEnd } from "@atlaskit/editor-core/dist/es5/utils";
import { ProviderFactory } from "@atlaskit/editor-common";
import ReactEditorView from "@atlaskit/editor-core/dist/es5/create-editor/ReactEditorView";
import actionsPlugin from "./plugins/actions";
import imagesPlugin from "./plugins/images";
const EditorStylesWrapper = styled.div`
flex-grow: 1;
overflow-y: scroll;
overflow-x: hidden;
height: 100%;
position: relative;
display: flex;
flex-direction: column;
padding-bottom: 8px;
box-sizing: border-box;
& > div {
flex: 1;
padding: 8px 28px 0;
& > div {
height: 100%;
}
}
.ProseMirror {
height: 100%;
table {
width: 100%;
margin-left: 0;
margin-right: 0;
}
img {
display: block;
max-width: 100%;
}
}
`;
class ReactEditor extends ReactEditorView {
getPlugins() {
return super
.getPlugins({ allowLists: true, allowCodeBlocks: true })
.concat([imagesPlugin, actionsPlugin]);
}
}
export default class Editor extends React.Component {
static contextTypes = {
editorActions: PropTypes.object
};
state = { editor: {} };
constructor(props) {
super(props);
this.providerFactory = new ProviderFactory();
}
onEditorCreated = editor => {
this.registerEditorForActions(editor);
if (!editor.view.hasFocus()) {
editor.view.focus();
}
if (this.props.selection) {
const selection = Selection.fromJSON(editor.view.state.doc, this.props.selection);
const tr = editor.view.state.tr.setSelection(selection);
editor.view.dispatch(tr.scrollIntoView());
}
};
onEditorDestroyed = () => {
this.unregisterEditorFromActions();
};
registerEditorForActions(editor) {
if (this.context && this.context.editorActions) {
this.context.editorActions._privateRegisterEditor(
editor.view,
editor.eventDispatcher,
editor.contentTransformer
);
}
}
unregisterEditorFromActions() {
if (this.context && this.context.editorActions) {
this.context.editorActions._privateUnregisterEditor();
}
}
render() {
const { editor } = this.state;
const { editorView, contentComponents, eventDispatcher } = editor;
return (
<EditorStylesWrapper>
<EditorContext editorActions={this.editorActions}>
<PortalProvider
render={portalProviderAPI => (
<React.Fragment>
<ReactEditor
editorProps={{
defaultValue: this.props.defaultValue
}}
portalProviderAPI={portalProviderAPI}
providerFactory={this.providerFactory}
onEditorCreated={this.onEditorCreated}
onEditorDestroyed={this.onEditorDestroyed}
render={({ editor, view, eventDispatcher, config }) => (
<Chromeless
editorDOMElement={editor}
editorView={view}
providerFactory={this.providerFactory}
eventDispatcher={eventDispatcher}
popupsMountPoint={this.props.popupsMountPoint}
popupsBoundariesElement={document.body}
contentComponents={config.contentComponents}
/>
)}
/>
<PortalRenderer portalProviderAPI={portalProviderAPI} />
</React.Fragment>
)}
/>
</EditorContext>
</EditorStylesWrapper>
);
}
}
|
importScripts('./ngsw-worker.js');
(function () {
'use strict';
self.addEventListener('notificationclick', (event) => {
console.log("This is custom service worker notificationclick method.");
console.log('Notification details: ', event.notification);
// Write the code to open
if (clients.openWindow && event.notification.data.url) {
event.waitUntil(clients.openWindow(event.notification.data.url));
}
});}
());
|
# MenuTitle: Remove Hints
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from GlyphsApp import Glyphs, TOPGHOST, STEM, BOTTOMGHOST
__doc__ = """
Remove PostScript hints in selected glyphs
"""
ps_hints = [
TOPGHOST,
STEM,
BOTTOMGHOST,
]
Glyphs.font.disableUpdateInterface()
for l in Glyphs.font.selectedLayers:
g = l.parent
for layer in g.layers:
delete = []
for i, hint in enumerate(layer.hints):
if hint.isPostScript and hint.type in ps_hints:
delete.append(i)
if delete:
for i in reversed(delete):
del layer.hints[i]
Glyphs.font.enableUpdateInterface()
|
<?php
namespace App\Imports;
use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\Hash;
use Auth;
use App\Department;
use App\Designation;
use App\UserProfile;
use Carbon\Carbon;
use DateTime;
class UsersImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
if (Department::where('name', '=', $row['department'])->count() > 0) {
$department = Department::where('name', '=', $row['department'])->first();
}
else
{
$department = new Department;
$department->name = $row['department'];
$department->save();
}
if (Designation::where('name', '=', $row['designation'])->count() > 0) {
$designation = Designation::where('name', '=', $row['designation'])->first();
}
else
{
$designation = new Designation;
$designation->name = $row['designation'];
$designation->save();
}
$user = new User;
$user->department_id = $department->id;
$user->designation_id = $designation->id;
$user->name = $row['name'];
$user->last_name = $row['lastname'];
$user->middle_name = $row['middlename'];
$user->email = $row['email'];
$user->password = Hash::make(123);
$user->role = $row['role'];
$user->status = $row['status'];
$user->save();
$user_profile = new UserProfile;
$user_profile->user_id = $user->id;
$user_profile->phone = $row['phone'];
$user_profile->address_1 = $row['address1'];
$user_profile->address_2 = $row['address2'];
$user_profile->city = $row['city'];
$user_profile->state = $row['state'];
$user_profile->country = $row['country'];
$user_profile->gender = $row['gender'];
$user_profile->management_level = $row['managementlevel'];
$user_profile->save();
}
}
|
import React from 'react';
import Radium from 'radium';
import MdLanguage from 'react-icons/lib/md/language';
import MdArrowDropDown from 'react-icons/lib/md/arrow-drop_down';
import MdCheck from 'react-icons/lib/md/check';
import { Lang } from 'i18n/lang';
@Lang
@Radium
class LanguageSwitcher extends React.Component {
componentDidMount() {
// Since bind() will wrap onClickOutside, we need a proper ref
// to the wrapped function to efectively remove the listener on unmount.
this.bindedFunction = this.onClickOutside.bind(this);
window.addEventListener('click', this.bindedFunction, false);
}
componentWillUnmount() {
window.removeEventListener('click', this.bindedFunction);
}
switchLanguage(locale, event) {
event.stopPropagation();
window.L.setLocale(locale);
window.L.processQueue();
}
onClickOutside(event) {
this.setState({ ...this.state, dropdownActive: false });
}
onTogglerClick(event) {
event.stopPropagation();
this.setState({ ...this.state, dropdownActive: !this.state.dropdownActive });
}
onMouseLeave() {
this.setState({ ...this.state, dropdownActive: false });
}
render() {
var dropdown = this.state.dropdownActive ?
<ul style={ styles.dropdown } onMouseLeave={ this.onMouseLeave.bind(this) }>
<li style={ styles.dropdownOption }>
<button key={ 1 } style={ styles.languageButton } onClick={ this.switchLanguage.bind(this, 'en') }>
English
{
this.props.currentLocale == 'en' ?
<span style={ styles.check }><MdCheck /></span>
: null
}
</button>
</li>
<li style={ styles.dropdownOption }>
<button key={ 2 } style={ styles.languageButton } onClick={ this.switchLanguage.bind(this, 'de') }>
Deutsch
{
this.props.currentLocale == 'de' ?
<span style={ styles.check }><MdCheck /></span>
: null
}
</button>
</li>
<li style={ styles.dropdownOption }>
<button key={ 3 } style={ styles.languageButton } onClick={ this.switchLanguage.bind(this, 'es') }>
Spanish
{
this.props.currentLocale == 'es' ?
<span style={ styles.check }><MdCheck /></span>
: null
}
</button>
</li>
</ul>
: null;
return (
<div style={ styles.languageSwitcher }>
<button onClick={ this.onTogglerClick.bind(this) } style={ styles.toggler }>
<MdLanguage />
<span style={ styles.togglerText }>{ window.L.t('Language') }</span>
<MdArrowDropDown />
</button>
{ dropdown }
</div>
);
}
}
const styles = {
languageSwitcher: {
'float': 'right',
position: 'relative'
},
languageButton: {
margin: '0px',
borderBottom: '1px solid #ccc',
borderRight: 'none',
borderTop: 'none',
borderLeft: 'none',
background: '#f0f0f0',
padding: '0 10px',
display: 'block',
textAlign: 'left',
width: '120px',
cursor: 'pointer',
height: '50px',
lineHeight: '50px',
outline: 'none',
':hover': {
background: '#fff'
}
},
toggler: {
borderLeft: '1px solid rgba(255,255,255,.4)',
borderRight: 'none',
borderTop: 'none',
borderBottom: 'none',
color: 'white',
height: '50px',
lineHeight: '50px',
padding: '0 10px',
fontSize: '12pt',
background: 'none',
outline: 'none',
cursor: 'pointer'
},
togglerText: {
padding: '0 20px 0 10px'
},
dropdown: {
position: 'absolute',
right: '20px',
top: '50px',
zIndex: '99999',
borderLeft: '1px solid #ddd',
borderRight: '1px solid #ddd'
},
check: {
color: "#0A0",
'float': 'right'
}
}
export default LanguageSwitcher;
|
---
title: Lambda関数へのREST APIの接続
description: REST API をLambda 関数に接続する方法
---
このガイドでは、REST APIを既存のLambda関数に接続する方法を学びます。
始めるには、新しいAPIを作成してください。
```sh
amplify add api
? Please select from one of the below mentioned services: REST
? Provide a friendly name for your resource to be used as a label for this category in the project: myapi
? Provide a path (e.g., /book/{isbn}): /hello
? Choose a Lambda source: Use a Lambda function already added in the current Amplify project
? Choose the Lambda function to invoke by this path: <your-function-name>
? Restrict API access: N
? Do you want to add another path: N
```
APIのデプロイ:
```sh
push を増幅する
```
APIを使用できるようになりました!
クライアント側アプリケーションからAPIを操作する方法の詳細については、こちらのドキュメント [をご覧ください](~/lib/restapi/getting-started.md) |
package com.zbiljic.resterror;
import com.zbiljic.resterror.http.HttpStatus;
/**
* Factory for creating {@link RestError} instances.
*
* @author Nemanja Zbiljic
*/
public abstract class RestErrorFactory {
/**
* Returns new builder for creating a {@code RestError} instance.
*
* @return A builder for creating a {@code RestError} instance.
*/
public static RestErrorBuilder builder() {
return new RestErrorBuilder();
}
/**
* Returns new builder for creating a {@code RestError} instance based on existing {@code
* RestError} instance.
*
* @return A builder for creating a {@code RestError} instance based on existing {@code RestError}
* instance.
*/
public static RestErrorBuilder builderCopyOf(RestError error) {
return new RestErrorBuilder()
.withStatus(error.getStatus())
.withCode(error.getCode())
.withMessage(error.getMessage())
.withDeveloperMessage(error.getDeveloperMessage())
.withMoreInfoUrl(error.getMoreInfo());
}
/**
* Creates new generic {@code RestError} for the specified HTTP status.
*
* @param status The desired HTTP status.
* @return Generic RestError for specified HTTP status.
* @see <a href="http://httpstatus.es/">http://httpstatus.es/</a>
*/
public static RestError valueOf(final HttpStatus status) {
return GenericRestError.create(status).build();
}
/**
* Creates new generic {@code RestError} for the specified HTTP status with custom message.
*
* @param status The desired HTTP status.
* @param message The custom message for the error.
* @return Generic RestError for specified http status and message.
* @see <a href="http://httpstatus.es/">http://httpstatus.es/</a>
*/
public static RestError valueOf(final HttpStatus status, final String message) {
return GenericRestError.create(status).withMessage(message).build();
}
}
|
"""
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import json
from cfnlint.rules import Match
class BaseFormatter(object):
"""Base Formatter class"""
def _format(self, match):
"""Format the specific match"""
def print_matches(self, matches):
"""Output all the matches"""
if not matches:
return None
# Output each match on a separate line by default
output = []
for match in matches:
output.append(self._format(match))
return '\n'.join(output)
class Formatter(BaseFormatter):
"""Generic Formatter"""
def _format(self, match):
"""Format output"""
formatstr = u'{0} {1}\n{2}:{3}:{4}\n'
return formatstr.format(
match.rule.id,
match.message,
match.filename,
match.linenumber,
match.columnnumber
)
class JsonFormatter(BaseFormatter):
"""Json Formatter"""
class CustomEncoder(json.JSONEncoder):
"""Custom Encoding for the Match Object"""
# pylint: disable=E0202
def default(self, o):
if isinstance(o, Match):
if o.rule.id[0] == 'W':
level = 'Warning'
elif o.rule.id[0] == 'I':
level = 'Informational'
else:
level = 'Error'
return {
'Rule': {
'Id': o.rule.id,
'Description': o.rule.description,
'ShortDescription': o.rule.shortdesc,
'Source': o.rule.source_url
},
'Location': {
'Start': {
'ColumnNumber': o.columnnumber,
'LineNumber': o.linenumber,
},
'End': {
'ColumnNumber': o.columnnumberend,
'LineNumber': o.linenumberend,
},
'Path': getattr(o, 'path', None),
},
'Level': level,
'Message': o.message,
'Filename': o.filename,
}
return {'__{}__'.format(o.__class__.__name__): o.__dict__}
def print_matches(self, matches):
# JSON formatter outputs a single JSON object
return json.dumps(
matches, indent=4, cls=self.CustomEncoder,
sort_keys=True, separators=(',', ': '))
class QuietFormatter(BaseFormatter):
"""Quiet Formatter"""
def _format(self, match):
"""Format output"""
formatstr = u'{0} {1}:{2}'
return formatstr.format(
match.rule,
match.filename,
match.linenumber
)
class ParseableFormatter(BaseFormatter):
"""Parseable Formatter"""
def _format(self, match):
"""Format output"""
formatstr = u'{0}:{1}:{2}:{3}:{4}:{5}:{6}'
return formatstr.format(
match.filename,
match.linenumber,
match.columnnumber,
match.linenumberend,
match.columnnumberend,
match.rule.id,
match.message
)
|
-- Insert with duplicate policy (psycopg2)
INSERT INTO ohlcvs VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (exchange, base_id, quote_id, "time") DO NOTHING;
-- Execute prepared INSERT statement (psycopg2)
EXECUTE ohlcvs_rows_insert_stmt(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
-- Delete duplicate rows
delete from ohlcvs oh
where exists (
select 1 from ohlcvs
where exchange = oh.exchange and base_id = oh.base_id
and quote_id = oh.quote_id and "time" = oh."time"
and ohlcvs.ctid > oh.ctid
);
-- Insert with duplicate policy (psycopg2)
INSERT INTO symbol_exchange VALUES (%s,%s,%s,%s)
ON CONFLICT (exchange, base_id, quote_id) DO NOTHING;
|
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.goto
import com.intellij.ide.actions.SearchEverywhereClassifier
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import java.awt.Component
import javax.swing.JList
class KotlinSearchEverywhereClassifier : SearchEverywhereClassifier {
override fun isClass(o: Any?) = o is KtClassOrObject
override fun isSymbol(o: Any?) = o is KtNamedDeclaration
override fun getVirtualFile(o: Any) = (o as? PsiElement)?.containingFile?.virtualFile
override fun getListCellRendererComponent(
list: JList<*>,
value: Any?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean
): Component? {
val declaration = (value as? PsiElement)?.unwrapped as? KtNamedDeclaration ?: return null
return KotlinSearchEverywherePsiRenderer(list).getListCellRendererComponent(list, declaration, index, isSelected, isSelected)
}
} |
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SeiyuuMoe.Domain.ValueObjects;
namespace SeiyuuMoe.Infrastructure.Database.Converters
{
public class MalIdConverter : ValueConverter<MalId, long>
{
public MalIdConverter(ConverterMappingHints mappingHints = null)
: base(
id => id.Value,
value => new MalId(value),
mappingHints
)
{ }
}
} |
package org.consumersunion.stories.server.api.rest.mapper;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.consumersunion.stories.common.shared.dto.ErrorApiResponse;
import org.consumersunion.stories.server.exception.NotLoggedInException;
import org.springframework.stereotype.Component;
@Provider
@Component
public class NotLoggedInExceptionMapper implements ExceptionMapper<NotLoggedInException> {
private static final Logger LOGGER = Logger.getLogger(NotLoggedInExceptionMapper.class.getName());
@Override
public Response toResponse(NotLoggedInException exception) {
LOGGER.log(Level.SEVERE, exception.getMessage(), exception);
return Response.status(Status.UNAUTHORIZED)
.entity(new ErrorApiResponse(exception.getMessage()))
.build();
}
}
|
### 关系扩展
#sql("EDbRel")
select
#if(fields)
#(fields)
#else
*
#end
from #(tableName) where 1=1
### 判断是否是map类型
#if(JpaKit.isList(params))
#for(param : params)
and #(param) = ?
#end
#if(appendSql)
#(appendSql)
#end
#if(limit)
limit #(limit)
#end
#if(offset)
offset #(offset)
#end
#end
#end
|
using Volo.CmsKit.Entities;
namespace Volo.CmsKit.Comments;
public static class CommentConsts
{
public const string EntityType = "Comment";
public static int MaxEntityTypeLength { get; set; } = CmsEntityConsts.MaxEntityTypeLength;
public static int MaxEntityIdLength { get; set; } = CmsEntityConsts.MaxEntityIdLength;
public static int MaxTextLength { get; set; } = 512;
}
|
//
// PadTorch.cpp
// MNNConverter
//
// Created by MNN on 2021/08/11.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include <stdio.h>
#include "torchOpConverter.hpp"
DECLARE_OP_CONVERTER(PadTorch);
MNN::OpType PadTorch::opType() {
return MNN::OpType_Extra;
}
MNN::OpParameter PadTorch::type() {
return MNN::OpParameter_Extra;
}
std::vector<int> PadTorch::inputTensorIdx() {
return {-1};
}
void PadTorch::run(MNN::OpT* dstOp, const torch::jit::Node* node, TorchScope* scope) {
auto extra = new MNN::ExtraT;
dstOp->main.value = extra;
extra->engine = "Torch";
extra->type = "pad";
extra->attr.resize(1);
extra->attr[0].reset(new MNN::AttributeT);
extra->attr[0]->key = "mode";
std::string opType = getRealOpType(node);
if (opType.find("constant") != std::string::npos) {
extra->attr[0]->s = "constant";
} else if (opType.find("reflection") != std::string::npos) {
extra->attr[0]->s = "reflect";
}
}
REGISTER_CONVERTER(PadTorch, constant_pad_nd);
REGISTER_CONVERTER(PadTorch, reflection_pad1d);
REGISTER_CONVERTER(PadTorch, reflection_pad2d);
|
package static_example;
class SuperClass{
public void staticMethod(){
System.out.println("SuperClass: inside staticMethod");
}
}
class SubClass extends SuperClass{
//overriding the static method
public void staticMethod(){
System.out.println("SubClass: inside staticMethod");
}
}
public class TestSuperClass {
public static void main(String[] args) {
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
}
}
|
module Deserializer
module Attribute
autoload :Base, "deserializer/attribute/base"
autoload :Association, "deserializer/attribute/association"
autoload :Attribute, "deserializer/attribute/attribute"
autoload :HasManyAssociation, "deserializer/attribute/has_many_association"
autoload :HasOneAssociation, "deserializer/attribute/has_one_association"
autoload :NestedAssociation, "deserializer/attribute/nested_association"
autoload :ValueAttribute, "deserializer/attribute/value_attribute"
end
end |
using Innovator.Client.Model;
using Innovator.Client.QueryModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Innovator.Client.QueryModel.Tests
{
[TestClass]
public class AmlSearchTests
{
[TestMethod]
public void SimpleSearchMode()
{
var parser = new SimpleSearchParser();
var prop = (IPropertyDefinition)ElementFactory.Local.FromXml("<Item type='Property'><name>name</name></Item>").AssertItem();
var query = new QueryItem(ElementFactory.Local.LocalizationContext);
query.AddCondition(prop, "*|short*", parser);
if (query.Where is OrOperator orOp)
{
Assert.IsTrue(orOp.Left is LikeOperator);
Assert.IsTrue(orOp.Right is LikeOperator);
}
else
{
Assert.Fail();
}
query = new QueryItem(ElementFactory.Local.LocalizationContext);
query.AddCondition(prop, @"\*\|sh\ort*", parser);
if (query.Where is LikeOperator likeOp
&& likeOp.Right is PatternList pat)
{
Assert.AreEqual(1, pat.Patterns.Count);
Assert.AreEqual(1, pat.Patterns[0].Matches.Count);
var strMatch = pat.Patterns[0].Matches[0] as StringMatch;
Assert.IsNotNull(strMatch);
Assert.AreEqual("|short", strMatch.Match.ToString());
}
else
{
Assert.Fail();
}
}
}
}
|
require "lightrail/wrapper/associations"
module Lightrail
module Wrapper
class Model
class_attribute :associations
self.associations = []
class << self
def inherited(base)
base.class_eval do
alias_method wrapped_class.model_name.underscore, :resource
end
end
def around_association(collection, scope)
yield
end
# Declares that this object is associated to the given association
# with cardinality 1..1.
def has_one(*associations)
options = associations.extract_options!
self.associations += associations.map { |a| Associations::HasOneConfig.new(a, options) }
define_association_methods(associations)
end
# Declares that this object is associated to the given association
# with cardinality 1..*.
def has_many(*associations)
options = associations.extract_options!
self.associations += associations.map { |a| Associations::HasManyConfig.new(a, options) }
define_association_methods(associations)
end
# Based on the declared associations and the given parameters,
# generate an includes clause that can be passed down to the relation
# object to avoid doing N+1 queries.
def valid_includes(includes)
result = []
includes.each do |i|
if association = associations.find { |a| a.includes == i }
result << association.name
end
end
result
end
# Returns the original class wrapped by this wrapper.
def wrapped_class
@wrapped_class ||= name.sub(/Wrapper$/, "").constantize
end
private
def define_association_methods(associations)
associations.each do |association|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{association}
@resource.#{association}
end
RUBY
end
end
end
attr_reader :resource, :scope
def initialize(resource, scope)
@resource = resource
@scope = scope
end
def view
raise NotImplementedError, "No view implemented for #{self}"
end
# Gets the view and render the associated object.
def render(options={}, result=Result.new)
name = options[:as] || wrapped_model_name.underscore
result[name] = view = self.view
_include_associations(result, view, options[:include])
end
# Gets the view and render the associated considering it is part of a collection.
def render_many(options={}, result=Result.new)
name = options[:as] || wrapped_model_name.plural
view = self.view
array = (result[name] ||= []) << view
_include_associations(result, view, options[:include])
end
private
def _include_associations(result, view, includes)
return result if includes.blank?
associations = result.associations
self.class.associations.each do |config|
next unless includes.include?(config.includes)
object = send(config.name)
config.update(view, object)
associations[config.as].concat Array.wrap(object)
end
result
end
def wrapped_model_name
self.class.wrapped_class.model_name
end
end
end
end
|
//-----------------------------------------------------------------------
// <copyright company="Nuclei">
// Copyright 2013 Nuclei. Licensed under the Apache License, Version 2.0.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Reactive.Testing;
using Moq;
using Nuclei.Communication.Protocol.Messages;
using Nuclei.Communication.Protocol.Messages.Processors;
using Nuclei.Diagnostics;
using NUnit.Framework;
namespace Nuclei.Communication.Protocol
{
[TestFixture]
[SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented",
Justification = "Unit tests do not need documentation.")]
public sealed class MessageHandlerTest
{
[Test]
public void ForwardResponse()
{
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
var endpoint = new EndpointId("sendingEndpoint");
var messageId = new MessageId();
var timeout = TimeSpan.FromSeconds(30);
var task = handler.ForwardResponse(endpoint, messageId, timeout);
Assert.IsFalse(task.IsCompleted);
var msg = new SuccessMessage(endpoint, messageId);
handler.ProcessMessage(msg);
task.Wait();
Assert.IsTrue(task.IsCompleted);
Assert.AreSame(msg, task.Result);
}
[Test]
public void ForwardResponseWithMessageReceiveTimeout()
{
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var scheduler = new TestScheduler();
var handler = new MessageHandler(store.Object, systemDiagnostics, scheduler);
var endpoint = new EndpointId("sendingEndpoint");
var messageId = new MessageId();
var timeout = TimeSpan.FromSeconds(30);
var task = handler.ForwardResponse(endpoint, messageId, timeout);
Assert.IsFalse(task.IsCompleted);
Assert.IsFalse(task.IsCanceled);
scheduler.Start();
Assert.Throws<AggregateException>(task.Wait);
Assert.IsTrue(task.IsCompleted);
Assert.IsFalse(task.IsCanceled);
Assert.IsTrue(task.IsFaulted);
}
[Test]
public void ForwardResponseWithDisconnectingEndpoint()
{
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
var endpoint = new EndpointId("sendingEndpoint");
var messageId = new MessageId();
var timeout = TimeSpan.FromSeconds(30);
var task = handler.ForwardResponse(endpoint, messageId, timeout);
Assert.IsFalse(task.IsCompleted);
Assert.IsFalse(task.IsCanceled);
handler.OnEndpointSignedOff(endpoint);
Assert.Throws<AggregateException>(task.Wait);
Assert.IsTrue(task.IsCompleted);
Assert.IsTrue(task.IsCanceled);
}
[Test]
public void ActOnArrivalWithMessageFromNonBlockedSender()
{
ICommunicationMessage storedMessage = null;
var processAction = new Mock<IMessageProcessAction>();
{
processAction.Setup(p => p.Invoke(It.IsAny<ICommunicationMessage>()))
.Callback<ICommunicationMessage>(m => { storedMessage = m; });
}
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(true);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
handler.ActOnArrival(new MessageKindFilter(typeof(SuccessMessage)), processAction.Object);
var endpoint = new EndpointId("sendingEndpoint");
var msg = new SuccessMessage(endpoint, MessageId.None);
handler.ProcessMessage(msg);
Assert.AreSame(msg, storedMessage);
}
[Test]
public void ActOnArrivalWithMessageFromBlockedSender()
{
ICommunicationMessage storedMessage = null;
var processAction = new Mock<IMessageProcessAction>();
{
processAction.Setup(p => p.Invoke(It.IsAny<ICommunicationMessage>()))
.Callback<ICommunicationMessage>(m => { storedMessage = m; });
}
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
handler.ActOnArrival(new MessageKindFilter(typeof(SuccessMessage)), processAction.Object);
var endpoint = new EndpointId("sendingEndpoint");
var msg = new SuccessMessage(endpoint, new MessageId());
handler.ProcessMessage(msg);
Assert.IsNull(storedMessage);
}
[Test]
public void ActOnArrivalWithHandshakeMessage()
{
ICommunicationMessage storedMessage = null;
var processAction = new Mock<IMessageProcessAction>();
{
processAction.Setup(p => p.Invoke(It.IsAny<ICommunicationMessage>()))
.Callback<ICommunicationMessage>(m => { storedMessage = m; });
}
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
handler.ActOnArrival(new MessageKindFilter(typeof(EndpointConnectMessage)), processAction.Object);
var endpoint = new EndpointId("sendingEndpoint");
var msg = new EndpointConnectMessage(
endpoint,
new DiscoveryInformation(new Uri("http://localhost/discovery/invalid")),
new ProtocolInformation(
new Version(),
new Uri(@"net.pipe://localhost/test"),
new Uri(@"net.pipe://localhost/test/data")),
new ProtocolDescription(new List<CommunicationSubject>()));
handler.ProcessMessage(msg);
Assert.AreSame(msg, storedMessage);
}
[Test]
public void ActOnArrivalWithLastChanceHandler()
{
var localEndpoint = new EndpointId("id");
ICommunicationMessage storedMsg = null;
SendMessage sendAction =
(e, m, r) =>
{
storedMsg = m;
};
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var processAction = new UnknownMessageTypeProcessAction(localEndpoint, sendAction, systemDiagnostics);
var handler = new MessageHandler(store.Object, systemDiagnostics);
handler.ActOnArrival(new MessageKindFilter(processAction.MessageTypeToProcess), processAction);
var endpoint = new EndpointId("sendingEndpoint");
var msg = new EndpointConnectMessage(
endpoint,
new DiscoveryInformation(new Uri("http://localhost/discovery/invalid")),
new ProtocolInformation(
new Version(),
new Uri(@"net.pipe://localhost/test"),
new Uri(@"net.pipe://localhost/test/data")),
new ProtocolDescription(new List<CommunicationSubject>()));
handler.ProcessMessage(msg);
Assert.IsInstanceOf<FailureMessage>(storedMsg);
}
[Test]
public void OnLocalChannelClosed()
{
var store = new Mock<IStoreInformationAboutEndpoints>();
{
store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny<EndpointId>()))
.Returns(false);
}
var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
var handler = new MessageHandler(store.Object, systemDiagnostics);
var endpoint = new EndpointId("sendingEndpoint");
var messageId = new MessageId();
var timeout = TimeSpan.FromSeconds(30);
var task = handler.ForwardResponse(endpoint, messageId, timeout);
Assert.IsFalse(task.IsCompleted);
Assert.IsFalse(task.IsCanceled);
handler.OnLocalChannelClosed();
Assert.Throws<AggregateException>(task.Wait);
Assert.IsTrue(task.IsCompleted);
Assert.IsTrue(task.IsCanceled);
}
}
}
|
#!/usr/bin/python
# Copyright (C) 2013 Technische Universitaet Muenchen
# This file is part of the SG++ project. For conditions of distribution and
# use, please see the copyright notice at http://www5.in.tum.de/SGpp
#
"""
@file ParameterBuilder.py
@author Fabian Franzelin <[email protected]>
@date Thu Sep 5 13:27:19 2013
@brief Fluent interface for parameter specification
@version 0.1
"""
from pysgpp.extensions.datadriven.uq.dists import Corr
from ParameterDescriptor import (UncertainParameterDesciptor,
DeterministicParameterDescriptor)
from ParameterSet import ParameterSet
class ParameterBuilder(object):
"""
Deterministic and uncertain parameter builder class
"""
def __init__(self):
self.__id = 0
self.__uncertainParams = UncertainParameterBuilder(self)
self.__deterministicParams = DeterministicParameterBuilder(self)
def defineUncertainParameters(self):
return self.__uncertainParams
def defineDeterministicParameters(self):
return self.__deterministicParams
def getId(self):
ans = self.__id
self.__id += 1
return ans
def andGetResult(self):
ans = ParameterSet(self.__id)
ans.addParams(self.__uncertainParams.andGetResult())
ans.addParams(self.__deterministicParams.andGetResult())
return ans
class GeneralParameterBuilder(object):
"""
General builder class for both, a list of uncertain and
deterministic parameters
"""
def __init__(self, builder):
self._builder = builder
self.__n = 0
self._params = {}
def getDescriptor(self):
raise NotImplementedError()
def __getId(self):
if self._builder:
ix = self._builder.getId()
elif len(self._params) == 0:
ix = 0
else:
ix = max(self._params.keys()) + 1
self.__n = ix + 1
return ix
def new(self):
descriptor = self.getDescriptor()
ix = self.__getId()
self._params[ix] = descriptor
return descriptor
def andGetResult(self):
ans = ParameterSet(self.__n)
correlated = []
# insert uncorrelated variables
for newkey, builder in self._params.items():
newparam = builder.andGetResult()
correlations = builder.getCorrelations()
if newparam.isUncertain() and \
correlations is not None:
correlated.append((newkey, builder))
else:
ans.addParam(newkey, newparam)
# insert correlated variables
for newkey, builder in correlated:
found = False
newparam = builder.andGetResult()
for key, param in ans.items():
if param.getName() == correlations:
# build correlated random variable
names = [param.getName(), newparam.getName()]
dist = Corr([param.getDistribution(),
newparam.getDistribution()])
# set new distribution and new names
newparam.setDistribution(dist)
newparam.setName(names)
# replace old parameter by new parameter
ans.replaceParam(key, newparam)
found = True
if not found:
raise AttributeError('the parameter "%s" was not found but is \
required by "%s"' %
(builder.correlatedTo,
newparam.getName()))
return ans
class DeterministicParameterBuilder(GeneralParameterBuilder):
"""
Deterministic parameter builder
"""
def __init__(self, builder=None):
super(DeterministicParameterBuilder, self).__init__(builder)
def getDescriptor(self):
return DeterministicParameterDescriptor()
class UncertainParameterBuilder(GeneralParameterBuilder):
"""
Uncertain parameter builder
"""
def __init__(self, builder=None):
super(UncertainParameterBuilder, self).__init__(builder)
def getDescriptor(self):
return UncertainParameterDesciptor()
|
<?php
/*
* This file is part of Mannequin.
*
* (c) 2017 Last Call Media, Rob Bayliss <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace LastCall\Mannequin\Core\Console;
use LastCall\Mannequin\Core\Config\ConfigLoader;
use LastCall\Mannequin\Core\Console\Helper\StartHelper;
use LastCall\Mannequin\Core\Mannequin;
use LastCall\Mannequin\Core\Version;
use Symfony\Component\Console\Application as ConsoleApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
class Application extends ConsoleApplication
{
private $autoloadPath;
public function __construct(string $autoloadPath)
{
$this->autoloadPath = $autoloadPath;
parent::__construct('Mannequin', Version::id());
}
protected function getDefaultHelperSet()
{
$set = parent::getDefaultHelperSet();
$set->set(new StartHelper($this->autoloadPath));
return $set;
}
protected function getDefaultInputDefinition()
{
$definition = parent::getDefaultInputDefinition();
$definition->addOption(
new InputOption(
'config',
'c',
InputOption::VALUE_OPTIONAL,
'Path to the configuration file',
'.mannequin.php'
)
);
$definition->addOption(
new InputOption(
'debug',
'd',
InputOption::VALUE_NONE,
'Enable debug mode'
)
);
return $definition;
}
/**
* Override the default commands to hide the list command by default.
*/
protected function getDefaultCommands()
{
$commands = parent::getDefaultCommands();
foreach ($commands as $command) {
if ('list' === $command->getName()) {
if (method_exists($commands, 'setHidden')) {
$command->setHidden(true);
} elseif (method_exists($command, 'setPrivate')) {
$commands->setPrivate(true);
}
}
}
return $commands;
}
public function doRun(InputInterface $input, OutputInterface $output)
{
$configFile = $input->getParameterOption(['--config', '-c'], '.mannequin.php');
$debug = $input->getParameterOption(['--debug', '-d'], false);
$config = ConfigLoader::load($configFile);
$this->getHelperSet()->get('start')->setConfigFile($configFile);
$mannequin = new Mannequin($config, [
'debug' => $debug,
'logger' => new ConsoleLogger($output),
'config_file' => $configFile,
'autoload_file' => $this->autoloadPath,
]);
$this->setDispatcher($mannequin['dispatcher']);
$mannequin->boot();
$this->addCommands($mannequin['commands']);
parent::doRun($input, $output);
}
}
|
def test_movie_awards(ia):
movie = ia.get_movie('0133093', info=['awards'])
awards = movie.get('awards', [])
assert len(awards) > 80
|
import React from 'react';
import './FilterCard.css';
import Input from '../Input/Input';
interface FilterCardProps {
onUpdate: Function;
title: string;
children: JSX.Element
}
function FilterCard({ onUpdate, title, children }: FilterCardProps): JSX.Element {
const onInputChange = (name: string, value: string): void => {
onUpdate(name, value);
};
return (
<div className="filterCard">
<div className="filterCard_checkbox">
<Input onUpdate={onInputChange} name={title} type="checkbox" />
</div>
<p className="filterCard_title">{title}</p>
{children}
</div>
);
}
export default FilterCard;
|
#include "soft_uart.h"
int main() {
uart_init();
uart_puts("\nBooted from flash.\n");
uart_puts("Hello, world from C!\n");
}
|
#define SYSFS_GPIO_DIR "/sys/class/gpio"
// #define POLL_TIMEOUT (3 * 1000) /* 3 seconds */
#define MAX_BUF 100
int gpio_export(unsigned int gpio);
int gpio_set_dir(unsigned int gpio, unsigned int out_flag);
|
# require 'test_helper'
#
# class Admin::ProgrammesControllerTest < ActionController::TestCase
#
# setup do
# panopticon_has_metadata(
# "id" => "12345",
# "name" => "Test",
# "slug" => "test"
# )
# login_as_stub_user
# @programme = ProgrammeEdition.create(title: "test", slug: "test", panopticon_id: 12345)
# end
#
# test "programmes index redirects to root" do
# get :index
# assert_response :redirect
# assert_redirected_to(:controller => "root", "action" => "index")
# end
#
# test "requesting a publication that doesn't exist returns a 404" do
# get :show, :id => '4e663834e2ba80480a0000e6'
# assert_response 404
# end
#
# test "we can view a programme" do
# get :show, :id => @programme.id
# assert_response :success
# assert_not_nil assigns(:programme)
# end
#
# test "destroy programme" do
# assert @programme.can_destroy?
# assert_difference('ProgrammeEdition.count', -1) do
# delete :destroy, :id => @programme.id
# end
# assert_redirected_to(:controller => "root", "action" => "index")
# end
#
# test "can't destroy published programme" do
# @programme.state = 'ready'
# @programme.save!
# @programme.publish
# @programme.save!
# assert @programme.published?
# assert [email protected]_destroy?
#
# assert_difference('ProgrammeEdition.count', 0) do
# delete :destroy, :id => @programme.id
# end
# end
#
# end
|
---
title: 怎么查看git仓库当前的分支、最后一次commitId、tag等
date: 2020-05-06 18:34:57
layout: post
author: "Heropoo"
categories:
- Git
tags:
- Git
excerpt: "最近想把项目的git仓库版本作为项目版本来使用,就研究了下,做点笔记"
---
最近想把项目的git仓库版本作为项目版本来使用,就研究了下,做点笔记。
## 查看当前分支名称
```sh
git symbolic-ref --short -q HEAD
# 输出 master
```
## 查看当前最后一次提交的commit_id
```sh
git log -1 --pretty=format:%H # 完整的
# 输出 7b6b2803d2b7135b239d062847816e55a810371e
git log -1 --pretty=format:%h # 前7位
# 输出 7b6b280
```
## 查看最后一次提交的时间
```sh
git log -1 --format="%ct"
输出 1588759297
```
这里输出是unix时间戳,需要自己转换下,如果在shell中可以这么写
```sh
#!/bin/sh
commit_ts=`git log -1 --format="%ct"`
sys=`uname`
if [ $sys = "Darwin" ]
then
commit_time=`date -r${commit_ts} +"%Y-%m-%d %H:%M:%S"`
else
commit_time=`date -d @${commit_ts} +"%Y-%m-%d %H:%M:%S"`
fi
echo $commit_time
```
MacOS和Linux有差别,做个系统判断
## 查看最后一次提交对应的tag
```sh
git log -1 --decorate=short --oneline|grep -Eo 'tag: (.*)[,)]+'|awk '{print $2}'|sed 's/)//g'|sed 's/,//g'
```
这里使用`git log -1 --decorate=short --oneline`,输出
```sh
e4df105 (HEAD -> develop, tag: v0.1.1, origin/develop) 测试提交
```
然后使用grep正则表达式配合awk、sed提取出了`v0.1.1`
好了,就这些吧~
|
package factory;
import model.Brand;
import model.Category;
import model.Item;
public interface ItemCreator {
public Item create(String name, Brand brand, int inStock, float price, Category type);
public Item create(String name, String barCode, Brand brand, int inStock, float price, Category type);
}
|
# archlinux-docker
Setup [yay](https://github.com/Jguer/yay), [fish](https://fishshell.com), vim, git, etc...
## Run
### Normal
```
docker run -it fox0430/archlinux-docker
```
### Rust
```
docker run -it fox0430/archlinux-docker:rust
```
[dockerhub](https://hub.docker.com/repository/docker/fox0430/archlinux-docker)
|
# -*- coding: utf-8 -*-
%w[xot rays reflex]
.map {|s| File.expand_path "../../../#{s}/lib", __FILE__}
.each {|s| $:.unshift s if !$:.include?(s) && File.directory?(s)}
require 'reflex'
include Reflex
class SliderView < View
has_model
def initialize ()
add @back = View.new(name: :back, background: :white)
add @knob = View.new(name: :knob, background: :gray, x: 50) {
style.width 50
}
start = nil
@knob.on :pointer do |e|
case e.type
when :down
start = e.position
@knob.capture :pointer
when :up
start = nil
@knob.capture :none
when :move
self.data = (@knob.x + e.x - start.x) / knob_x_max.to_f if start
end
end
super
end
def on_data_update (e)
@knob.x = knob_x_max * data.to_f
super
end
private
def knob_x_max ()
width - @knob.width
end
end# SliderView
class LabelView < View
has_model
def on_draw (e)
e.painter.text data.to_s if data
end
end# LabelView
class ArrayView < View
has_model
def on_draw (e)
e.painter.text "[#{data.to_s.chars.map{|c| "'#{c}'"}.to_a.join(', ')}]" if data
end
end# ArrayView
win = Window.new do
title 'Model View Sample'
frame 100, 100, 500, 400
add @slider = SliderView.new {set name: :slider, frame: [50, 50, 300, 30]}
add @text = LabelView.new {set name: :text, frame: [50, 150, 300, 30]}
add @array = ArrayView.new {set name: :array, frame: [50, 250, 300, 30]}
@slider.model = @text.model = @array.model = Model.new(0) {set minmax: 0..1}
end
Reflex.start do
win.show
end
|
use cotli_helper::crusader::CrusaderName::VeronicaTheAndroidArcher;
use cotli_helper::crusader::{Crusader, Tags, ROBOT};
use cotli_helper::gear::GearQuality;
use cotli_helper::user_data::*;
use support::*;
#[test]
fn veronica_has_correct_base_dps() {
let veronica = default_crusader(VeronicaTheAndroidArcher);
let mut formation = worlds_wake();
formation.place_crusader(0, &veronica);
assert_formation_dps!("2.07e4", formation);
}
#[test]
fn veronica_buffs_crusaders_in_same_column() {
let dummy_crusader = Crusader::dummy(Tags::empty());
let veronica = default_crusader(VeronicaTheAndroidArcher).at_level(0);
let mut formation = worlds_wake();
formation.place_crusader(0, &dummy_crusader);
assert_formation_dps!("100", formation);
formation.place_crusader(3, &veronica);
assert_formation_dps!("172", formation);
}
#[test]
fn precise_aim_affects_adjacent() {
let dummy_crusader = Crusader::dummy(Tags::empty());
let veronica = default_crusader(VeronicaTheAndroidArcher).at_level(0);
let mut formation = worlds_wake();
formation.place_crusader(0, &dummy_crusader);
assert_formation_dps!("100", formation);
formation.place_crusader(4, &veronica);
assert_formation_dps!("172", formation);
}
#[test]
fn precise_aim_is_not_global() {
let dummy_crusader = Crusader::dummy(Tags::empty());
let veronica = default_crusader(VeronicaTheAndroidArcher).at_level(0);
let mut formation = worlds_wake();
formation.place_crusader(0, &dummy_crusader);
assert_formation_dps!("100", formation);
formation.place_crusader(9, &veronica);
assert_formation_dps!("114", formation); // Floating point rounding error
}
#[test]
fn precise_aim_additively_affected_by_robots() {
let dummy_dps = Crusader::dummy(Tags::empty());
let dummy_robot = Crusader::dummy(ROBOT).at_level(0);
let veronica = default_crusader(VeronicaTheAndroidArcher).at_level(0);
let mut formation = worlds_wake();
formation.place_crusader(0, &dummy_dps);
assert_formation_dps!("100", formation);
formation.place_crusader(1, &veronica);
assert_formation_dps!("172", formation);
formation.place_crusader(9, &dummy_robot);
assert_formation_dps!("201", formation);
formation.place_crusader(8, &dummy_robot);
assert_formation_dps!("229", formation); // Floating point rounding error
}
#[test]
fn precise_aim_scales_correctly_with_gear() {
let dummy_dps = Crusader::dummy(Tags::empty());
let dummy_robot = Crusader::dummy(ROBOT).at_level(0);
let veronica = UserData::default()
.add_crusader(VeronicaTheAndroidArcher, CrusaderData {
gear: [GearQuality::Common, GearQuality::None, GearQuality::None],
..Default::default()
}).unlocked_crusaders(None)
.into_iter()
.find(|c| c.name == VeronicaTheAndroidArcher)
.unwrap()
.at_level(0);
let mut formation = worlds_wake();
formation.place_crusader(0, &dummy_dps);
assert_formation_dps!("100", formation);
formation.place_crusader(1, &veronica);
assert_formation_dps!("178", formation);
formation.place_crusader(9, &dummy_robot);
assert_formation_dps!("209", formation);
formation.place_crusader(8, &dummy_robot);
assert_formation_dps!("241", formation);
}
|
#!/usr/bin/env bash
# Exit script immediately on first error.
set -e
# Print commands and their arguments as they are executed.
set -x
# Install PostgreSQL
sudo apt-get install -y postgresql
sudo -u postgres createuser --superuser ubuntu
sudo -u postgres createdb ubuntu
# Install Heroku
wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh
# Install requirements
pip install pyrax
# TODO: Setup cron
# python ~/backups/run-backup.py
|
'use strict';
const {join} = require('path');
const createSymlink = require('.');
const {realpath, unlink} = require('graceful-fs');
const runSeries = require('run-series');
const test = require('tape');
test('createSymlink()', t => {
t.plan(14);
createSymlink('index.js', '.tmp').then(arg => {
t.strictEqual(arg, undefined, 'should pass no arguments to the onResolved function.');
runSeries([cb => realpath('.tmp', cb), cb => unlink('.tmp', cb)], (err, [result]) => {
t.strictEqual(err, null, 'should create a symlink to the given path.');
t.strictEqual(result, join(__dirname, 'index.js'), 'should create a symlink of the given target.');
});
});
const fail = t.fail.bind(t, 'Unexpectedly succeeded.');
createSymlink('test.js', 'node_modules', {type: 'file'}).then(fail, err => {
t.strictEqual(
err.code,
'EEXIST',
'should fail when it cannot create a symlink.'
);
});
createSymlink('too long symlink target'.repeat(9999), 'o', {}).then(fail, err => {
t.strictEqual(
err.code,
'ENAMETOOLONG',
'should fail when the symlink target is invalid.'
);
});
createSymlink(['?'], 'a').then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: Expected a symlink target (string), but got a non-string value [ \'?\' ] (array).',
'should fail when the first argument is not a string.'
);
});
createSymlink('b', Buffer.from('c')).then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: Expected a path (string) where to create a symlink, but got a non-string value <Buffer 63>.',
'should fail when the second argument is not a string.'
);
});
createSymlink('dest', 'src', new Set()).then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: The third argument of create-symlink must be an object, but got Set {}.',
'should fail when the third argument is not a plain object.'
);
});
createSymlink('1', '2', {type: new Map()}).then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: Expected `type` option to be a valid symlink type – ' +
'\'dir\', \'file\' or \'junction\', but got a non-strng value Map {}.',
'should fail when `type` option is not a string.'
);
});
createSymlink('_', '_', {type: ''}).then(fail, err => {
t.strictEqual(
err.toString(),
'Error: Expected `type` option to be a valid symlink type – ' +
'\'dir\', \'file\' or \'junction\', but got \'\' (empty string).',
'should fail when `type` option is an empty string.'
);
});
createSymlink('_', '_', {type: '?'}).then(fail, err => {
t.strictEqual(
err.toString(),
'Error: Expected `type` option to be a valid symlink type – ' +
'\'dir\', \'file\' or \'junction\', but got an unknown type \'?\'.',
'should fail when `type` option is an unknown symlink type.'
);
});
createSymlink('_', '_', {type: 'DIR'}).then(fail, err => {
t.strictEqual(
err.toString(),
'Error: Expected `type` option to be a valid symlink type – \'dir\', \'file\' or \'junction\', ' +
'but got an unknown type \'DIR\'. Symlink type must be lower case.',
'should suggest using lowercase symlink type.'
);
});
createSymlink().then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: Expected 2 or 3 arguments (target: <string>, path: <string>[, option: <object>]), ' +
'but got no arguments instead.',
'should fail when it takes no argumnts.'
);
});
createSymlink('_', '_', {}, '_').then(fail, err => {
t.strictEqual(
err.toString(),
'TypeError: Expected 2 or 3 arguments (target: <string>, path: <string>[, option: <object>]), ' +
'but got 4 arguments instead.',
'should fail when it takes too many argumnts.'
);
});
});
|
import { ChangePasswordComponent } from "./change-password/change-password.component";
import { DeleteProfileComponent } from "./delete-profile/delete-profile.component";
import { EditProfileComponent } from "./edit-profile/edit-profile.component";
import { ForgotPasswordComponent } from "./forgot-password/forgot-password.component";
import { ListProfilesComponent } from "./list-profiles/list-profiles.component";
import { ProfileComponent } from "./profile/profile.component";
export const profileComponents = [
ForgotPasswordComponent,
ProfileComponent,
EditProfileComponent,
ChangePasswordComponent,
DeleteProfileComponent,
ListProfilesComponent,
] |
object locals[:task]
attributes :id, :action
attributes :username, :started_at, :ended_at, :state, :result, :progress
attributes :input, :output, :humanized
|
/**
* Custom aliases
* With our custom paths being required in and using them in out next.config.js file,
* we're saved from backstepping imports like '../../../middleware/mongodb',
* and can use the needed functionality directly like: import ConnectDB from 'middleware/mongodb'.
*/
const path = require('path');
const paths = require('./paths');
module.exports = {
alias: {
lib: paths.lib,
pages: paths.pages,
customHooks: paths.customHooks,
middleware: paths.middleware,
mongodbModels: paths.mongodbModels,
components: paths.components,
styles: paths.styles
}
};
|
import {Point} from './point'
import {Polyline} from './polyline'
export class PolylinePoint {
private _point: Point
public get point(): Point {
return this._point
}
public set point(value: Point) {
this._point = value
}
private _next: PolylinePoint = null
public get next(): PolylinePoint {
return this._next
}
public set next(value: PolylinePoint) {
this._next = value
}
prev: PolylinePoint = null
polyline: Polyline
get nextOnPolyline(): PolylinePoint {
return this.polyline.next(this)
}
get prevOnPolyline(): PolylinePoint {
return this.polyline.prev(this)
}
//
getNext(): PolylinePoint {
return this.next
}
setNext(nVal: PolylinePoint) {
this.next = nVal
if (this.polyline != null) this.polyline.setInitIsRequired()
}
//
getPrev() {
return this.prev
}
setPrev(prevVal: PolylinePoint) {
this.prev = prevVal
if (this.polyline != null) this.polyline.setInitIsRequired()
}
static mkFromPoint(p: Point) {
const pp = new PolylinePoint()
pp.point = p
return pp
}
}
|
package org.simple.clinic.bppassportgen.util
import org.approvaltests.Approvals
import org.approvaltests.approvers.ApprovalApprover
import org.approvaltests.core.ApprovalFailureReporter
import org.approvaltests.core.ApprovalReporterWithCleanUp
import org.approvaltests.core.ApprovalWriter
import org.approvaltests.namer.ApprovalNamer
import org.approvaltests.writers.ImageApprovalWriter
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
class ImageApprover(
namer: ApprovalNamer,
private val writer: ApprovalWriter,
private val minimumSimilarity: Double
) : ApprovalApprover {
private val baseFilePath = "${namer.sourceFilePath}${namer.approvalName}"
private val received: File = File(writer.getReceivedFilename(baseFilePath))
private val approved: File = File(writer.getApprovalFilename(baseFilePath))
companion object {
fun create(image: BufferedImage, minimumSimilarity: Double): ImageApprover {
return ImageApprover(
namer = Approvals.createApprovalNamer(),
writer = ImageApprovalWriter(image),
minimumSimilarity = minimumSimilarity
)
}
}
override fun cleanUpAfterSuccess(reporter: ApprovalFailureReporter) {
received.delete()
(reporter as? ApprovalReporterWithCleanUp)?.cleanUp(received.absolutePath, approved.absolutePath)
}
override fun approve(): Boolean {
writer.writeReceivedFile(received.absolutePath)
if (!approved.exists() || !received.exists()) {
return false
}
val receivedImage = ImageIO.read(received)
val approvedImage = ImageIO.read(approved)
val similarity = ImageSimilarity.similarity(receivedImage, approvedImage)
return similarity >= minimumSimilarity
}
override fun reportFailure(reporter: ApprovalFailureReporter) {
reporter.report(received.absolutePath, approved.absolutePath)
}
override fun fail() {
throw Error("Failed Approval\n Approved:${approved.absolutePath}\n Received:${received.absolutePath}")
}
}
|
package id.ac.polban.jtk.myapplication;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import id.ac.polban.jtk.database.MhsDatabaseHelper;
/*
@author Mufid Jamaluddin
*/
public class AddMahasiswa extends AppCompatActivity
{
private EditText nameV;
private EditText nimV;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_mahasiswa);
this.nameV = findViewById(R.id.input_name);
this.nimV = findViewById(R.id.input_nim);
Button saveBtn = findViewById(R.id.saveBtn);
Button showBtn = findViewById(R.id.showBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
ContentValues values = new ContentValues();
values.put("NAME",nameV.getText().toString());
values.put("NIM",nimV.getText().toString());
SQLiteOpenHelper sqLiteOpenHelper = new MhsDatabaseHelper(AddMahasiswa.this);
SQLiteDatabase db = null;
try
{
db = sqLiteOpenHelper.getWritableDatabase();
db.insert("MAHASISWA", null, values);
Toast.makeText(AddMahasiswa.this, "Insert Success", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(AddMahasiswa.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
finally
{
if(db != null && db.isOpen())
db.close();
}
}
});
showBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Intent intent = new Intent(AddMahasiswa.this, ListMahasiswa.class);
startActivity(intent);
}
});
}
}
|
# pweb_2020.2_jeffersonNascimento
Repositório para o componente Programação Web da Licenciatura em Computação e Informática - UFERSA/CMA.
Componente responsável por Xico.
|
/**
* Loop through all entries in our user agents object and test everything.
*
* @see src/useragents.js
* @author [email protected]
*/
var g
, ua
, p
, assert = require('assert')
, browser = require('../src/bowser').browser
, allUserAgents = require('../src/useragents').useragents
/**
* Get the length of an object.
* http://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array
*
* @param {Object} obj
* @return {Number}
*/
function objLength(obj) {
var size = 0
, key
for (key in obj) {
if (obj.hasOwnProperty(key)) size++
}
return size
}
function objKeys(obj) {
var keys = []
, key
for (key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key)
}
}
keys.sort();
return keys.join(', ')
}
/* Groups */
for (g in allUserAgents) { (function(group, userAgents) {
describe(group, function() {
/* User Agents */
for (ua in userAgents) { (function(userAgent, expections) {
describe('user agent "' + userAgent + '"', function() {
expections.name = group
/* Get the result from bowser. */
var result = browser._detect(userAgent)
/* At first, check if the result has the correct length. */
it('should have ' + objLength(expections) + ' properties', function() {
assert.equal(objKeys(result), objKeys(expections))
})
/* Properties */
for (p in expections) { (function(property, value, resultValue) {
/* Now ensure correctness of every property. */
it('\'s Property "' + property + '" should be ' + value, function() {
assert.equal(resultValue, value)
})
})(p, expections[p], result[p])}
})
})(ua, userAgents[ua])}
})
})(g, allUserAgents[g])}
|
require 'rails_helper'
RSpec.describe 'users/show', type: :view do
before(:each) do
@user = assign(:user, FactoryGirl.create(:user))
login_as(@user, scope: :user)
end
it 'shows the profile page' do
visit user_path(@user)
expect(page).to have_content(@user.name)
end
it 'expects handed in time sheets section for wimis' do
# will be back soon
# @wimi = assign(:user, FactoryGirl.create(:user))
# @chair = FactoryGirl.create(:chair)
# ChairWimi.create(user: @wimi, chair: @chair, application: 'accepted')
#
# login_as(@wimi, scope: :user)
# visit user_path(@user)
#
# expect(page).to have_content(t('users.show.handed_in_timesheets'))
end
it 'expects time sheets overview section for wimis' do
# will be back soon
# @chair = FactoryGirl.create(:chair)
# ChairWimi.create(user: @user, chair: @chair, application: 'accepted')
# login_as(@user, scope: :user)
# visit user_path(@user)
# expect(page).to have_content(t('users.show.time_sheets_overview'))
end
it 'shows the correct chair in profile' do
chair = FactoryGirl.create(:chair)
ChairWimi.create(user: @user, chair: chair, application: 'accepted')
visit user_path(@user)
expect(page).to have_content(chair.name)
end
it 'allows the superadmin to see his own profile' do
superadmin = FactoryGirl.create(:user, superadmin: true)
login_as(superadmin, scope: :user)
visit user_path(superadmin)
expect(current_path).to eq(user_path(superadmin))
end
# it 'tests if a superadmin can only change his password in his user profile' do
# superadmin = FactoryGirl.create(:user, superadmin: true)
# login_as(superadmin, scope: :user)
#
# visit user_path(superadmin)
# expect(page).to_not have_content(t('users.show.signature'))
# expect(page).to_not have_content(t('users.show.time_sheets_overview'))
# expect(page).to_not have_content(t('users.show.handed_in_timesheets'))
# expect(page).to_not have_content(t('users.show.holiday_requests'))
# expect(page).to_not have_content(t('users.show.business_trips'))
# expect(page).to_not have_content(t('users.show.user_data'))
# expect(page).to have_content(t('users.show.password'))
# end
context 'event settings' do
before :each do
visit user_path(@user)
end
it 'are displayed for event types that are mail enabled' do
Event.mail_enabled_types.each do |type,v|
expect(page).to have_content(I18n.t("event.user_friendly_name.#{type}"))
end
end
it 'are hidden for event types that are not mail enabled' do
Event.NOMAIL.each do |type|
expect(page).not_to have_content(I18n.t("event.user_friendly_name.#{type}"))
end
end
end
end
|
package ca.cmpt213.as3.UI.INPUT;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import ca.cmpt213.as3.MazeGame.ValidInput;
import javax.swing.*;
/**
* UserInput class to obtain user input with case statement depending on what input
*/
public class UserInput {
private static final String[] VALIDKEYS = {"UP", "DOWN", "LEFT", "RIGHT"};
private static ValidInput input;
public static ValidInput getInput() {
return input;
}
public static void setInput(ValidInput input) {
UserInput.input = input;
}
private static void stringInputToEnum(String input) {
switch (input) {
case ("UP"):
setInput(ValidInput.UP);
break;
case ("DOWN"):
setInput(ValidInput.DOWN);
break;
case ("LEFT"):
setInput(ValidInput.LEFT);
break;
case ("RIGHT"):
setInput(ValidInput.RIGHT);
break;
default:
setInput(ValidInput.START);
}
}
private static AbstractAction getKeyListener(final String key, JLabel statusTextBox) {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent evt) {
stringInputToEnum(key);
String stringInput = "Move: ";
switch (input) {
case UP:
stringInput = stringInput + "Up";
break;
case DOWN:
stringInput = stringInput + "Down";
break;
case LEFT:
stringInput = stringInput + "Left";
break;
case RIGHT:
stringInput = stringInput + "Right";
break;
default:
stringInput = "Enter a key";
}
statusTextBox.setText(stringInput);
}
};
}
public static void registerKey(JLabel statusTextBox) {
for (int i = 0; i < VALIDKEYS.length; i++) {
String key = VALIDKEYS[i];
statusTextBox.getInputMap().put(KeyStroke.getKeyStroke(key), key);
statusTextBox.getActionMap().put(key, getKeyListener(key, statusTextBox));
}
}
/**
* Returs a valid input based.
*
* @param testInput User input as a string.
* @return ValidInput
*/
public static ValidInput getValidInput(String testInput) {
switch (testInput) {
case "w":
return ValidInput.UP;
case "s":
return ValidInput.DOWN;
case "a":
return ValidInput.LEFT;
case "d":
return ValidInput.RIGHT;
case "m":
return ValidInput.MAP;
case "?":
return ValidInput.HELP;
case "p":
return ValidInput.PASS;
case "f":
return ValidInput.FREEZE;
case "e":
return ValidInput.EXIT;
case "r":
return ValidInput.RESTART;
case "+":
return ValidInput.RADIUSUP;
case "-":
return ValidInput.RADIUSDOWN;
case "h":
return ValidInput.DIFFICULTY;
case "c":
return ValidInput.CHEESE;
default:
return ValidInput.INVALID;
}
}
}
|
# Description
TypeScript API for
* [LIGO](https://ligolang.org/) contract compilation.
* Interaction with [Flextesa](https://tezos.gitlab.io/flextesa/) sandbox (using
docker images).
* Pinning files and directories to Pinata IPFS.
|
package umontreal.ssj.mcqmctools.florian.examples;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import umontreal.ssj.hups.BakerTransformedPointSet;
import umontreal.ssj.hups.CachedPointSet;
import umontreal.ssj.hups.FaureSequence;
import umontreal.ssj.hups.IndependentPointsCached;
import umontreal.ssj.hups.LMScrambleShift;
import umontreal.ssj.hups.NestedUniformScrambling;
import umontreal.ssj.hups.PointSet;
import umontreal.ssj.hups.PointSetRandomization;
import umontreal.ssj.hups.RQMCPointSet;
import umontreal.ssj.hups.RandomShift;
import umontreal.ssj.hups.Rank1Lattice;
import umontreal.ssj.hups.SobolSequence;
import umontreal.ssj.hups.SortedAndCutPointSet;
import umontreal.ssj.hups.StratifiedUnitCube;
import umontreal.ssj.mcqmctools.MonteCarloModelDouble;
import umontreal.ssj.mcqmctools.RQMCExperimentSeries;
import umontreal.ssj.rng.MRG32k3a;
import umontreal.ssj.rng.RandomStream;
import umontreal.ssj.stat.PgfDataTable;
import umontreal.ssj.stat.Tally;
import umontreal.ssj.util.Num;
/**
* Class containing a main() function to run an experiment for RQMC mean estimation.
* @author florian
*
*/
public class TestRQMCExperimentDouble {
public static void main(String[] args) throws IOException {
MonteCarloModelDouble model;
String modelDescr;
RandomStream noise = new MRG32k3a();
int dim;
String outdir = "";
FileWriter fw;
File file;
StringBuffer sb = new StringBuffer("");
// double a = 0.5;
// dim = 5;
// model = new GFunction(a, dim);
// sb.append(model.toString());
// modelDescr = "GFunction";
// System.out.println(sb.toString());
double a = 2;
dim = 5;
double u = 0.5;
model = new GenzGaussianPeak(a, u,dim);
sb.append(model.toString());
modelDescr = "GenzGaussianPeak";
System.out.println(sb.toString());
// Define the RQMC point sets to be used in experiments.
int basis = 2; // Basis for the loglog plots.
int numSkipReg = 0; // Number of sets skipped for the regression.
int mink = 13; // first log(N) considered
int i;
int m = 500; // Number of RQMC randomizations.
// int[] N = { 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152 }; // 13
int[] N = { 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576 };
int numSets = N.length; // Number of sets in the series.
//Lattice Parameters:
// 0.6^k
int[][] aa = {
{ 1, 3455, 1967, 1029, 2117, 3871, 533, 2411, 1277, 2435, 1723, 3803, 1469, 569, 1035, 3977, 721, 797,
297, 1659 }, // 13
{ 1, 6915, 3959, 7743, 3087, 5281, 6757, 3369, 7107, 6405, 7753, 1641, 3613, 1819, 5827, 2087, 4417,
6909, 5623, 4739 }, // 14
{ 1, 12031, 14297, 677, 6719, 15787, 10149, 7665, 1017, 2251, 12105, 2149, 16273, 14137, 8179, 6461,
15051, 6593, 12763, 8497 }, // 15
{ 1, 19463, 8279, 14631, 12629, 26571, 30383, 1337, 6431, 3901, 12399, 20871, 5175, 3111, 26857, 15111,
22307, 30815, 25901, 27415 }, // 16
{ 1, 38401, 59817, 33763, 32385, 2887, 45473, 48221, 3193, 63355, 40783, 37741, 54515, 11741, 10889,
17759, 6115, 18687, 19665, 26557 }, // 17
{ 1, 100135, 28235, 46895, 82781, 36145, 36833, 130557, 73161, 2259, 3769, 2379, 80685, 127279, 45979,
66891, 8969, 56169, 92713, 67743 }, // 18
{ 1, 154805, 242105, 171449, 27859, 76855, 183825, 38785, 178577, 18925, 260553, 130473, 258343, 79593,
96263, 36291, 2035, 198019, 15473, 148703 }, // 19
{ 1, 387275, 314993, 50301, 174023, 354905, 303021, 486111, 286797, 463237, 211171, 216757, 29831,
155061, 315509, 193933, 129563, 276501, 395079, 139111 } // 20
};
// 0.6^k
int[] aMult = { 1, 103259, 511609, 482163, 299529, 491333, 30987, 286121, 388189, 39885, 413851, 523765, 501705,
93009, 44163, 325229, 345483, 168873, 376109, 146111 };
// Create a list of series of RQMC point sets.
ArrayList<RQMCPointSet[]> listRQMC = new ArrayList<RQMCPointSet[]>();
PointSet p;
PointSetRandomization rand;
RQMCPointSet[] rqmcPts;
String[] merits;
String path;
// // Independent points (Monte Carlo)
// rqmcPts = new RQMCPointSet[numSets];
// for (i = 0; i < numSets; ++i) {
// p = new IndependentPointsCached(N[i], dim);
// rand = new RandomShift(noise);
// rqmcPts[i] = new RQMCPointSet(p, rand);
// }
// rqmcPts[0].setLabel("Independent points");
// listRQMC.add(rqmcPts);
// Stratification
// rqmcPts = new RQMCPointSet[numSets];
// int k;
// for (i = 0; i < numSets; ++i) {
// k = (int) Math.round(Math.pow(Num.TWOEXP[i + mink], 1.0 / (double) (dim)));
// p = new StratifiedUnitCube(k, dim);
//
// rand = new RandomShift(noise);
// rqmcPts[i] = new RQMCPointSet(p, rand);
// }
// rqmcPts[0].setLabel("Stratification");
// listRQMC.add(rqmcPts);
// lattice+shift
rqmcPts = new RQMCPointSet[numSets];
for (i = 0; i < numSets; ++i) {
// p = new Rank1Lattice(N[i], aa[i], dim);
p = new Rank1Lattice(N[i], aMult, dim);
rand = new RandomShift(noise);
rqmcPts[i] = new RQMCPointSet(p, rand);
}
rqmcPts[0].setLabel("Lattice+Shift");
listRQMC.add(rqmcPts);
// lattice+baker
rqmcPts = new RQMCPointSet[numSets];
for (i = 0; i < numSets; ++i) {
// p = new BakerTransformedPointSet(new Rank1Lattice(N[i],aa[i],dim));
p = new BakerTransformedPointSet(new Rank1Lattice(N[i], aMult, dim));
rand = new RandomShift(noise);
rqmcPts[i] = new RQMCPointSet(p, rand);
}
rqmcPts[0].setLabel("Lattice+Baker");
listRQMC.add(rqmcPts);
// // Sobol + LMS
// rqmcPts = new RQMCPointSet[numSets];
// for (i = 0; i < numSets; ++i) {
//
// p = new SobolSequence(i + mink, 31, dim);
//
// rand = new LMScrambleShift(noise);
// rqmcPts[i] = new RQMCPointSet(p, rand);
// }
// rqmcPts[0].setLabel("Sobol+LMS");
// listRQMC.add(rqmcPts);
//
// // Sobol+NUS
// rqmcPts = new RQMCPointSet[numSets];
// for (i = 0; i < numSets; ++i) {
// CachedPointSet cp = new CachedPointSet(new SobolSequence(N[i], dim));
//
// cp.setRandomizeParent(false);
// p = cp;
//
// rand = new NestedUniformScrambling(noise, i + mink + 1);
// rqmcPts[i] = new RQMCPointSet(p, rand);
// }
// rqmcPts[0].setLabel("Sobol+NUS");
// listRQMC.add(rqmcPts);
boolean makePgfTable = true;
boolean printReport = true;
boolean details = true;
// Perform an experiment with the list of series of RQMC point sets.
// This list contains two series: lattice and Sobol.
ArrayList<PgfDataTable> listCurves = new ArrayList<PgfDataTable>();
RQMCExperimentSeries experSeries = new RQMCExperimentSeries(listRQMC.get(0), basis);
experSeries.setExecutionDisplay(details);
file = new File(outdir + "reportRQMC.txt");
// file.getParentFile().mkdirs();
fw = new FileWriter(file);
fw.write(modelDescr + experSeries.testVarianceRateManyPointTypes(model, listRQMC, m, numSkipReg, makePgfTable,
printReport, details, listCurves));
fw.close();
// Produces LaTeX code to draw these curves with pgfplot.
sb = new StringBuffer("");
sb.append(PgfDataTable.pgfplotFileHeader());
sb.append(PgfDataTable.drawPgfPlotManyCurves(modelDescr + ": Mean values", "axis", 3, 1, listCurves, basis, "",
" "));
sb.append(PgfDataTable.pgfplotEndDocument());
file = new File(outdir + "plotMean.tex");
fw = new FileWriter(file);
fw.write(sb.toString());
fw.close();
sb = new StringBuffer("");
sb.append(PgfDataTable.pgfplotFileHeader());
sb.append(PgfDataTable.drawPgfPlotManyCurves(modelDescr + ": Variance", "axis", 3, 4, listCurves, basis, "",
" "));
sb.append(PgfDataTable.pgfplotEndDocument());
file = new File(outdir + "plotVariance.tex");
fw = new FileWriter(file);
fw.write(sb.toString());
fw.close();
}
}
|
using Sharpen;
namespace android.logging.@internal
{
[Sharpen.NakedStub]
public class AndroidConfig
{
}
}
|
# dicewin
(description)
* [Installation](#installation)
* [Usage](#usage)
## <a name="installation"></a> Installation
## <a name="usage"></a> Usage
|
use super::char_tree::{CharacterTree, Comparator};
use super::grammars::{ExternalToken, LexicalGrammar, SyntaxGrammar, VariableType};
use super::rules::{Alias, AliasMap, Symbol, SymbolType};
use super::tables::{
AdvanceAction, FieldLocation, GotoAction, LexState, LexTable, ParseAction, ParseTable,
ParseTableEntry,
};
use core::ops::Range;
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::mem::swap;
const LARGE_CHARACTER_RANGE_COUNT: usize = 8;
const SMALL_STATE_THRESHOLD: usize = 64;
macro_rules! add {
($this: tt, $($arg: tt)*) => {{
$this.buffer.write_fmt(format_args!($($arg)*)).unwrap();
}}
}
macro_rules! add_whitespace {
($this: tt) => {{
for _ in 0..$this.indent_level {
write!(&mut $this.buffer, " ").unwrap();
}
}};
}
macro_rules! add_line {
($this: tt, $($arg: tt)*) => {
add_whitespace!($this);
$this.buffer.write_fmt(format_args!($($arg)*)).unwrap();
$this.buffer += "\n";
}
}
macro_rules! indent {
($this: tt) => {
$this.indent_level += 1;
};
}
macro_rules! dedent {
($this: tt) => {
assert_ne!($this.indent_level, 0);
$this.indent_level -= 1;
};
}
struct Generator {
buffer: String,
indent_level: usize,
language_name: String,
parse_table: ParseTable,
main_lex_table: LexTable,
keyword_lex_table: LexTable,
large_state_count: usize,
keyword_capture_token: Option<Symbol>,
syntax_grammar: SyntaxGrammar,
lexical_grammar: LexicalGrammar,
default_aliases: AliasMap,
symbol_order: HashMap<Symbol, usize>,
symbol_ids: HashMap<Symbol, String>,
alias_ids: HashMap<Alias, String>,
unique_aliases: Vec<Alias>,
symbol_map: HashMap<Symbol, Symbol>,
field_names: Vec<String>,
#[allow(unused)]
next_abi: bool,
}
struct TransitionSummary {
is_included: bool,
ranges: Vec<Range<char>>,
call_id: Option<usize>,
}
struct LargeCharacterSetInfo {
ranges: Vec<Range<char>>,
symbol: Symbol,
index: usize,
}
impl Generator {
fn generate(mut self) -> String {
self.init();
self.add_includes();
self.add_pragmas();
self.add_stats();
self.add_symbol_enum();
self.add_symbol_names_list();
self.add_unique_symbol_map();
self.add_symbol_metadata_list();
if !self.field_names.is_empty() {
self.add_field_name_enum();
self.add_field_name_names_list();
self.add_field_sequences();
}
if !self.parse_table.production_infos.is_empty() {
self.add_alias_sequences();
}
self.add_non_terminal_alias_map();
let mut main_lex_table = LexTable::default();
swap(&mut main_lex_table, &mut self.main_lex_table);
self.add_lex_function("ts_lex", main_lex_table, true);
if self.keyword_capture_token.is_some() {
let mut keyword_lex_table = LexTable::default();
swap(&mut keyword_lex_table, &mut self.keyword_lex_table);
self.add_lex_function("ts_lex_keywords", keyword_lex_table, false);
}
self.add_lex_modes_list();
if !self.syntax_grammar.external_tokens.is_empty() {
self.add_external_token_enum();
self.add_external_scanner_symbol_map();
self.add_external_scanner_states_list();
}
self.add_parse_table();
self.add_parser_export();
self.buffer
}
fn init(&mut self) {
let mut symbol_identifiers = HashSet::new();
for i in 0..self.parse_table.symbols.len() {
self.assign_symbol_id(self.parse_table.symbols[i], &mut symbol_identifiers);
}
self.symbol_ids.insert(
Symbol::end_of_nonterminal_extra(),
self.symbol_ids[&Symbol::end()].clone(),
);
self.symbol_map = self
.parse_table
.symbols
.iter()
.map(|symbol| {
let mut mapping = symbol;
// There can be multiple symbols in the grammar that have the same name and kind,
// due to simple aliases. When that happens, ensure that they map to the same
// public-facing symbol. If one of the symbols is not aliased, choose that one
// to be the public-facing symbol. Otherwise, pick the symbol with the lowest
// numeric value.
if let Some(alias) = self.default_aliases.get(symbol) {
let kind = alias.kind();
for other_symbol in &self.parse_table.symbols {
if let Some(other_alias) = self.default_aliases.get(other_symbol) {
if other_symbol < mapping && other_alias == alias {
mapping = other_symbol;
}
} else if self.metadata_for_symbol(*other_symbol) == (&alias.value, kind) {
mapping = other_symbol;
break;
}
}
}
// Two anonymous tokens with different flags but the same string value
// should be represented with the same symbol in the public API. Examples:
// * "<" and token(prec(1, "<"))
// * "(" and token.immediate("(")
else if symbol.is_terminal() {
let metadata = self.metadata_for_symbol(*symbol);
for other_symbol in &self.parse_table.symbols {
let other_metadata = self.metadata_for_symbol(*other_symbol);
if other_metadata == metadata {
mapping = other_symbol;
break;
}
}
}
(*symbol, *mapping)
})
.collect();
for production_info in &self.parse_table.production_infos {
// Build a list of all field names
for field_name in production_info.field_map.keys() {
if let Err(i) = self.field_names.binary_search(&field_name) {
self.field_names.insert(i, field_name.clone());
}
}
for alias in &production_info.alias_sequence {
// Generate a mapping from aliases to C identifiers.
if let Some(alias) = &alias {
let existing_symbol = self.parse_table.symbols.iter().cloned().find(|symbol| {
if let Some(default_alias) = self.default_aliases.get(symbol) {
default_alias == alias
} else {
let (name, kind) = self.metadata_for_symbol(*symbol);
name == alias.value && kind == alias.kind()
}
});
// Some aliases match an existing symbol in the grammar.
let alias_id;
if let Some(existing_symbol) = existing_symbol {
alias_id = self.symbol_ids[&self.symbol_map[&existing_symbol]].clone();
}
// Other aliases don't match any existing symbol, and need their own identifiers.
else {
if let Err(i) = self.unique_aliases.binary_search(alias) {
self.unique_aliases.insert(i, alias.clone());
}
alias_id = if alias.is_named {
format!("alias_sym_{}", self.sanitize_identifier(&alias.value))
} else {
format!("anon_alias_sym_{}", self.sanitize_identifier(&alias.value))
};
}
self.alias_ids.entry(alias.clone()).or_insert(alias_id);
}
}
}
// Determine which states should use the "small state" representation, and which should
// use the normal array representation.
let threshold = cmp::min(SMALL_STATE_THRESHOLD, self.parse_table.symbols.len() / 2);
self.large_state_count = self
.parse_table
.states
.iter()
.enumerate()
.take_while(|(i, s)| {
*i <= 1 || s.terminal_entries.len() + s.nonterminal_entries.len() > threshold
})
.count();
}
fn add_includes(&mut self) {
add_line!(self, "#include <tree_sitter/parser.h>");
add_line!(self, "");
}
fn add_pragmas(&mut self) {
add_line!(self, "#if defined(__GNUC__) || defined(__clang__)");
add_line!(self, "#pragma GCC diagnostic push");
add_line!(
self,
"#pragma GCC diagnostic ignored \"-Wmissing-field-initializers\""
);
add_line!(self, "#endif");
add_line!(self, "");
// Compiling large lexer functions can be very slow. Disabling optimizations
// is not ideal, but only a very small fraction of overall parse time is
// spent lexing, so the performance impact of this is negligible.
if self.main_lex_table.states.len() > 300 {
add_line!(self, "#ifdef _MSC_VER");
add_line!(self, "#pragma optimize(\"\", off)");
add_line!(self, "#elif defined(__clang__)");
add_line!(self, "#pragma clang optimize off");
add_line!(self, "#elif defined(__GNUC__)");
add_line!(self, "#pragma GCC optimize (\"O0\")");
add_line!(self, "#endif");
add_line!(self, "");
}
}
fn add_stats(&mut self) {
let token_count = self
.parse_table
.symbols
.iter()
.filter(|symbol| {
if symbol.is_terminal() || symbol.is_eof() {
true
} else if symbol.is_external() {
self.syntax_grammar.external_tokens[symbol.index]
.corresponding_internal_token
.is_none()
} else {
false
}
})
.count();
add_line!(
self,
"#define LANGUAGE_VERSION {}",
if self.next_abi {
tree_sitter::LANGUAGE_VERSION
} else {
tree_sitter::LANGUAGE_VERSION - 1
}
);
add_line!(
self,
"#define STATE_COUNT {}",
self.parse_table.states.len()
);
add_line!(self, "#define LARGE_STATE_COUNT {}", self.large_state_count);
add_line!(
self,
"#define SYMBOL_COUNT {}",
self.parse_table.symbols.len()
);
add_line!(self, "#define ALIAS_COUNT {}", self.unique_aliases.len(),);
add_line!(self, "#define TOKEN_COUNT {}", token_count);
add_line!(
self,
"#define EXTERNAL_TOKEN_COUNT {}",
self.syntax_grammar.external_tokens.len()
);
add_line!(self, "#define FIELD_COUNT {}", self.field_names.len());
add_line!(
self,
"#define MAX_ALIAS_SEQUENCE_LENGTH {}",
self.parse_table.max_aliased_production_length
);
add_line!(
self,
"#define PRODUCTION_ID_COUNT {}",
self.parse_table.production_infos.len()
);
add_line!(self, "");
}
fn add_symbol_enum(&mut self) {
add_line!(self, "enum {{");
indent!(self);
self.symbol_order.insert(Symbol::end(), 0);
let mut i = 1;
for symbol in self.parse_table.symbols.iter() {
if *symbol != Symbol::end() {
self.symbol_order.insert(*symbol, i);
add_line!(self, "{} = {},", self.symbol_ids[&symbol], i);
i += 1;
}
}
for alias in &self.unique_aliases {
add_line!(self, "{} = {},", self.alias_ids[&alias], i);
i += 1;
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_symbol_names_list(&mut self) {
add_line!(self, "static const char *ts_symbol_names[] = {{");
indent!(self);
for symbol in self.parse_table.symbols.iter() {
let name = self.sanitize_string(
self.default_aliases
.get(symbol)
.map(|alias| alias.value.as_str())
.unwrap_or(self.metadata_for_symbol(*symbol).0),
);
add_line!(self, "[{}] = \"{}\",", self.symbol_ids[&symbol], name);
}
for alias in &self.unique_aliases {
add_line!(
self,
"[{}] = \"{}\",",
self.alias_ids[&alias],
self.sanitize_string(&alias.value)
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_unique_symbol_map(&mut self) {
add_line!(self, "static const TSSymbol ts_symbol_map[] = {{");
indent!(self);
for symbol in &self.parse_table.symbols {
add_line!(
self,
"[{}] = {},",
self.symbol_ids[symbol],
self.symbol_ids[&self.symbol_map[symbol]],
);
}
for alias in &self.unique_aliases {
add_line!(
self,
"[{}] = {},",
self.alias_ids[&alias],
self.alias_ids[&alias],
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_field_name_enum(&mut self) {
add_line!(self, "enum {{");
indent!(self);
for (i, field_name) in self.field_names.iter().enumerate() {
add_line!(self, "{} = {},", self.field_id(field_name), i + 1);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_field_name_names_list(&mut self) {
add_line!(self, "static const char *ts_field_names[] = {{");
indent!(self);
add_line!(self, "[0] = NULL,");
for field_name in &self.field_names {
add_line!(
self,
"[{}] = \"{}\",",
self.field_id(field_name),
field_name
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_symbol_metadata_list(&mut self) {
add_line!(
self,
"static const TSSymbolMetadata ts_symbol_metadata[] = {{"
);
indent!(self);
for symbol in &self.parse_table.symbols {
add_line!(self, "[{}] = {{", self.symbol_ids[&symbol]);
indent!(self);
if let Some(Alias { is_named, .. }) = self.default_aliases.get(symbol) {
add_line!(self, ".visible = true,");
add_line!(self, ".named = {},", is_named);
} else {
match self.metadata_for_symbol(*symbol).1 {
VariableType::Named => {
add_line!(self, ".visible = true,");
add_line!(self, ".named = true,");
}
VariableType::Anonymous => {
add_line!(self, ".visible = true,");
add_line!(self, ".named = false,");
}
VariableType::Hidden => {
add_line!(self, ".visible = false,");
add_line!(self, ".named = true,");
if self.syntax_grammar.supertype_symbols.contains(symbol) {
add_line!(self, ".supertype = true,");
}
}
VariableType::Auxiliary => {
add_line!(self, ".visible = false,");
add_line!(self, ".named = false,");
}
}
}
dedent!(self);
add_line!(self, "}},");
}
for alias in &self.unique_aliases {
add_line!(self, "[{}] = {{", self.alias_ids[&alias]);
indent!(self);
add_line!(self, ".visible = true,");
add_line!(self, ".named = {},", alias.is_named);
dedent!(self);
add_line!(self, "}},");
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_alias_sequences(&mut self) {
add_line!(
self,
"static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = {{",
);
indent!(self);
for (i, production_info) in self.parse_table.production_infos.iter().enumerate() {
if production_info.alias_sequence.is_empty() {
// Work around MSVC's intolerance of empty array initializers by
// explicitly zero-initializing the first element.
if i == 0 {
add_line!(self, "[0] = {{0}},");
}
continue;
}
add_line!(self, "[{}] = {{", i);
indent!(self);
for (j, alias) in production_info.alias_sequence.iter().enumerate() {
if let Some(alias) = alias {
add_line!(self, "[{}] = {},", j, self.alias_ids[&alias]);
}
}
dedent!(self);
add_line!(self, "}},");
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_non_terminal_alias_map(&mut self) {
let mut alias_ids_by_symbol = HashMap::new();
for variable in &self.syntax_grammar.variables {
for production in &variable.productions {
for step in &production.steps {
if let Some(alias) = &step.alias {
if step.symbol.is_non_terminal()
&& Some(alias) != self.default_aliases.get(&step.symbol)
{
if self.symbol_ids.contains_key(&step.symbol) {
if let Some(alias_id) = self.alias_ids.get(&alias) {
let alias_ids = alias_ids_by_symbol
.entry(step.symbol)
.or_insert(Vec::new());
if let Err(i) = alias_ids.binary_search(&alias_id) {
alias_ids.insert(i, alias_id);
}
}
}
}
}
}
}
}
let mut alias_ids_by_symbol = alias_ids_by_symbol.iter().collect::<Vec<_>>();
alias_ids_by_symbol.sort_unstable_by_key(|e| e.0);
add_line!(self, "static const uint16_t ts_non_terminal_alias_map[] = {{");
indent!(self);
for (symbol, alias_ids) in alias_ids_by_symbol {
let symbol_id = &self.symbol_ids[symbol];
let public_symbol_id = &self.symbol_ids[&self.symbol_map[&symbol]];
add_line!(self, "{}, {},", symbol_id, 1 + alias_ids.len());
indent!(self);
add_line!(self, "{},", public_symbol_id);
for alias_id in alias_ids {
add_line!(self, "{},", alias_id);
}
dedent!(self);
}
add_line!(self, "0,");
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_field_sequences(&mut self) {
let mut flat_field_maps = vec![];
let mut next_flat_field_map_index = 0;
self.get_field_map_id(
&Vec::new(),
&mut flat_field_maps,
&mut next_flat_field_map_index,
);
let mut field_map_ids = Vec::new();
for production_info in &self.parse_table.production_infos {
if !production_info.field_map.is_empty() {
let mut flat_field_map = Vec::new();
for (field_name, locations) in &production_info.field_map {
for location in locations {
flat_field_map.push((field_name.clone(), *location));
}
}
field_map_ids.push((
self.get_field_map_id(
&flat_field_map,
&mut flat_field_maps,
&mut next_flat_field_map_index,
),
flat_field_map.len(),
));
} else {
field_map_ids.push((0, 0));
}
}
add_line!(
self,
"static const TSFieldMapSlice ts_field_map_slices[PRODUCTION_ID_COUNT] = {{",
);
indent!(self);
for (production_id, (row_id, length)) in field_map_ids.into_iter().enumerate() {
if length > 0 {
add_line!(
self,
"[{}] = {{.index = {}, .length = {}}},",
production_id,
row_id,
length
);
}
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
add_line!(
self,
"static const TSFieldMapEntry ts_field_map_entries[] = {{",
);
indent!(self);
for (row_index, field_pairs) in flat_field_maps.into_iter().skip(1) {
add_line!(self, "[{}] =", row_index);
indent!(self);
for (field_name, location) in field_pairs {
add_whitespace!(self);
add!(self, "{{{}, {}", self.field_id(&field_name), location.index);
if location.inherited {
add!(self, ", .inherited = true");
}
add!(self, "}},\n");
}
dedent!(self);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_lex_function(
&mut self,
name: &str,
lex_table: LexTable,
extract_helper_functions: bool,
) {
let mut ruled_out_chars = HashSet::new();
let mut large_character_sets = Vec::<LargeCharacterSetInfo>::new();
// For each lex state, compute a summary of the code that needs to be
// generated.
let state_transition_summaries: Vec<Vec<TransitionSummary>> = lex_table
.states
.iter()
.map(|state| {
ruled_out_chars.clear();
// For each state transition, compute the set of character ranges
// that need to be checked.
state
.advance_actions
.iter()
.map(|(chars, action)| {
let is_included = !chars.contains(std::char::MAX);
let mut ranges;
if is_included {
ranges = chars.simplify_ignoring(&ruled_out_chars);
ruled_out_chars.extend(chars.iter());
} else {
ranges = chars.clone().negate().simplify_ignoring(&ruled_out_chars);
ranges.insert(0, '\0'..'\0')
}
// Record any large character sets so that they can be extracted
// into helper functions, reducing code duplication.
let mut call_id = None;
if extract_helper_functions && ranges.len() > LARGE_CHARACTER_RANGE_COUNT {
let char_set_symbol = self
.symbol_for_advance_action(action, &lex_table)
.expect("No symbol for lex state");
let mut count_for_symbol = 0;
for (i, info) in large_character_sets.iter_mut().enumerate() {
if info.ranges == ranges {
call_id = Some(i);
break;
}
if info.symbol == char_set_symbol {
count_for_symbol += 1;
}
}
if call_id.is_none() {
call_id = Some(large_character_sets.len());
large_character_sets.push(LargeCharacterSetInfo {
symbol: char_set_symbol,
index: count_for_symbol + 1,
ranges: ranges.clone(),
});
}
}
TransitionSummary {
is_included,
ranges,
call_id,
}
})
.collect()
})
.collect();
// Generate a helper function for each large character set.
let mut sorted_large_char_sets: Vec<_> = large_character_sets.iter().map(|e| e).collect();
sorted_large_char_sets.sort_unstable_by_key(|info| (info.symbol, info.index));
for info in sorted_large_char_sets {
add_line!(
self,
"static inline bool {}_character_set_{}(int32_t c) {{",
self.symbol_ids[&info.symbol],
info.index
);
indent!(self);
add_whitespace!(self);
add!(self, "return ");
let tree = CharacterTree::from_ranges(&info.ranges);
self.add_character_tree(tree.as_ref());
add!(self, ";\n");
dedent!(self);
add_line!(self, "}}");
add_line!(self, "");
}
add_line!(
self,
"static bool {}(TSLexer *lexer, TSStateId state) {{",
name
);
indent!(self);
add_line!(self, "START_LEXER();");
add_line!(self, "eof = lexer->eof(lexer);");
add_line!(self, "switch (state) {{");
indent!(self);
for (i, state) in lex_table.states.into_iter().enumerate() {
add_line!(self, "case {}:", i);
indent!(self);
self.add_lex_state(state, &state_transition_summaries[i], &large_character_sets);
dedent!(self);
}
add_line!(self, "default:");
indent!(self);
add_line!(self, "return false;");
dedent!(self);
dedent!(self);
add_line!(self, "}}");
dedent!(self);
add_line!(self, "}}");
add_line!(self, "");
}
fn symbol_for_advance_action(
&self,
action: &AdvanceAction,
lex_table: &LexTable,
) -> Option<Symbol> {
let mut state_ids = vec![action.state];
let mut i = 0;
while i < state_ids.len() {
let id = state_ids[i];
let state = &lex_table.states[id];
if let Some(accept) = state.accept_action {
return Some(accept);
}
for (_, action) in &state.advance_actions {
if !state_ids.contains(&action.state) {
state_ids.push(action.state);
}
}
i += 1;
}
return None;
}
fn add_lex_state(
&mut self,
state: LexState,
transition_info: &Vec<TransitionSummary>,
large_character_sets: &Vec<LargeCharacterSetInfo>,
) {
if let Some(accept_action) = state.accept_action {
add_line!(self, "ACCEPT_TOKEN({});", self.symbol_ids[&accept_action]);
}
if let Some(eof_action) = state.eof_action {
add_line!(self, "if (eof) ADVANCE({});", eof_action.state);
}
for (i, (_, action)) in state.advance_actions.into_iter().enumerate() {
let transition = &transition_info[i];
add_whitespace!(self);
// If there is a helper function for this transition's character
// set, then generate a call to that helper function.
if let Some(call_id) = transition.call_id {
let info = &large_character_sets[call_id];
add!(self, "if (");
if !transition.is_included {
add!(self, "!");
}
add!(
self,
"{}_character_set_{}(lookahead)) ",
self.symbol_ids[&info.symbol],
info.index
);
self.add_advance_action(&action);
add!(self, "\n");
continue;
}
// Otherwise, generate code to compare the lookahead character
// with all of the character ranges.
if transition.ranges.len() > 0 {
add!(self, "if (");
self.add_character_range_conditions(&transition.ranges, transition.is_included, 2);
add!(self, ") ");
}
self.add_advance_action(&action);
add!(self, "\n");
}
add_line!(self, "END_STATE();");
}
fn add_character_range_conditions(
&mut self,
ranges: &[Range<char>],
is_included: bool,
indent_count: usize,
) {
let mut line_break = "\n".to_string();
for _ in 0..self.indent_level + indent_count {
line_break.push_str(" ");
}
for (i, range) in ranges.iter().enumerate() {
if is_included {
if i > 0 {
add!(self, " ||{}", line_break);
}
if range.end == range.start {
add!(self, "lookahead == ");
self.add_character(range.start);
} else if range.end as u32 == range.start as u32 + 1 {
add!(self, "lookahead == ");
self.add_character(range.start);
add!(self, " ||{}lookahead == ", line_break);
self.add_character(range.end);
} else {
add!(self, "(");
self.add_character(range.start);
add!(self, " <= lookahead && lookahead <= ");
self.add_character(range.end);
add!(self, ")");
}
} else {
if i > 0 {
add!(self, " &&{}", line_break);
}
if range.end == range.start {
add!(self, "lookahead != ");
self.add_character(range.start);
} else if range.end as u32 == range.start as u32 + 1 {
add!(self, "lookahead != ");
self.add_character(range.start);
add!(self, " &&{}lookahead != ", line_break);
self.add_character(range.end);
} else {
if range.start != '\0' {
add!(self, "(lookahead < ");
self.add_character(range.start);
add!(self, " || ");
self.add_character(range.end);
add!(self, " < lookahead)");
} else {
add!(self, "lookahead > ");
self.add_character(range.end);
}
}
}
}
}
fn add_character_tree(&mut self, tree: Option<&CharacterTree>) {
match tree {
Some(CharacterTree::Compare {
value,
operator,
consequence,
alternative,
}) => {
let op = match operator {
Comparator::Less => "<",
Comparator::LessOrEqual => "<=",
Comparator::Equal => "==",
Comparator::GreaterOrEqual => ">=",
};
let consequence = consequence.as_ref().map(Box::as_ref);
let alternative = alternative.as_ref().map(Box::as_ref);
let simple = alternative.is_none() && consequence == Some(&CharacterTree::Yes);
if !simple {
add!(self, "(");
}
add!(self, "c {} ", op);
self.add_character(*value);
if !simple {
if alternative.is_none() {
add!(self, " && ");
self.add_character_tree(consequence);
} else if consequence == Some(&CharacterTree::Yes) {
add!(self, " || ");
self.add_character_tree(alternative);
} else {
add!(self, "\n");
indent!(self);
add_whitespace!(self);
add!(self, "? ");
self.add_character_tree(consequence);
add!(self, "\n");
add_whitespace!(self);
add!(self, ": ");
self.add_character_tree(alternative);
dedent!(self);
}
}
if !simple {
add!(self, ")");
}
}
Some(CharacterTree::Yes) => {
add!(self, "true");
}
None => {
add!(self, "false");
}
}
}
fn add_advance_action(&mut self, action: &AdvanceAction) {
if action.in_main_token {
add!(self, "ADVANCE({});", action.state);
} else {
add!(self, "SKIP({})", action.state);
}
}
fn add_lex_modes_list(&mut self) {
add_line!(self, "static const TSLexMode ts_lex_modes[STATE_COUNT] = {{");
indent!(self);
for (i, state) in self.parse_table.states.iter().enumerate() {
if state.is_end_of_non_terminal_extra() {
add_line!(self, "[{}] = {{(TSStateId)(-1)}},", i,);
} else if state.external_lex_state_id > 0 {
add_line!(
self,
"[{}] = {{.lex_state = {}, .external_lex_state = {}}},",
i,
state.lex_state_id,
state.external_lex_state_id
);
} else {
add_line!(self, "[{}] = {{.lex_state = {}}},", i, state.lex_state_id);
}
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_external_token_enum(&mut self) {
add_line!(self, "enum {{");
indent!(self);
for i in 0..self.syntax_grammar.external_tokens.len() {
add_line!(
self,
"{} = {},",
self.external_token_id(&self.syntax_grammar.external_tokens[i]),
i
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_external_scanner_symbol_map(&mut self) {
add_line!(
self,
"static const TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = {{"
);
indent!(self);
for i in 0..self.syntax_grammar.external_tokens.len() {
let token = &self.syntax_grammar.external_tokens[i];
let id_token = token
.corresponding_internal_token
.unwrap_or(Symbol::external(i));
add_line!(
self,
"[{}] = {},",
self.external_token_id(&token),
self.symbol_ids[&id_token],
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_external_scanner_states_list(&mut self) {
add_line!(
self,
"static const bool ts_external_scanner_states[{}][EXTERNAL_TOKEN_COUNT] = {{",
self.parse_table.external_lex_states.len(),
);
indent!(self);
for i in 0..self.parse_table.external_lex_states.len() {
if !self.parse_table.external_lex_states[i].is_empty() {
add_line!(self, "[{}] = {{", i);
indent!(self);
for token in self.parse_table.external_lex_states[i].iter() {
add_line!(
self,
"[{}] = true,",
self.external_token_id(&self.syntax_grammar.external_tokens[token.index])
);
}
dedent!(self);
add_line!(self, "}},");
}
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_parse_table(&mut self) {
let mut parse_table_entries = Vec::new();
let mut next_parse_action_list_index = 0;
self.get_parse_action_list_id(
&ParseTableEntry {
actions: Vec::new(),
reusable: false,
},
&mut parse_table_entries,
&mut next_parse_action_list_index,
);
add_line!(
self,
"static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = {{",
);
indent!(self);
let mut terminal_entries = Vec::new();
let mut nonterminal_entries = Vec::new();
for (i, state) in self
.parse_table
.states
.iter()
.enumerate()
.take(self.large_state_count)
{
add_line!(self, "[{}] = {{", i);
indent!(self);
// Ensure the entries are in a deterministic order, since they are
// internally represented as a hash map.
terminal_entries.clear();
nonterminal_entries.clear();
terminal_entries.extend(state.terminal_entries.iter());
nonterminal_entries.extend(state.nonterminal_entries.iter());
terminal_entries.sort_unstable_by_key(|e| self.symbol_order.get(e.0));
nonterminal_entries.sort_unstable_by_key(|k| k.0);
for (symbol, action) in &nonterminal_entries {
add_line!(
self,
"[{}] = STATE({}),",
self.symbol_ids[symbol],
match action {
GotoAction::Goto(state) => *state,
GotoAction::ShiftExtra => i,
}
);
}
for (symbol, entry) in &terminal_entries {
let entry_id = self.get_parse_action_list_id(
entry,
&mut parse_table_entries,
&mut next_parse_action_list_index,
);
add_line!(
self,
"[{}] = ACTIONS({}),",
self.symbol_ids[symbol],
entry_id
);
}
dedent!(self);
add_line!(self, "}},");
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
if self.large_state_count < self.parse_table.states.len() {
add_line!(self, "static const uint16_t ts_small_parse_table[] = {{");
indent!(self);
let mut index = 0;
let mut small_state_indices = Vec::new();
let mut symbols_by_value: HashMap<(usize, SymbolType), Vec<Symbol>> = HashMap::new();
for state in self.parse_table.states.iter().skip(self.large_state_count) {
small_state_indices.push(index);
symbols_by_value.clear();
terminal_entries.clear();
terminal_entries.extend(state.terminal_entries.iter());
terminal_entries.sort_unstable_by_key(|e| self.symbol_order.get(e.0));
// In a given parse state, many lookahead symbols have the same actions.
// So in the "small state" representation, group symbols by their action
// in order to avoid repeating the action.
for (symbol, entry) in &terminal_entries {
let entry_id = self.get_parse_action_list_id(
entry,
&mut parse_table_entries,
&mut next_parse_action_list_index,
);
symbols_by_value
.entry((entry_id, SymbolType::Terminal))
.or_default()
.push(**symbol);
}
for (symbol, action) in &state.nonterminal_entries {
let state_id = match action {
GotoAction::Goto(i) => *i,
GotoAction::ShiftExtra => {
self.large_state_count + small_state_indices.len() - 1
}
};
symbols_by_value
.entry((state_id, SymbolType::NonTerminal))
.or_default()
.push(*symbol);
}
let mut values_with_symbols = symbols_by_value.drain().collect::<Vec<_>>();
values_with_symbols.sort_unstable_by_key(|((value, kind), symbols)| {
(symbols.len(), *kind, *value, symbols[0])
});
add_line!(self, "[{}] = {},", index, values_with_symbols.len());
indent!(self);
for ((value, kind), symbols) in values_with_symbols.iter_mut() {
if *kind == SymbolType::NonTerminal {
add_line!(self, "STATE({}), {},", value, symbols.len());
} else {
add_line!(self, "ACTIONS({}), {},", value, symbols.len());
}
symbols.sort_unstable();
indent!(self);
for symbol in symbols {
add_line!(self, "{},", self.symbol_ids[symbol]);
}
dedent!(self);
}
dedent!(self);
index += 1 + values_with_symbols
.iter()
.map(|(_, symbols)| 2 + symbols.len())
.sum::<usize>();
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
add_line!(self, "static const uint32_t ts_small_parse_table_map[] = {{");
indent!(self);
for i in self.large_state_count..self.parse_table.states.len() {
add_line!(
self,
"[SMALL_STATE({})] = {},",
i,
small_state_indices[i - self.large_state_count]
);
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
self.add_parse_action_list(parse_table_entries);
}
fn add_parse_action_list(&mut self, parse_table_entries: Vec<(usize, ParseTableEntry)>) {
add_line!(self, "static const TSParseActionEntry ts_parse_actions[] = {{");
indent!(self);
for (i, entry) in parse_table_entries {
add!(
self,
" [{}] = {{.entry = {{.count = {}, .reusable = {}}}}},",
i,
entry.actions.len(),
entry.reusable
);
for action in entry.actions {
add!(self, " ");
match action {
ParseAction::Accept => add!(self, " ACCEPT_INPUT()"),
ParseAction::Recover => add!(self, "RECOVER()"),
ParseAction::ShiftExtra => add!(self, "SHIFT_EXTRA()"),
ParseAction::Shift {
state,
is_repetition,
} => {
if is_repetition {
add!(self, "SHIFT_REPEAT({})", state);
} else {
add!(self, "SHIFT({})", state);
}
}
ParseAction::Reduce {
symbol,
child_count,
dynamic_precedence,
production_id,
..
} => {
add!(self, "REDUCE({}, {}", self.symbol_ids[&symbol], child_count);
if dynamic_precedence != 0 {
add!(self, ", .dynamic_precedence = {}", dynamic_precedence);
}
if production_id != 0 {
add!(self, ", .production_id = {}", production_id);
}
add!(self, ")");
}
}
add!(self, ",")
}
add!(self, "\n");
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "");
}
fn add_parser_export(&mut self) {
let language_function_name = format!("tree_sitter_{}", self.language_name);
let external_scanner_name = format!("{}_external_scanner", language_function_name);
add_line!(self, "#ifdef __cplusplus");
add_line!(self, r#"extern "C" {{"#);
add_line!(self, "#endif");
if !self.syntax_grammar.external_tokens.is_empty() {
add_line!(self, "void *{}_create(void);", external_scanner_name);
add_line!(self, "void {}_destroy(void *);", external_scanner_name);
add_line!(
self,
"bool {}_scan(void *, TSLexer *, const bool *);",
external_scanner_name
);
add_line!(
self,
"unsigned {}_serialize(void *, char *);",
external_scanner_name
);
add_line!(
self,
"void {}_deserialize(void *, const char *, unsigned);",
external_scanner_name
);
add_line!(self, "");
}
add_line!(self, "#ifdef _WIN32");
add_line!(self, "#define extern __declspec(dllexport)");
add_line!(self, "#endif");
add_line!(self, "");
add_line!(
self,
"extern const TSLanguage *{}(void) {{",
language_function_name
);
indent!(self);
add_line!(self, "static const TSLanguage language = {{");
indent!(self);
add_line!(self, ".version = LANGUAGE_VERSION,");
// Quantities
add_line!(self, ".symbol_count = SYMBOL_COUNT,");
add_line!(self, ".alias_count = ALIAS_COUNT,");
add_line!(self, ".token_count = TOKEN_COUNT,");
add_line!(self, ".external_token_count = EXTERNAL_TOKEN_COUNT,");
add_line!(self, ".state_count = STATE_COUNT,");
add_line!(self, ".large_state_count = LARGE_STATE_COUNT,");
if self.next_abi {
add_line!(self, ".production_id_count = PRODUCTION_ID_COUNT,");
}
add_line!(self, ".field_count = FIELD_COUNT,");
add_line!(
self,
".max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH,"
);
// Parse table
add_line!(self, ".parse_table = &ts_parse_table[0][0],");
if self.large_state_count < self.parse_table.states.len() {
add_line!(
self,
".small_parse_table = ts_small_parse_table,"
);
add_line!(
self,
".small_parse_table_map = ts_small_parse_table_map,"
);
}
add_line!(self, ".parse_actions = ts_parse_actions,");
// Metadata
add_line!(self, ".symbol_names = ts_symbol_names,");
if !self.field_names.is_empty() {
add_line!(self, ".field_names = ts_field_names,");
add_line!(
self,
".field_map_slices = ts_field_map_slices,"
);
add_line!(
self,
".field_map_entries = ts_field_map_entries,"
);
}
add_line!(self, ".symbol_metadata = ts_symbol_metadata,");
add_line!(self, ".public_symbol_map = ts_symbol_map,");
add_line!(self, ".alias_map = ts_non_terminal_alias_map,");
if !self.parse_table.production_infos.is_empty() {
add_line!(
self,
".alias_sequences = &ts_alias_sequences[0][0],"
);
}
// Lexing
add_line!(self, ".lex_modes = ts_lex_modes,");
add_line!(self, ".lex_fn = ts_lex,");
if let Some(keyword_capture_token) = self.keyword_capture_token {
add_line!(self, ".keyword_lex_fn = ts_lex_keywords,");
add_line!(
self,
".keyword_capture_token = {},",
self.symbol_ids[&keyword_capture_token]
);
}
if !self.syntax_grammar.external_tokens.is_empty() {
add_line!(self, ".external_scanner = {{");
indent!(self);
add_line!(self, "&ts_external_scanner_states[0][0],");
add_line!(self, "ts_external_scanner_symbol_map,");
add_line!(self, "{}_create,", external_scanner_name);
add_line!(self, "{}_destroy,", external_scanner_name);
add_line!(self, "{}_scan,", external_scanner_name);
add_line!(self, "{}_serialize,", external_scanner_name);
add_line!(self, "{}_deserialize,", external_scanner_name);
dedent!(self);
add_line!(self, "}},");
}
dedent!(self);
add_line!(self, "}};");
add_line!(self, "return &language;");
dedent!(self);
add_line!(self, "}}");
add_line!(self, "#ifdef __cplusplus");
add_line!(self, "}}");
add_line!(self, "#endif");
}
fn get_parse_action_list_id(
&self,
entry: &ParseTableEntry,
parse_table_entries: &mut Vec<(usize, ParseTableEntry)>,
next_parse_action_list_index: &mut usize,
) -> usize {
if let Some((index, _)) = parse_table_entries.iter().find(|(_, e)| *e == *entry) {
return *index;
}
let result = *next_parse_action_list_index;
parse_table_entries.push((result, entry.clone()));
*next_parse_action_list_index += 1 + entry.actions.len();
result
}
fn get_field_map_id(
&self,
flat_field_map: &Vec<(String, FieldLocation)>,
flat_field_maps: &mut Vec<(usize, Vec<(String, FieldLocation)>)>,
next_flat_field_map_index: &mut usize,
) -> usize {
if let Some((index, _)) = flat_field_maps.iter().find(|(_, e)| *e == *flat_field_map) {
return *index;
}
let result = *next_flat_field_map_index;
flat_field_maps.push((result, flat_field_map.clone()));
*next_flat_field_map_index += flat_field_map.len();
result
}
fn external_token_id(&self, token: &ExternalToken) -> String {
format!(
"ts_external_token_{}",
self.sanitize_identifier(&token.name)
)
}
fn assign_symbol_id(&mut self, symbol: Symbol, used_identifiers: &mut HashSet<String>) {
let mut id;
if symbol == Symbol::end() {
id = "ts_builtin_sym_end".to_string();
} else {
let (name, kind) = self.metadata_for_symbol(symbol);
id = match kind {
VariableType::Auxiliary => format!("aux_sym_{}", self.sanitize_identifier(name)),
VariableType::Anonymous => format!("anon_sym_{}", self.sanitize_identifier(name)),
VariableType::Hidden | VariableType::Named => {
format!("sym_{}", self.sanitize_identifier(name))
}
};
let mut suffix_number = 1;
let mut suffix = String::new();
while used_identifiers.contains(&id) {
id.drain(id.len() - suffix.len()..);
suffix_number += 1;
suffix = suffix_number.to_string();
id += &suffix;
}
}
used_identifiers.insert(id.clone());
self.symbol_ids.insert(symbol, id);
}
fn field_id(&self, field_name: &String) -> String {
format!("field_{}", field_name)
}
fn metadata_for_symbol(&self, symbol: Symbol) -> (&str, VariableType) {
match symbol.kind {
SymbolType::End | SymbolType::EndOfNonTerminalExtra => ("end", VariableType::Hidden),
SymbolType::NonTerminal => {
let variable = &self.syntax_grammar.variables[symbol.index];
(&variable.name, variable.kind)
}
SymbolType::Terminal => {
let variable = &self.lexical_grammar.variables[symbol.index];
(&variable.name, variable.kind)
}
SymbolType::External => {
let token = &self.syntax_grammar.external_tokens[symbol.index];
(&token.name, token.kind)
}
}
}
fn sanitize_identifier(&self, name: &str) -> String {
let mut result = String::with_capacity(name.len());
for c in name.chars() {
if ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| ('0' <= c && c <= '9')
|| c == '_'
{
result.push(c);
} else {
let replacement = match c {
'~' => "TILDE",
'`' => "BQUOTE",
'!' => "BANG",
'@' => "AT",
'#' => "POUND",
'$' => "DOLLAR",
'%' => "PERCENT",
'^' => "CARET",
'&' => "AMP",
'*' => "STAR",
'(' => "LPAREN",
')' => "RPAREN",
'-' => "DASH",
'+' => "PLUS",
'=' => "EQ",
'{' => "LBRACE",
'}' => "RBRACE",
'[' => "LBRACK",
']' => "RBRACK",
'\\' => "BSLASH",
'|' => "PIPE",
':' => "COLON",
';' => "SEMI",
'"' => "DQUOTE",
'\'' => "SQUOTE",
'<' => "LT",
'>' => "GT",
',' => "COMMA",
'.' => "DOT",
'?' => "QMARK",
'/' => "SLASH",
'\n' => "LF",
'\r' => "CR",
'\t' => "TAB",
_ => continue,
};
if !result.is_empty() && !result.ends_with("_") {
result.push('_');
}
result += replacement;
}
}
result
}
fn sanitize_string(&self, name: &str) -> String {
let mut result = String::with_capacity(name.len());
for c in name.chars() {
match c {
'\"' => result += "\\\"",
'?' => result += "\\?",
'\\' => result += "\\\\",
'\u{000c}' => result += "\\f",
'\n' => result += "\\n",
'\r' => result += "\\r",
'\t' => result += "\\t",
_ => result.push(c),
}
}
result
}
fn add_character(&mut self, c: char) {
match c {
'\'' => add!(self, "'\\''"),
'\\' => add!(self, "'\\\\'"),
'\u{000c}' => add!(self, "'\\f'"),
'\n' => add!(self, "'\\n'"),
'\t' => add!(self, "'\\t'"),
'\r' => add!(self, "'\\r'"),
_ => {
if c == ' ' || c.is_ascii_graphic() {
add!(self, "'{}'", c)
} else {
add!(self, "{}", c as u32)
}
}
}
}
}
/// Returns a String of C code for the given components of a parser.
///
/// # Arguments
///
/// * `name` - A string slice containing the name of the language
/// * `parse_table` - The generated parse table for the language
/// * `main_lex_table` - The generated lexing table for the language
/// * `keyword_lex_table` - The generated keyword lexing table for the language
/// * `keyword_capture_token` - A symbol indicating which token is used
/// for keyword capture, if any.
/// * `syntax_grammar` - The syntax grammar extracted from the language's grammar
/// * `lexical_grammar` - The lexical grammar extracted from the language's grammar
/// * `default_aliases` - A map describing the global rename rules that should apply.
/// the keys are symbols that are *always* aliased in the same way, and the values
/// are the aliases that are applied to those symbols.
/// * `next_abi` - A boolean indicating whether to opt into the new, unstable parse
/// table format. This is mainly used for testing, when developing Tree-sitter itself.
pub(crate) fn render_c_code(
name: &str,
parse_table: ParseTable,
main_lex_table: LexTable,
keyword_lex_table: LexTable,
keyword_capture_token: Option<Symbol>,
syntax_grammar: SyntaxGrammar,
lexical_grammar: LexicalGrammar,
default_aliases: AliasMap,
next_abi: bool,
) -> String {
Generator {
buffer: String::new(),
indent_level: 0,
language_name: name.to_string(),
large_state_count: 0,
parse_table,
main_lex_table,
keyword_lex_table,
keyword_capture_token,
syntax_grammar,
lexical_grammar,
default_aliases,
symbol_ids: HashMap::new(),
symbol_order: HashMap::new(),
alias_ids: HashMap::new(),
symbol_map: HashMap::new(),
unique_aliases: Vec::new(),
field_names: Vec::new(),
next_abi,
}
.generate()
}
|
import 'dart:convert';
const String EVENT_NAME = 'EVENT_NAME';
const String SCANNER_STATUS = 'SCANNER_STATUS';
const String SCAN_RESULT = 'SCAN_RESULT';
enum FlutterDataWedgeEvents {
scannerStatus,
scanResult
}
class DataWedgeEvent {
String? type;
DataWedgeEvent();
factory DataWedgeEvent.fromEvent(dynamic event) {
Map eventObj = jsonDecode(event as String);
String type = eventObj[EVENT_NAME];
switch (type) {
case SCANNER_STATUS:
break;
default:
}
DataWedgeEvent dataWedgeEvent = DataWedgeEvent();
return dataWedgeEvent;
}
} |
package fr.inrae.metabohub.semantic_web
import fr.inrae.metabohub.semantic_web.node.Root
import fr.inrae.metabohub.semantic_web.configuration._
import utest.{TestSuite, Tests, test}
object SparqlQueryBuilderTest extends TestSuite {
def tests = Tests {
test("baseQuery empty Root") {
assert(SparqlQueryBuilder.baseQuery(Root()).nonEmpty)
}
test("selectQueryString empty Root") {
assert(SparqlQueryBuilder.selectQueryString(Root()).nonEmpty)
}
test("selectQueryString Root directive") {
assert(SparqlQueryBuilder.selectQueryString(Root(directives = Seq("test"))).contains("test"))
}
}
}
|
/*
* 版权所有.(c)2008-2017. 卡尔科技工作室
*/
package com.carl.sso.support.captcha.imp.cage;
import com.github.cage.Cage;
import com.github.cage.GCage;
import com.carl.sso.support.captcha.string.StringCaptchaWriter;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.OutputStream;
/**
* http://akiraly.github.io/cage/quickstart.html 验证码库
*
* @author Carl
* @date 2017/10/27
* @since 2.3.8
*/
public class CageStringCaptchaWriter extends StringCaptchaWriter {
private Cage cage = new GCage();
@Override
public void write(String text, OutputStream outputStream) throws IOException {
ImageIO.write(cage.drawImage(text),"png", outputStream);
}
}
|
/*
* Copyright 2019 Yassine AZIMANI
*
* 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 snapads4j.model.adsquads;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import snapads4j.enums.FrequencyCapIntervalEnum;
import snapads4j.enums.FrequencyCapTypeEnum;
@Getter
@Setter
@ToString
public class FrequencyCapConfig {
/**
* Number of times an ad is shown to the user in the interval
*/
@JsonProperty("frequency_cap_count")
private Integer frequencyCapCount;
/**
* Event to be frequency capped
*/
@JsonProperty("frequency_cap_type")
private FrequencyCapTypeEnum frequencyCapType;
/**
* Interval during which the frequency cap rule is applied. frequency_cap_count is reset at the
* end of the interval. (Max 30 days or 720 hours)
*/
@JsonProperty("time_interval")
private Integer timeInterval;
/**
* Unit for time_interval
*/
@JsonProperty("frequency_cap_interval")
private FrequencyCapIntervalEnum frequencyCapInterval;
} // FrequencyCapConfig
|
#include <ros/ros.h>
#include <serial/serial.h>
#include <std_msgs/String.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Float32.h>
#include <sensor_msgs/JointState.h>
#include <vector>
#include <string>
#include <math.h>
#include <numeric>
#include <time.h>
#include "blue_hardware_drivers/BLDCControllerClient.h"
namespace blue_hardware_drivers {
const unsigned int ENCODER_ANGLE_PERIOD = 1 << 14;
/* const double MAX_CURRENT = 2.8; */
const unsigned int CONTROL_LOOP_FREQ = 5000;
std::map<uint8_t, float> g_command_queue;
ros::Time last_time;
int filter_length = 10;
ros::Time get_time() {
return ros::Time::now();
}
float get_period() {
ros::Time current_time = ros::Time::now();
ros::Duration period = current_time - last_time;
last_time = current_time;
return period.toSec();
}
class SetCommand {
private:
uint8_t id_;
public:
void callback(const std_msgs::Float64::ConstPtr& msg);
SetCommand(uint8_t id);
};
void SetCommand::callback(const std_msgs::Float64::ConstPtr& msg) {
double effort_raw = msg->data;
ROS_ERROR("motor id: %d", id_);
ROS_ERROR("command: %f", effort_raw);
g_command_queue[id_] = effort_raw;
}
SetCommand::SetCommand(uint8_t id) : id_(id) {}
void initMaps(std::map<uint8_t, std::string>& joint_mapping,
std::map<uint8_t, uint16_t>& angle_mapping,
std::map<uint8_t, uint8_t>& invert_mapping,
std::map<uint8_t, uint8_t>& erevs_mapping) {
joint_mapping[15] = "base_roll_motor";
joint_mapping[11] = "right_motor1";
joint_mapping[12] = "left_motor1";
joint_mapping[14] = "right_motor2";
joint_mapping[16] = "left_motor2";
joint_mapping[21] = "right_motor3";
joint_mapping[19] = "left_motor3";
//joint_mapping[17] = "left_motor3";
//joint_mapping[13] = "base_roll_motor";
angle_mapping[15] = 13002;
angle_mapping[11] = 2164;
angle_mapping[12] = 1200;
angle_mapping[14] = 4484;
angle_mapping[16] = 2373;
angle_mapping[21] = 5899;
angle_mapping[19] = 2668;
//angle_mapping[17] = 10720;
//angle_mapping[13] = 11839;
invert_mapping[15] = 0;
invert_mapping[11] = 0;
invert_mapping[12] = 0;
invert_mapping[14] = 0;
invert_mapping[16] = 0;
invert_mapping[21] = 0;
invert_mapping[19] = 0;
//invert_mapping[17] = 1;
//invert_mapping[13] = 1;
erevs_mapping[15] = 14;
erevs_mapping[11] = 14;
erevs_mapping[12] = 14;
erevs_mapping[14] = 14;
erevs_mapping[16] = 14;
erevs_mapping[21] = 21;
erevs_mapping[19] = 21;
//erevs_mapping[17] = 14;
//erevs_mapping[13] = 14;
/* joint_mapping[1] = "left_motor"; */
/* joint_mapping[2] = "right_motor"; */
/* joint_mapping[3] = "right_motor2"; */
/* joint_mapping[4] = "left_motor2"; */
// joint_mapping[10] = "test_motor";
// angle_mapping[10] = 7568;
/* std::map<std::string, int> angles; */
/* ros::param::get("/blue_hardware_drivers/calibrations", angles); */
/* if (angles.size() < 5) { */
/* std::cerr << "did not get correct map, size " << angles.size() << "\n"; */
/* } */
/* for(std::map<std::string, int>::iterator it = angles.begin(); it != angles.end(); it++) { */
/* uint16_t angle = (uint16_t) it->second; */
/* uint8_t id = atoi(it->first.c_str()); */
/* if (id == 0) { */
/* return; */
/* } */
/* angle_mapping[id] = angle; */
/* } */
}
/*
int main(int argc, char **argv) {
ros::init(argc, argv, "jointInterface", ros::init_options::AnonymousName);
ros::NodeHandle nh;
std::map<uint8_t, std::string> joint_mapping;
std::map<uint8_t, uint16_t> angle_mapping;
std::map<uint8_t, std::vector<double> > velocity_history_mapping;
std::map<uint8_t, uint8_t> invert_mapping;
std::map<uint8_t, uint8_t> erevs_mapping;
initMaps(joint_mapping, angle_mapping, invert_mapping, erevs_mapping);
std::string port;
nh.param<std::string>("port", port, "/dev/ttyUSB0");
BLDCControllerClient device(port);
ros::Rate r(CONTROL_LOOP_FREQ);
std::map<uint8_t, std::string>::iterator it;
for (it = joint_mapping.begin(); it != joint_mapping.end(); it++) {
device.leaveBootloader(it->first, 0);
}
ros::Duration(0.5).sleep();
std::map<uint8_t, ros::Publisher> publishers;
std::map<uint8_t, ros::Publisher> publishers_curr;
std::map<uint8_t, ros::Subscriber> subscribers;
for (it = joint_mapping.begin(); it != joint_mapping.end(); it++) {
publishers[it->first] = nh.advertise<sensor_msgs::JointState>("/DOF/" + it->second + "_State", 10);
publishers_curr[it->first] = nh.advertise<std_msgs::Float32>("/DOF/" + it->second + "_Current", 10);
SetCommand *cmd = new SetCommand(it->first);
subscribers[it->first] = nh.subscribe("/DOF/" + it->second + "_Cmd", 1, &SetCommand::callback, cmd);
}
ROS_ERROR("c4");
std::map<uint8_t, double> angle_zero;
std::map<uint8_t, double> past_angle;
ros::Duration(0.2).sleep();
for (it = joint_mapping.begin(); it != joint_mapping.end(); it++) {
ROS_ERROR("c41, id: %d", it->first);
angle_zero[it->first] = device.getRotorPosition(it->first);
ROS_ERROR("c42");
velocity_history_mapping[it->first].resize(filter_length);
past_angle[it->first] = angle_zero[it->first];
}
for(std::map<uint8_t, uint16_t>::iterator it2 = angle_mapping.begin(); it2 != angle_mapping.end(); it2++) {
device.setZeroAngle(it2->first, it2->second);
device.setERevsPerMRev(it2->first, erevs_mapping[it2->first]);
device.setInvertPhases(it2->first, invert_mapping[it2->first]);
device.setCurrentControlMode(it2->first);
}
last_time = get_time(); //
float dt = 0;
int counter = 0;
while (ros::ok()) {
ros::spinOnce();
dt = get_period();
for (it = joint_mapping.begin(); it != joint_mapping.end(); it++) {
uint8_t id = it->first;
std::vector<double> v = velocity_history_mapping[id];
std::string joint_name = it->second;
double curr_angle;
if (g_command_queue.find(id) != g_command_queue.end()) {
// std::cerr << "setting duty to " << g_command_queue[id];
curr_angle = device.setCommandAndGetRotorPosition(id, g_command_queue[id]) - angle_zero[id];
// ROS_ERROR("Set Duty");
} else {
curr_angle = device.getRotorPosition(id) - angle_zero[id];
}
v[counter] = (curr_angle - past_angle[id])/dt;
past_angle[id] = curr_angle;
sensor_msgs::JointState joint_msg;
joint_msg.name = std::vector<std::string>(1, joint_name);
joint_msg.position = std::vector<double>(1, curr_angle);
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double avg_vel = sum / v.size();
joint_msg.velocity = std::vector<double>(1, avg_vel);
joint_msg.effort = std::vector<double>(1, 0.0);
publishers[id].publish(joint_msg);
std_msgs::Float32 curr_msg;
curr_msg.data = (float) 0.0;
publishers_curr[id].publish(curr_msg);
// ROS_ERROR("TRy to set duty");
}
counter ++;
counter = counter % filter_length;
g_command_queue.clear();
r.sleep();
}
return 0;
}
*/
} // namespace blue_hardware_drivers
|
#
# /etc/profile.d/doaway_aliases.sh
#
alias runawayroot='runaway root'
alias runaway.fast='runaway root file:/var/lib/doaway/hostlist'
alias castaway.fast='castaway -l /var/lib/doaway/hostlist'
alias putaway.fast='putaway -l /var/lib/doaway/hostlist'
alias syncaway.fast='syncaway -l /var/lib/doaway/hostlist'
alias walkaway.fast='walkaway -l /var/lib/doaway/hostlist'
alias getaway.fast='getaway -l /var/lib/doaway/hostlist'
alias mkhostlist.fast='mkhostlist -l /var/lib/doaway/hostlist'
alias mkmaclist.fast='mkmaclist /var/lib/dhcp/db/dhcpd.leases > /var/lib/doaway/maclist'
|
using System.Windows.Controls;
namespace FaceRecognition.Controls
{
public partial class ResultsFaceRecognitionControl : UserControl
{
public ResultsFaceRecognitionControl()
{
InitializeComponent();
}
}
}
|
using System.Threading.Tasks;
using UnityEngine;
namespace Panthea.Editor.Asset
{
public class ZipAssets: AResPipeline
{
public override Task Do()
{
Debug.Log("等待实现");
return Task.CompletedTask;
}
}
} |
#!/usr/bin/env ruby
frequency = 0
previous_frequencies = []
loop do
$stdin.each_line do |line|
if previous_frequencies.include?(frequency)
puts
puts frequency
exit 0
end
previous_frequencies << frequency
frequency += line.to_i
end
$stdout.print '.'
$stdout.flush
$stdin.rewind
end
exit 1
|
# frozen_string_literal: true
require 'find'
module Webgl
class UnityValidator
attr_reader :id, :root_path, :loader, :data, :framework, :code
def self.from_directory(root_path) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
return null_object unless root_path.present? && Dir.exist?(root_path)
if !Dir.exist?(File.join(root_path, "TemplateData"))
::Webgl.logger.info("#{root_path} is missing TemplateData folder")
return null_object
end
build_path = File.join(root_path, "Build")
if !Dir.exist?(build_path)
::Webgl.logger.info("#{root_path} is missing Build folder")
return null_object
end
loader_file = Pathname.glob(File.join(build_path, '*.loader.js')).first
if loader_file.blank?
::Webgl.logger.info("#{build_path} is missing Unity *.loader.js file")
return null_object
end
data_file = Pathname.glob(File.join(build_path, '*.data')).first
if data_file.blank?
::Webgl.logger.info("#{build_path} is missing Unity *.data file")
return null_object
end
framework_file = Pathname.glob(File.join(build_path, '*.framework.js')).first
if framework_file.blank?
::Webgl.logger.info("#{build_path} is missing Unity *.framework.js file")
return null_object
end
code_file = Pathname.glob(File.join(build_path, '*.wasm')).first
if code_file.blank?
::Webgl.logger.info("#{build_path} is missing Unity *.wasm file")
return null_object
end
id = root_path_to_noid(root_path)
new(id: id,
loader: File.join(id, 'Build', File.basename(loader_file)),
data: File.join(id, 'Build', File.basename(data_file)),
framework: File.join(id, 'Build', File.basename(framework_file)),
code: File.join(id, 'Build', File.basename(code_file)),
root_path: root_path)
end
def self.null_object
UnityValidatorNullObject.new
end
def self.root_path_to_noid(root_path)
root_path.gsub(/-webgl/, '').split('/').slice(-5, 5).join('')
end
private
def initialize(opts)
@id = opts[:id]
@loader = opts[:loader]
@data = opts[:data]
@framework = opts[:framework]
@code = opts[:code]
@root_path = opts[:root_path]
end
end
class UnityValidatorNullObject < UnityValidator
def initialize
@id = "webglnull"
@loader = nil
@data = nil
@framework = nil
@code = nil
@root_path = nil
end
end
end
|
package com.foobarust.domain.models.cart
/**
* Created by kevin on 1/19/21
*/
data class UpdateUserCartItem(
val cartItemId: String,
val amounts: Int
) |
# Bestillling av varsler gjennom brukernotifikasjon
Bruk [BrukernotifikasjonService](BrukernotifikasjonService.java) til og bestille og stoppe brukernotifikajoner async.
Kafkameldinger for å Opprete og avlutte brukernotifkajonene produseres av cronjobber i undermodulene.
## brukernotifiaksjon docks:
### Brukernotifikasjon
[doks for brukernotifikasjon](https://navikt.github.io/brukernotifikasjon-docs/)
[slack kanal #brukernotifikasjoner](https://nav-it.slack.com/archives/CR61BPH7G)
### EksternvarselKvitering
[doks for eksternvarsel kvitering](https://confluence.adeo.no/display/BOA/For+Konsumenter)
[slck kanal #team_dokumentløsninger](https://nav-it.slack.com/archives/C6W9E5GPJ)
## Intern modell
### Varsel staus:

### Varsel kvitering status:
 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.